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/session-migrate.go | migrateSessionV6ToV7 | func migrateSessionV6ToV7() {
for _, sid := range getSessionIDs() {
sV6Header, err := loadSessionV6Header(sid)
if err != nil {
if os.IsNotExist(err.ToGoError()) {
continue
}
fatalIf(err.Trace(sid), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
}
sessionVersion, e := strconv.Atoi(sV6Header.Version)
fatalIf(probe.NewError(e), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionVersion > 6 { // It is new format.
continue
}
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
// Initialize v7 header and migrate to new config.
sV7Header := &sessionV7Header{}
sV7Header.Version = "7"
sV7Header.When = sV6Header.When
sV7Header.RootPath = sV6Header.RootPath
sV7Header.GlobalBoolFlags = sV6Header.GlobalBoolFlags
sV7Header.GlobalIntFlags = sV6Header.GlobalIntFlags
sV7Header.GlobalStringFlags = sV6Header.GlobalStringFlags
sV7Header.CommandType = sV6Header.CommandType
sV7Header.CommandArgs = sV6Header.CommandArgs
sV7Header.CommandBoolFlags = sV6Header.CommandBoolFlags
sV7Header.CommandIntFlags = sV6Header.CommandIntFlags
sV7Header.CommandStringFlags = sV6Header.CommandStringFlags
sV7Header.LastCopied = sV6Header.LastCopied
sV7Header.LastRemoved = ""
sV7Header.TotalBytes = sV6Header.TotalBytes
sV7Header.TotalObjects = sV6Header.TotalObjects
qs, e := quick.NewConfig(sV7Header, nil)
fatalIf(probe.NewError(e).Trace(sid), "Unable to initialize quick config for session '7' header.")
e = qs.Save(sessionFile)
fatalIf(probe.NewError(e).Trace(sid, sessionFile), "Unable to migrate session from '6' to '7'.")
console.Println("Successfully migrated `" + sessionFile + "` from version `" + sV6Header.Version + "` to " + "`" + sV7Header.Version + "`.")
}
} | go | func migrateSessionV6ToV7() {
for _, sid := range getSessionIDs() {
sV6Header, err := loadSessionV6Header(sid)
if err != nil {
if os.IsNotExist(err.ToGoError()) {
continue
}
fatalIf(err.Trace(sid), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
}
sessionVersion, e := strconv.Atoi(sV6Header.Version)
fatalIf(probe.NewError(e), "Unable to load version `6`. Migration failed please report this issue at https://github.com/minio/mc/issues.")
if sessionVersion > 6 { // It is new format.
continue
}
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to get session file.")
// Initialize v7 header and migrate to new config.
sV7Header := &sessionV7Header{}
sV7Header.Version = "7"
sV7Header.When = sV6Header.When
sV7Header.RootPath = sV6Header.RootPath
sV7Header.GlobalBoolFlags = sV6Header.GlobalBoolFlags
sV7Header.GlobalIntFlags = sV6Header.GlobalIntFlags
sV7Header.GlobalStringFlags = sV6Header.GlobalStringFlags
sV7Header.CommandType = sV6Header.CommandType
sV7Header.CommandArgs = sV6Header.CommandArgs
sV7Header.CommandBoolFlags = sV6Header.CommandBoolFlags
sV7Header.CommandIntFlags = sV6Header.CommandIntFlags
sV7Header.CommandStringFlags = sV6Header.CommandStringFlags
sV7Header.LastCopied = sV6Header.LastCopied
sV7Header.LastRemoved = ""
sV7Header.TotalBytes = sV6Header.TotalBytes
sV7Header.TotalObjects = sV6Header.TotalObjects
qs, e := quick.NewConfig(sV7Header, nil)
fatalIf(probe.NewError(e).Trace(sid), "Unable to initialize quick config for session '7' header.")
e = qs.Save(sessionFile)
fatalIf(probe.NewError(e).Trace(sid, sessionFile), "Unable to migrate session from '6' to '7'.")
console.Println("Successfully migrated `" + sessionFile + "` from version `" + sV6Header.Version + "` to " + "`" + sV7Header.Version + "`.")
}
} | [
"func",
"migrateSessionV6ToV7",
"(",
")",
"{",
"for",
"_",
",",
"sid",
":=",
"range",
"getSessionIDs",
"(",
")",
"{",
"sV6Header",
",",
"err",
":=",
"loadSessionV6Header",
"(",
"sid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExi... | // Migrates session header version '6' to '7'. Only change is
// LastRemoved field which was added in version '7'. | [
"Migrates",
"session",
"header",
"version",
"6",
"to",
"7",
".",
"Only",
"change",
"is",
"LastRemoved",
"field",
"which",
"was",
"added",
"in",
"version",
"7",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-migrate.go#L85-L130 | train |
minio/mc | cmd/rm-main.go | mainRm | func mainRm(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'rm' cli arguments.
checkRmSyntax(ctx, encKeyDB)
// rm specific flags.
isIncomplete := ctx.Bool("incomplete")
isRecursive := ctx.Bool("recursive")
isFake := ctx.Bool("fake")
isStdin := ctx.Bool("stdin")
olderThan := ctx.String("older-than")
newerThan := ctx.String("newer-than")
isForce := ctx.Bool("force")
// Set color.
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
var rerr error
var e error
// Support multiple targets.
for _, url := range ctx.Args() {
if isRecursive {
e = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB)
} else {
e = removeSingle(url, isIncomplete, isFake, isForce, olderThan, newerThan, encKeyDB)
}
if rerr == nil {
rerr = e
}
}
if !isStdin {
return rerr
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
url := scanner.Text()
if isRecursive {
e = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB)
} else {
e = removeSingle(url, isIncomplete, isFake, isForce, olderThan, newerThan, encKeyDB)
}
if rerr == nil {
rerr = e
}
}
return rerr
} | go | func mainRm(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'rm' cli arguments.
checkRmSyntax(ctx, encKeyDB)
// rm specific flags.
isIncomplete := ctx.Bool("incomplete")
isRecursive := ctx.Bool("recursive")
isFake := ctx.Bool("fake")
isStdin := ctx.Bool("stdin")
olderThan := ctx.String("older-than")
newerThan := ctx.String("newer-than")
isForce := ctx.Bool("force")
// Set color.
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
var rerr error
var e error
// Support multiple targets.
for _, url := range ctx.Args() {
if isRecursive {
e = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB)
} else {
e = removeSingle(url, isIncomplete, isFake, isForce, olderThan, newerThan, encKeyDB)
}
if rerr == nil {
rerr = e
}
}
if !isStdin {
return rerr
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
url := scanner.Text()
if isRecursive {
e = removeRecursive(url, isIncomplete, isFake, olderThan, newerThan, encKeyDB)
} else {
e = removeSingle(url, isIncomplete, isFake, isForce, olderThan, newerThan, encKeyDB)
}
if rerr == nil {
rerr = e
}
}
return rerr
} | [
"func",
"mainRm",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"checkRmSyntax",
"(",
"ctx",
",",... | // main for rm command. | [
"main",
"for",
"rm",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/rm-main.go#L315-L369 | train |
minio/mc | pkg/colorjson/indent.go | Compact | func Compact(dst *bytes.Buffer, src []byte) error {
return compact(dst, src, false)
} | go | func Compact(dst *bytes.Buffer, src []byte) error {
return compact(dst, src, false)
} | [
"func",
"Compact",
"(",
"dst",
"*",
"bytes",
".",
"Buffer",
",",
"src",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"compact",
"(",
"dst",
",",
"src",
",",
"false",
")",
"\n",
"}"
] | // Compact appends to dst the JSON-encoded src with
// insignificant space characters elided. | [
"Compact",
"appends",
"to",
"dst",
"the",
"JSON",
"-",
"encoded",
"src",
"with",
"insignificant",
"space",
"characters",
"elided",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/indent.go#L23-L25 | train |
minio/mc | cmd/cp-url-syntax.go | checkCopySyntaxTypeA | func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL, false, keys)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(), "Source `"+srcURL+"` is not a file.")
}
} | go | func checkCopySyntaxTypeA(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL, false, keys)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(), "Source `"+srcURL+"` is not a file.")
}
} | [
"func",
"checkCopySyntaxTypeA",
"(",
"srcURLs",
"[",
"]",
"string",
",",
"tgtURL",
"string",
",",
"keys",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"{",
"if",
"len",
"(",
"srcURLs",
")",
"!=",
"1",
"{",
"fatalIf",
"(",
"errInvalidArgumen... | // checkCopySyntaxTypeA verifies if the source and target are valid file arguments. | [
"checkCopySyntaxTypeA",
"verifies",
"if",
"the",
"source",
"and",
"target",
"are",
"valid",
"file",
"arguments",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url-syntax.go#L78-L90 | train |
minio/mc | cmd/cp-url-syntax.go | checkCopySyntaxTypeB | func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL, false, keys)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(srcURL), "Source `"+srcURL+"` is not a file.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
} | go | func checkCopySyntaxTypeB(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
srcURL := srcURLs[0]
_, srcContent, err := url2Stat(srcURL, false, keys)
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
if !srcContent.Type.IsRegular() {
fatalIf(errInvalidArgument().Trace(srcURL), "Source `"+srcURL+"` is not a file.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
} | [
"func",
"checkCopySyntaxTypeB",
"(",
"srcURLs",
"[",
"]",
"string",
",",
"tgtURL",
"string",
",",
"keys",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"{",
"if",
"len",
"(",
"srcURLs",
")",
"!=",
"1",
"{",
"fatalIf",
"(",
"errInvalidArgumen... | // checkCopySyntaxTypeB verifies if the source is a valid file and target is a valid folder. | [
"checkCopySyntaxTypeB",
"verifies",
"if",
"the",
"source",
"is",
"a",
"valid",
"file",
"and",
"target",
"is",
"a",
"valid",
"folder",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url-syntax.go#L93-L112 | train |
minio/mc | cmd/cp-url-syntax.go | checkCopySyntaxTypeC | func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
for _, srcURL := range srcURLs {
c, srcContent, err := url2Stat(srcURL, false, keys)
// incomplete uploads are not necessary for copy operation, no need to verify for them.
isIncomplete := false
if err != nil {
if !isURLPrefixExists(srcURL, isIncomplete) {
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
}
// No more check here, continue to the next source url
continue
}
if srcContent.Type.IsDir() {
// Require --recursive flag if we are copying a directory
if !isRecursive {
fatalIf(errInvalidArgument().Trace(srcURL), "To copy a folder requires --recursive flag.")
}
// Check if we are going to copy a directory into itself
if isURLContains(srcURL, tgtURL, string(c.GetURL().Separator)) {
fatalIf(errInvalidArgument().Trace(), "Copying a folder into itself is not allowed.")
}
}
}
} | go | func checkCopySyntaxTypeC(srcURLs []string, tgtURL string, isRecursive bool, keys map[string][]prefixSSEPair) {
// Check source.
if len(srcURLs) != 1 {
fatalIf(errInvalidArgument().Trace(), "Invalid number of source arguments.")
}
// Check target.
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
for _, srcURL := range srcURLs {
c, srcContent, err := url2Stat(srcURL, false, keys)
// incomplete uploads are not necessary for copy operation, no need to verify for them.
isIncomplete := false
if err != nil {
if !isURLPrefixExists(srcURL, isIncomplete) {
fatalIf(err.Trace(srcURL), "Unable to stat source `"+srcURL+"`.")
}
// No more check here, continue to the next source url
continue
}
if srcContent.Type.IsDir() {
// Require --recursive flag if we are copying a directory
if !isRecursive {
fatalIf(errInvalidArgument().Trace(srcURL), "To copy a folder requires --recursive flag.")
}
// Check if we are going to copy a directory into itself
if isURLContains(srcURL, tgtURL, string(c.GetURL().Separator)) {
fatalIf(errInvalidArgument().Trace(), "Copying a folder into itself is not allowed.")
}
}
}
} | [
"func",
"checkCopySyntaxTypeC",
"(",
"srcURLs",
"[",
"]",
"string",
",",
"tgtURL",
"string",
",",
"isRecursive",
"bool",
",",
"keys",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"{",
"if",
"len",
"(",
"srcURLs",
")",
"!=",
"1",
"{",
"fat... | // checkCopySyntaxTypeC verifies if the source is a valid recursive dir and target is a valid folder. | [
"checkCopySyntaxTypeC",
"verifies",
"if",
"the",
"source",
"is",
"a",
"valid",
"recursive",
"dir",
"and",
"target",
"is",
"a",
"valid",
"folder",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url-syntax.go#L115-L153 | train |
minio/mc | cmd/cp-url-syntax.go | checkCopySyntaxTypeD | func checkCopySyntaxTypeD(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Source can be anything: file, dir, dir...
// Check target if it is a dir
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
} | go | func checkCopySyntaxTypeD(srcURLs []string, tgtURL string, keys map[string][]prefixSSEPair) {
// Source can be anything: file, dir, dir...
// Check target if it is a dir
if _, tgtContent, err := url2Stat(tgtURL, false, keys); err == nil {
if !tgtContent.Type.IsDir() {
fatalIf(errInvalidArgument().Trace(tgtURL), "Target `"+tgtURL+"` is not a folder.")
}
}
} | [
"func",
"checkCopySyntaxTypeD",
"(",
"srcURLs",
"[",
"]",
"string",
",",
"tgtURL",
"string",
",",
"keys",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"{",
"if",
"_",
",",
"tgtContent",
",",
"err",
":=",
"url2Stat",
"(",
"tgtURL",
",",
"f... | // checkCopySyntaxTypeD verifies if the source is a valid list of files and target is a valid folder. | [
"checkCopySyntaxTypeD",
"verifies",
"if",
"the",
"source",
"is",
"a",
"valid",
"list",
"of",
"files",
"and",
"target",
"is",
"a",
"valid",
"folder",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-url-syntax.go#L156-L164 | train |
minio/mc | cmd/stat-main.go | checkStatSyntax | func checkStatSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "stat", 1) // last argument is exit code
}
args := ctx.Args()
for _, arg := range args {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
}
}
// extract URLs.
URLs := ctx.Args()
isIncomplete := false
for _, url := range URLs {
_, _, err := url2Stat(url, false, encKeyDB)
if err != nil && !isURLPrefixExists(url, isIncomplete) {
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
} | go | func checkStatSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "stat", 1) // last argument is exit code
}
args := ctx.Args()
for _, arg := range args {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
}
}
// extract URLs.
URLs := ctx.Args()
isIncomplete := false
for _, url := range URLs {
_, _, err := url2Stat(url, false, encKeyDB)
if err != nil && !isURLPrefixExists(url, isIncomplete) {
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
} | [
"func",
"checkStatSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"{",
"if",
"!",
"ctx",
".",
"Args",
"(",
")",
".",
"Present",
"(",
")",
"{",
"cli",
".",
"ShowCommandHelpAn... | // checkStatSyntax - validate all the passed arguments | [
"checkStatSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/stat-main.go#L72-L93 | train |
minio/mc | cmd/stat-main.go | mainStat | func mainStat(ctx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("Name", color.New(color.Bold, color.FgCyan))
console.SetColor("Date", color.New(color.FgWhite))
console.SetColor("Size", color.New(color.FgWhite))
console.SetColor("ETag", color.New(color.FgWhite))
console.SetColor("EncryptionHeaders", color.New(color.FgWhite))
console.SetColor("Metadata", color.New(color.FgWhite))
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'stat' cli arguments.
checkStatSyntax(ctx, encKeyDB)
// Set command flags from context.
isRecursive := ctx.Bool("recursive")
args := ctx.Args()
// mimic operating system tool behavior.
if !ctx.Args().Present() {
args = []string{"."}
}
var cErr error
for _, targetURL := range args {
stats, err := statURL(targetURL, false, isRecursive, encKeyDB)
if err != nil {
fatalIf(err, "Unable to stat `"+targetURL+"`.")
}
for _, stat := range stats {
st := parseStat(stat)
if !globalJSON {
printStat(st)
} else {
console.Println(st.JSON())
}
}
}
return cErr
} | go | func mainStat(ctx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("Name", color.New(color.Bold, color.FgCyan))
console.SetColor("Date", color.New(color.FgWhite))
console.SetColor("Size", color.New(color.FgWhite))
console.SetColor("ETag", color.New(color.FgWhite))
console.SetColor("EncryptionHeaders", color.New(color.FgWhite))
console.SetColor("Metadata", color.New(color.FgWhite))
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// check 'stat' cli arguments.
checkStatSyntax(ctx, encKeyDB)
// Set command flags from context.
isRecursive := ctx.Bool("recursive")
args := ctx.Args()
// mimic operating system tool behavior.
if !ctx.Args().Present() {
args = []string{"."}
}
var cErr error
for _, targetURL := range args {
stats, err := statURL(targetURL, false, isRecursive, encKeyDB)
if err != nil {
fatalIf(err, "Unable to stat `"+targetURL+"`.")
}
for _, stat := range stats {
st := parseStat(stat)
if !globalJSON {
printStat(st)
} else {
console.Println(st.JSON())
}
}
}
return cErr
} | [
"func",
"mainStat",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"console",
".",
"SetColor",
"(",
"\"Name\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"Bold",
",",
"color",
".",
"FgCyan",
")",
")",
"\n",
"console",
".",
"SetColor",
... | // mainStat - is a handler for mc stat command | [
"mainStat",
"-",
"is",
"a",
"handler",
"for",
"mc",
"stat",
"command"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/stat-main.go#L96-L139 | train |
minio/mc | cmd/scan-bar.go | fixateScanBar | func fixateScanBar(text string, width int) string {
if len([]rune(text)) > width {
// Trim text to fit within the screen
trimSize := len([]rune(text)) - width + 3 //"..."
if trimSize < len([]rune(text)) {
text = "..." + text[trimSize:]
}
} else {
text += strings.Repeat(" ", width-len([]rune(text)))
}
return text
} | go | func fixateScanBar(text string, width int) string {
if len([]rune(text)) > width {
// Trim text to fit within the screen
trimSize := len([]rune(text)) - width + 3 //"..."
if trimSize < len([]rune(text)) {
text = "..." + text[trimSize:]
}
} else {
text += strings.Repeat(" ", width-len([]rune(text)))
}
return text
} | [
"func",
"fixateScanBar",
"(",
"text",
"string",
",",
"width",
"int",
")",
"string",
"{",
"if",
"len",
"(",
"[",
"]",
"rune",
"(",
"text",
")",
")",
">",
"width",
"{",
"trimSize",
":=",
"len",
"(",
"[",
"]",
"rune",
"(",
"text",
")",
")",
"-",
"... | // fixateScanBar truncates or stretches text to fit within the terminal size. | [
"fixateScanBar",
"truncates",
"or",
"stretches",
"text",
"to",
"fit",
"within",
"the",
"terminal",
"size",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/scan-bar.go#L28-L39 | train |
minio/mc | cmd/scan-bar.go | scanBarFactory | func scanBarFactory() scanBarFunc {
fileCount := 0
// Cursor animate channel.
cursorCh := cursorAnimate()
return func(source string) {
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), <-cursorCh)
source = fixateScanBar(source, globalTermWidth-len([]rune(scanPrefix)))
barText := scanPrefix + source
console.PrintC("\r" + barText + "\r")
fileCount++
}
} | go | func scanBarFactory() scanBarFunc {
fileCount := 0
// Cursor animate channel.
cursorCh := cursorAnimate()
return func(source string) {
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), <-cursorCh)
source = fixateScanBar(source, globalTermWidth-len([]rune(scanPrefix)))
barText := scanPrefix + source
console.PrintC("\r" + barText + "\r")
fileCount++
}
} | [
"func",
"scanBarFactory",
"(",
")",
"scanBarFunc",
"{",
"fileCount",
":=",
"0",
"\n",
"cursorCh",
":=",
"cursorAnimate",
"(",
")",
"\n",
"return",
"func",
"(",
"source",
"string",
")",
"{",
"scanPrefix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"[%s] %s \"",
",... | // scanBarFactory returns a progress bar function to report URL scanning. | [
"scanBarFactory",
"returns",
"a",
"progress",
"bar",
"function",
"to",
"report",
"URL",
"scanning",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/scan-bar.go#L45-L57 | train |
minio/mc | cmd/session.go | createSessionDir | func createSessionDir() *probe.Error {
sessionDir, err := getSessionDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(sessionDir, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | go | func createSessionDir() *probe.Error {
sessionDir, err := getSessionDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(sessionDir, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"createSessionDir",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"sessionDir",
",",
"err",
":=",
"getSessionDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
".",
"Trace",
"(",
")",
"\n",
"}",
"\n",
"if",
"e",
":=",
"os",
... | // createSessionDir - create session directory. | [
"createSessionDir",
"-",
"create",
"session",
"directory",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L40-L50 | train |
minio/mc | cmd/session.go | getSessionDir | func getSessionDir() (string, *probe.Error) {
configDir, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
sessionDir := filepath.Join(configDir, globalSessionDir)
return sessionDir, nil
} | go | func getSessionDir() (string, *probe.Error) {
configDir, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
sessionDir := filepath.Join(configDir, globalSessionDir)
return sessionDir, nil
} | [
"func",
"getSessionDir",
"(",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"configDir",
",",
"err",
":=",
"getMcConfigDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
".",
"Trace",
"(",
")",
"\n",... | // getSessionDir - get session directory. | [
"getSessionDir",
"-",
"get",
"session",
"directory",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L53-L61 | train |
minio/mc | cmd/session.go | isSessionDirExists | func isSessionDirExists() bool {
sessionDir, err := getSessionDir()
fatalIf(err.Trace(), "Unable to determine session folder.")
if _, e := os.Stat(sessionDir); e != nil {
return false
}
return true
} | go | func isSessionDirExists() bool {
sessionDir, err := getSessionDir()
fatalIf(err.Trace(), "Unable to determine session folder.")
if _, e := os.Stat(sessionDir); e != nil {
return false
}
return true
} | [
"func",
"isSessionDirExists",
"(",
")",
"bool",
"{",
"sessionDir",
",",
"err",
":=",
"getSessionDir",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
")",
",",
"\"Unable to determine session folder.\"",
")",
"\n",
"if",
"_",
",",
"e",
":=",
"os",... | // isSessionDirExists - verify if session directory exists. | [
"isSessionDirExists",
"-",
"verify",
"if",
"session",
"directory",
"exists",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L64-L72 | train |
minio/mc | cmd/session.go | getSessionFile | func getSessionFile(sid string) (string, *probe.Error) {
sessionDir, err := getSessionDir()
if err != nil {
return "", err.Trace()
}
sessionFile := filepath.Join(sessionDir, sid+".json")
return sessionFile, nil
} | go | func getSessionFile(sid string) (string, *probe.Error) {
sessionDir, err := getSessionDir()
if err != nil {
return "", err.Trace()
}
sessionFile := filepath.Join(sessionDir, sid+".json")
return sessionFile, nil
} | [
"func",
"getSessionFile",
"(",
"sid",
"string",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"sessionDir",
",",
"err",
":=",
"getSessionDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
".",
"Trace",... | // getSessionFile - get current session file. | [
"getSessionFile",
"-",
"get",
"current",
"session",
"file",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L75-L83 | train |
minio/mc | cmd/session.go | isSessionExists | func isSessionExists(sid string) bool {
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to determine session filename for `"+sid+"`.")
if _, e := os.Stat(sessionFile); e != nil {
return false
}
return true // Session exists.
} | go | func isSessionExists(sid string) bool {
sessionFile, err := getSessionFile(sid)
fatalIf(err.Trace(sid), "Unable to determine session filename for `"+sid+"`.")
if _, e := os.Stat(sessionFile); e != nil {
return false
}
return true // Session exists.
} | [
"func",
"isSessionExists",
"(",
"sid",
"string",
")",
"bool",
"{",
"sessionFile",
",",
"err",
":=",
"getSessionFile",
"(",
"sid",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
"sid",
")",
",",
"\"Unable to determine session filename for `\"",
"+",
"sid"... | // isSessionExists verifies if given session exists. | [
"isSessionExists",
"verifies",
"if",
"given",
"session",
"exists",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L86-L95 | train |
minio/mc | cmd/session.go | getSessionDataFile | func getSessionDataFile(sid string) (string, *probe.Error) {
sessionDir, err := getSessionDir()
if err != nil {
return "", err.Trace()
}
sessionDataFile := filepath.Join(sessionDir, sid+".data")
return sessionDataFile, nil
} | go | func getSessionDataFile(sid string) (string, *probe.Error) {
sessionDir, err := getSessionDir()
if err != nil {
return "", err.Trace()
}
sessionDataFile := filepath.Join(sessionDir, sid+".data")
return sessionDataFile, nil
} | [
"func",
"getSessionDataFile",
"(",
"sid",
"string",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"sessionDir",
",",
"err",
":=",
"getSessionDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
".",
"Tra... | // getSessionDataFile - get session data file for a given session. | [
"getSessionDataFile",
"-",
"get",
"session",
"data",
"file",
"for",
"a",
"given",
"session",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L98-L106 | train |
minio/mc | cmd/session.go | getSessionIDs | func getSessionIDs() (sids []string) {
sessionDir, err := getSessionDir()
fatalIf(err.Trace(), "Unable to access session folder.")
sessionList, e := filepath.Glob(sessionDir + "/*.json")
fatalIf(probe.NewError(e), "Unable to access session folder `"+sessionDir+"`.")
for _, path := range sessionList {
sids = append(sids, strings.TrimSuffix(filepath.Base(path), ".json"))
}
return sids
} | go | func getSessionIDs() (sids []string) {
sessionDir, err := getSessionDir()
fatalIf(err.Trace(), "Unable to access session folder.")
sessionList, e := filepath.Glob(sessionDir + "/*.json")
fatalIf(probe.NewError(e), "Unable to access session folder `"+sessionDir+"`.")
for _, path := range sessionList {
sids = append(sids, strings.TrimSuffix(filepath.Base(path), ".json"))
}
return sids
} | [
"func",
"getSessionIDs",
"(",
")",
"(",
"sids",
"[",
"]",
"string",
")",
"{",
"sessionDir",
",",
"err",
":=",
"getSessionDir",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
")",
",",
"\"Unable to access session folder.\"",
")",
"\n",
"sessionLi... | // getSessionIDs - get all active sessions. | [
"getSessionIDs",
"-",
"get",
"all",
"active",
"sessions",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L109-L120 | train |
minio/mc | cmd/session.go | removeSessionFile | func removeSessionFile(sid string) {
sessionFile, err := getSessionFile(sid)
if err != nil {
return
}
os.Remove(sessionFile)
} | go | func removeSessionFile(sid string) {
sessionFile, err := getSessionFile(sid)
if err != nil {
return
}
os.Remove(sessionFile)
} | [
"func",
"removeSessionFile",
"(",
"sid",
"string",
")",
"{",
"sessionFile",
",",
"err",
":=",
"getSessionFile",
"(",
"sid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"os",
".",
"Remove",
"(",
"sessionFile",
")",
"\n",
"}"
] | // removeSessionFile - remove the session file, ending with .json | [
"removeSessionFile",
"-",
"remove",
"the",
"session",
"file",
"ending",
"with",
".",
"json"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L123-L129 | train |
minio/mc | cmd/session.go | removeSessionDataFile | func removeSessionDataFile(sid string) {
dataFile, err := getSessionDataFile(sid)
if err != nil {
return
}
os.Remove(dataFile)
} | go | func removeSessionDataFile(sid string) {
dataFile, err := getSessionDataFile(sid)
if err != nil {
return
}
os.Remove(dataFile)
} | [
"func",
"removeSessionDataFile",
"(",
"sid",
"string",
")",
"{",
"dataFile",
",",
"err",
":=",
"getSessionDataFile",
"(",
"sid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"os",
".",
"Remove",
"(",
"dataFile",
")",
"\n",
"}"
] | // removeSessionDataFile - remove the session data file, ending with .data | [
"removeSessionDataFile",
"-",
"remove",
"the",
"session",
"data",
"file",
"ending",
"with",
".",
"data"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session.go#L132-L138 | train |
minio/mc | cmd/runtime-checks.go | checkGoVersion | func checkGoVersion() {
runtimeVersion := runtime.Version()
// Checking version is always successful with go tip
if strings.HasPrefix(runtimeVersion, "devel") {
return
}
// Parsing golang version
curVersion, e := version.NewVersion(runtimeVersion[2:])
if e != nil {
console.Fatalln("Unable to determine current go version.", e)
}
// Prepare version constraint.
constraints, e := version.NewConstraint(minGoVersion)
if e != nil {
console.Fatalln("Unable to check go version.")
}
// Check for minimum version.
if !constraints.Check(curVersion) {
console.Fatalln(fmt.Sprintf("Please recompile MinIO with Golang version %s.", minGoVersion))
}
} | go | func checkGoVersion() {
runtimeVersion := runtime.Version()
// Checking version is always successful with go tip
if strings.HasPrefix(runtimeVersion, "devel") {
return
}
// Parsing golang version
curVersion, e := version.NewVersion(runtimeVersion[2:])
if e != nil {
console.Fatalln("Unable to determine current go version.", e)
}
// Prepare version constraint.
constraints, e := version.NewConstraint(minGoVersion)
if e != nil {
console.Fatalln("Unable to check go version.")
}
// Check for minimum version.
if !constraints.Check(curVersion) {
console.Fatalln(fmt.Sprintf("Please recompile MinIO with Golang version %s.", minGoVersion))
}
} | [
"func",
"checkGoVersion",
"(",
")",
"{",
"runtimeVersion",
":=",
"runtime",
".",
"Version",
"(",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"runtimeVersion",
",",
"\"devel\"",
")",
"{",
"return",
"\n",
"}",
"\n",
"curVersion",
",",
"e",
":=",
"ve... | // check if minimum Go version is met. | [
"check",
"if",
"minimum",
"Go",
"version",
"is",
"met",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/runtime-checks.go#L29-L53 | train |
minio/mc | cmd/admin-user-enable.go | checkAdminUserEnableSyntax | func checkAdminUserEnableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "enable", 1) // last argument is exit code
}
} | go | func checkAdminUserEnableSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "enable", 1) // last argument is exit code
}
} | [
"func",
"checkAdminUserEnableSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"2",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"enable\"",
",",
"1",
")",
"\n",
"}"... | // checkAdminUserEnableSyntax - validate all the passed arguments | [
"checkAdminUserEnableSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-enable.go#L49-L53 | train |
minio/mc | cmd/config-migrate.go | migrateConfig | func migrateConfig() {
// Migrate config V1 to V101
migrateConfigV1ToV101()
// Migrate config V101 to V2
migrateConfigV101ToV2()
// Migrate config V2 to V3
migrateConfigV2ToV3()
// Migrate config V3 to V4
migrateConfigV3ToV4()
// Migrate config V4 to V5
migrateConfigV4ToV5()
// Migrate config V5 to V6
migrateConfigV5ToV6()
// Migrate config V6 to V7
migrateConfigV6ToV7()
// Migrate config V7 to V8
migrateConfigV7ToV8()
// Migrate config V8 to V9
migrateConfigV8ToV9()
} | go | func migrateConfig() {
// Migrate config V1 to V101
migrateConfigV1ToV101()
// Migrate config V101 to V2
migrateConfigV101ToV2()
// Migrate config V2 to V3
migrateConfigV2ToV3()
// Migrate config V3 to V4
migrateConfigV3ToV4()
// Migrate config V4 to V5
migrateConfigV4ToV5()
// Migrate config V5 to V6
migrateConfigV5ToV6()
// Migrate config V6 to V7
migrateConfigV6ToV7()
// Migrate config V7 to V8
migrateConfigV7ToV8()
// Migrate config V8 to V9
migrateConfigV8ToV9()
} | [
"func",
"migrateConfig",
"(",
")",
"{",
"migrateConfigV1ToV101",
"(",
")",
"\n",
"migrateConfigV101ToV2",
"(",
")",
"\n",
"migrateConfigV2ToV3",
"(",
")",
"\n",
"migrateConfigV3ToV4",
"(",
")",
"\n",
"migrateConfigV4ToV5",
"(",
")",
"\n",
"migrateConfigV5ToV6",
"(... | // migrate config files from the any older version to the latest. | [
"migrate",
"config",
"files",
"from",
"the",
"any",
"older",
"version",
"to",
"the",
"latest",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L29-L48 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV1ToV101 | func migrateConfigV1ToV101() {
if !isMcConfigExists() {
return
}
mcCfgV1, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV1())
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
// If loaded config version does not match 1.0.0, we do nothing.
if mcCfgV1.Version() != "1.0.0" {
return
}
// 1.0.1 is compatible to 1.0.0. We are just adding new entries.
cfgV101 := newConfigV101()
// Copy aliases.
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
cfgV101.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
cfgV101.Hosts[k] = hostConfigV101{
AccessKeyID: hostCfgV1.AccessKeyID,
SecretAccessKey: hostCfgV1.SecretAccessKey,
}
}
// Example localhost entry.
if _, ok := cfgV101.Hosts["localhost:*"]; !ok {
cfgV101.Hosts["localhost:*"] = hostConfigV101{}
}
// Example loopback IP entry.
if _, ok := cfgV101.Hosts["127.0.0.1:*"]; !ok {
cfgV101.Hosts["127.0.0.1:*"] = hostConfigV101{}
}
// Example AWS entry.
// Look for glob string (not glob match). We used to support glob based key matching earlier.
if _, ok := cfgV101.Hosts["*.s3*.amazonaws.com"]; !ok {
cfgV101.Hosts["*.s3*.amazonaws.com"] = hostConfigV101{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
}
}
// Save the new config back to the disk.
mcCfgV101, e := quick.NewConfig(cfgV101, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `1.0.1`.")
e = mcCfgV101.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `1.0.1`.")
console.Infof("Successfully migrated %s from version `1.0.0` to version `1.0.1`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV1ToV101() {
if !isMcConfigExists() {
return
}
mcCfgV1, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV1())
fatalIf(probe.NewError(e), "Unable to load config version `1`.")
// If loaded config version does not match 1.0.0, we do nothing.
if mcCfgV1.Version() != "1.0.0" {
return
}
// 1.0.1 is compatible to 1.0.0. We are just adding new entries.
cfgV101 := newConfigV101()
// Copy aliases.
for k, v := range mcCfgV1.Data().(*configV1).Aliases {
cfgV101.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV1 := range mcCfgV1.Data().(*configV1).Hosts {
cfgV101.Hosts[k] = hostConfigV101{
AccessKeyID: hostCfgV1.AccessKeyID,
SecretAccessKey: hostCfgV1.SecretAccessKey,
}
}
// Example localhost entry.
if _, ok := cfgV101.Hosts["localhost:*"]; !ok {
cfgV101.Hosts["localhost:*"] = hostConfigV101{}
}
// Example loopback IP entry.
if _, ok := cfgV101.Hosts["127.0.0.1:*"]; !ok {
cfgV101.Hosts["127.0.0.1:*"] = hostConfigV101{}
}
// Example AWS entry.
// Look for glob string (not glob match). We used to support glob based key matching earlier.
if _, ok := cfgV101.Hosts["*.s3*.amazonaws.com"]; !ok {
cfgV101.Hosts["*.s3*.amazonaws.com"] = hostConfigV101{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
}
}
// Save the new config back to the disk.
mcCfgV101, e := quick.NewConfig(cfgV101, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `1.0.1`.")
e = mcCfgV101.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `1.0.1`.")
console.Infof("Successfully migrated %s from version `1.0.0` to version `1.0.1`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV1ToV101",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV1",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV1",
"(",
")"... | // Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back. | [
"Migrate",
"from",
"config",
"version",
"1",
".",
"0",
"to",
"1",
".",
"0",
".",
"1",
".",
"Populate",
"example",
"entries",
"and",
"save",
"it",
"back",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L51-L105 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV101ToV2 | func migrateConfigV101ToV2() {
if !isMcConfigExists() {
return
}
mcCfgV101, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV101())
fatalIf(probe.NewError(e), "Unable to load config version `1.0.1`.")
// update to newer version
if mcCfgV101.Version() != "1.0.1" {
return
}
cfgV2 := newConfigV2()
// Copy aliases.
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
cfgV2.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
cfgV2.Hosts[k] = hostConfigV2{
AccessKeyID: hostCfgV101.AccessKeyID,
SecretAccessKey: hostCfgV101.SecretAccessKey,
}
}
mcCfgV2, e := quick.NewConfig(cfgV2, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `2`.")
e = mcCfgV2.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `2`.")
console.Infof("Successfully migrated %s from version `1.0.1` to version `2`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV101ToV2() {
if !isMcConfigExists() {
return
}
mcCfgV101, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV101())
fatalIf(probe.NewError(e), "Unable to load config version `1.0.1`.")
// update to newer version
if mcCfgV101.Version() != "1.0.1" {
return
}
cfgV2 := newConfigV2()
// Copy aliases.
for k, v := range mcCfgV101.Data().(*configV101).Aliases {
cfgV2.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV101 := range mcCfgV101.Data().(*configV101).Hosts {
cfgV2.Hosts[k] = hostConfigV2{
AccessKeyID: hostCfgV101.AccessKeyID,
SecretAccessKey: hostCfgV101.SecretAccessKey,
}
}
mcCfgV2, e := quick.NewConfig(cfgV2, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `2`.")
e = mcCfgV2.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `2`.")
console.Infof("Successfully migrated %s from version `1.0.1` to version `2`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV101ToV2",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV101",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV101",
"(",
... | // Migrate from config `1.0.1` to `2`. Drop semantic versioning and move to integer versioning. No other changes. | [
"Migrate",
"from",
"config",
"1",
".",
"0",
".",
"1",
"to",
"2",
".",
"Drop",
"semantic",
"versioning",
"and",
"move",
"to",
"integer",
"versioning",
".",
"No",
"other",
"changes",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L108-L142 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV2ToV3 | func migrateConfigV2ToV3() {
if !isMcConfigExists() {
return
}
mcCfgV2, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV2())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV2.Version() != "2" {
return
}
cfgV3 := newConfigV3()
// Copy aliases.
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
cfgV3.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
// New hostConfV3 uses struct json tags.
cfgV3.Hosts[k] = hostConfigV3{
AccessKeyID: hostCfgV2.AccessKeyID,
SecretAccessKey: hostCfgV2.SecretAccessKey,
}
}
mcNewCfgV3, e := quick.NewConfig(cfgV3, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.")
e = mcNewCfgV3.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `3`.")
console.Infof("Successfully migrated %s from version `2` to version `3`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV2ToV3() {
if !isMcConfigExists() {
return
}
mcCfgV2, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV2())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV2.Version() != "2" {
return
}
cfgV3 := newConfigV3()
// Copy aliases.
for k, v := range mcCfgV2.Data().(*configV2).Aliases {
cfgV3.Aliases[k] = v
}
// Copy hosts.
for k, hostCfgV2 := range mcCfgV2.Data().(*configV2).Hosts {
// New hostConfV3 uses struct json tags.
cfgV3.Hosts[k] = hostConfigV3{
AccessKeyID: hostCfgV2.AccessKeyID,
SecretAccessKey: hostCfgV2.SecretAccessKey,
}
}
mcNewCfgV3, e := quick.NewConfig(cfgV3, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `3`.")
e = mcNewCfgV3.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `3`.")
console.Infof("Successfully migrated %s from version `2` to version `3`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV2ToV3",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV2",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV2",
"(",
")",
... | // Migrate from config `2` to `3`. Use `-` separated names for
// hostConfig using struct json tags. | [
"Migrate",
"from",
"config",
"2",
"to",
"3",
".",
"Use",
"-",
"separated",
"names",
"for",
"hostConfig",
"using",
"struct",
"json",
"tags",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L146-L182 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV3ToV4 | func migrateConfigV3ToV4() {
if !isMcConfigExists() {
return
}
mcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV3())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV3.Version() != "3" {
return
}
cfgV4 := newConfigV4()
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
cfgV4.Aliases[k] = v
}
// New hostConfig has API signature. All older entries were V4
// only. So it is safe to assume V4 as default for all older
// entries.
// HostConfigV4 als uses JavaScript naming notation for struct JSON tags.
for host, hostCfgV3 := range mcCfgV3.Data().(*configV3).Hosts {
cfgV4.Hosts[host] = hostConfigV4{
AccessKeyID: hostCfgV3.AccessKeyID,
SecretAccessKey: hostCfgV3.SecretAccessKey,
Signature: "v4",
}
}
mcNewCfgV4, e := quick.NewConfig(cfgV4, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `4`.")
e = mcNewCfgV4.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `4`.")
console.Infof("Successfully migrated %s from version `3` to version `4`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV3ToV4() {
if !isMcConfigExists() {
return
}
mcCfgV3, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV3())
fatalIf(probe.NewError(e), "Unable to load mc config V2.")
// update to newer version
if mcCfgV3.Version() != "3" {
return
}
cfgV4 := newConfigV4()
for k, v := range mcCfgV3.Data().(*configV3).Aliases {
cfgV4.Aliases[k] = v
}
// New hostConfig has API signature. All older entries were V4
// only. So it is safe to assume V4 as default for all older
// entries.
// HostConfigV4 als uses JavaScript naming notation for struct JSON tags.
for host, hostCfgV3 := range mcCfgV3.Data().(*configV3).Hosts {
cfgV4.Hosts[host] = hostConfigV4{
AccessKeyID: hostCfgV3.AccessKeyID,
SecretAccessKey: hostCfgV3.SecretAccessKey,
Signature: "v4",
}
}
mcNewCfgV4, e := quick.NewConfig(cfgV4, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `4`.")
e = mcNewCfgV4.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `4`.")
console.Infof("Successfully migrated %s from version `3` to version `4`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV3ToV4",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV3",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV3",
"(",
")",
... | // Migrate from config version `3` to `4`. Introduce API Signature
// field in host config. Also Use JavaScript notation for field names. | [
"Migrate",
"from",
"config",
"version",
"3",
"to",
"4",
".",
"Introduce",
"API",
"Signature",
"field",
"in",
"host",
"config",
".",
"Also",
"Use",
"JavaScript",
"notation",
"for",
"field",
"names",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L186-L222 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV4ToV5 | func migrateConfigV4ToV5() {
if !isMcConfigExists() {
return
}
mcCfgV4, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV4())
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
// update to newer version
if mcCfgV4.Version() != "4" {
return
}
cfgV5 := newConfigV5()
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
cfgV5.Aliases[k] = v
}
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
cfgV5.Hosts[host] = hostConfigV5{
AccessKeyID: hostCfgV4.AccessKeyID,
SecretAccessKey: hostCfgV4.SecretAccessKey,
API: "v4", // Rename from .Signature to .API
}
}
mcNewCfgV5, e := quick.NewConfig(cfgV5, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `5`.")
e = mcNewCfgV5.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `5`.")
console.Infof("Successfully migrated %s from version `4` to version `5`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV4ToV5() {
if !isMcConfigExists() {
return
}
mcCfgV4, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV4())
fatalIf(probe.NewError(e), "Unable to load mc config V4.")
// update to newer version
if mcCfgV4.Version() != "4" {
return
}
cfgV5 := newConfigV5()
for k, v := range mcCfgV4.Data().(*configV4).Aliases {
cfgV5.Aliases[k] = v
}
for host, hostCfgV4 := range mcCfgV4.Data().(*configV4).Hosts {
cfgV5.Hosts[host] = hostConfigV5{
AccessKeyID: hostCfgV4.AccessKeyID,
SecretAccessKey: hostCfgV4.SecretAccessKey,
API: "v4", // Rename from .Signature to .API
}
}
mcNewCfgV5, e := quick.NewConfig(cfgV5, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `5`.")
e = mcNewCfgV5.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `5`.")
console.Infof("Successfully migrated %s from version `4` to version `5`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV4ToV5",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV4",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV4",
"(",
")",
... | // Migrate config version `4` to `5`. Rename hostConfigV4.Signature -> hostConfigV5.API. | [
"Migrate",
"config",
"version",
"4",
"to",
"5",
".",
"Rename",
"hostConfigV4",
".",
"Signature",
"-",
">",
"hostConfigV5",
".",
"API",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L225-L256 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV5ToV6 | func migrateConfigV5ToV6() {
if !isMcConfigExists() {
return
}
mcCfgV5, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV5())
fatalIf(probe.NewError(e), "Unable to load mc config V5.")
// update to newer version
if mcCfgV5.Version() != "5" {
return
}
cfgV6 := newConfigV6()
// Add new Google Cloud Storage alias.
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
cfgV6.Aliases[k] = v
}
// Add defaults.
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
API: "S3v4",
}
cfgV6.Hosts["*storage.googleapis.com"] = hostConfigV6{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
API: "S3v2",
}
for host, hostCfgV5 := range mcCfgV5.Data().(*configV5).Hosts {
// Find any matching s3 entry and copy keys from it to newer generalized glob entry.
if strings.Contains(host, "s3") {
if (hostCfgV5.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE") ||
(hostCfgV5.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE") ||
hostCfgV5.AccessKeyID == "" ||
hostCfgV5.SecretAccessKey == "" {
continue // Skip defaults.
}
// Now we have real keys set by the user. Copy
// them over to newer glob rule.
// Original host entry has "." in the glob rule.
host = "*s3*amazonaws.com" // Use this glob entry.
}
cfgV6.Hosts[host] = hostConfigV6{
AccessKeyID: hostCfgV5.AccessKeyID,
SecretAccessKey: hostCfgV5.SecretAccessKey,
API: hostCfgV5.API,
}
}
mcNewCfgV6, e := quick.NewConfig(cfgV6, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `6`.")
e = mcNewCfgV6.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `6`.")
console.Infof("Successfully migrated %s from version `5` to version `6`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV5ToV6() {
if !isMcConfigExists() {
return
}
mcCfgV5, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV5())
fatalIf(probe.NewError(e), "Unable to load mc config V5.")
// update to newer version
if mcCfgV5.Version() != "5" {
return
}
cfgV6 := newConfigV6()
// Add new Google Cloud Storage alias.
cfgV6.Aliases["gcs"] = "https://storage.googleapis.com"
for k, v := range mcCfgV5.Data().(*configV5).Aliases {
cfgV6.Aliases[k] = v
}
// Add defaults.
cfgV6.Hosts["*s3*amazonaws.com"] = hostConfigV6{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
API: "S3v4",
}
cfgV6.Hosts["*storage.googleapis.com"] = hostConfigV6{
AccessKeyID: "YOUR-ACCESS-KEY-ID-HERE",
SecretAccessKey: "YOUR-SECRET-ACCESS-KEY-HERE",
API: "S3v2",
}
for host, hostCfgV5 := range mcCfgV5.Data().(*configV5).Hosts {
// Find any matching s3 entry and copy keys from it to newer generalized glob entry.
if strings.Contains(host, "s3") {
if (hostCfgV5.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE") ||
(hostCfgV5.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE") ||
hostCfgV5.AccessKeyID == "" ||
hostCfgV5.SecretAccessKey == "" {
continue // Skip defaults.
}
// Now we have real keys set by the user. Copy
// them over to newer glob rule.
// Original host entry has "." in the glob rule.
host = "*s3*amazonaws.com" // Use this glob entry.
}
cfgV6.Hosts[host] = hostConfigV6{
AccessKeyID: hostCfgV5.AccessKeyID,
SecretAccessKey: hostCfgV5.SecretAccessKey,
API: hostCfgV5.API,
}
}
mcNewCfgV6, e := quick.NewConfig(cfgV6, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `6`.")
e = mcNewCfgV6.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `6`.")
console.Infof("Successfully migrated %s from version `5` to version `6`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV5ToV6",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV5",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV5",
"(",
")",
... | // Migrate config version `5` to `6`. Add google cloud storage servers
// to host config. Also remove "." from s3 aws glob rule. | [
"Migrate",
"config",
"version",
"5",
"to",
"6",
".",
"Add",
"google",
"cloud",
"storage",
"servers",
"to",
"host",
"config",
".",
"Also",
"remove",
".",
"from",
"s3",
"aws",
"glob",
"rule",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L260-L322 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV6ToV7 | func migrateConfigV6ToV7() {
if !isMcConfigExists() {
return
}
mcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
fatalIf(probe.NewError(e), "Unable to load mc config V6.")
if mcCfgV6.Version() != "6" {
return
}
cfgV7 := newConfigV7()
aliasIndex := 0
// old Aliases.
oldAliases := mcCfgV6.Data().(*configV6).Aliases
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
// Look through old aliases, if found any matching save those entries.
for aliasName, aliasedHost := range oldAliases {
if aliasedHost == host {
cfgV7.Hosts[aliasName] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
continue
}
}
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
hostCfgV6.AccessKeyID == "" ||
hostCfgV6.SecretAccessKey == "" {
// Ignore default entries. configV7.loadDefaults() will re-insert them back.
} else if host == "https://s3.amazonaws.com" {
// Only one entry can exist for "s3" domain.
cfgV7.Hosts["s3"] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else if host == "https://storage.googleapis.com" {
// Only one entry can exist for "gcs" domain.
cfgV7.Hosts["gcs"] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else {
// Assign a generic "cloud1", cloud2..." key
// for all other entries that has valid keys set.
alias := fmt.Sprintf("cloud%d", aliasIndex)
aliasIndex++
cfgV7.Hosts[alias] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
}
}
// Load default settings.
cfgV7.loadDefaults()
mcNewCfgV7, e := quick.NewConfig(cfgV7, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `7`.")
e = mcNewCfgV7.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `7`.")
console.Infof("Successfully migrated %s from version `6` to version `7`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV6ToV7() {
if !isMcConfigExists() {
return
}
mcCfgV6, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV6())
fatalIf(probe.NewError(e), "Unable to load mc config V6.")
if mcCfgV6.Version() != "6" {
return
}
cfgV7 := newConfigV7()
aliasIndex := 0
// old Aliases.
oldAliases := mcCfgV6.Data().(*configV6).Aliases
// We dropped alias support in v7. We only need to migrate host configs.
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
// Look through old aliases, if found any matching save those entries.
for aliasName, aliasedHost := range oldAliases {
if aliasedHost == host {
cfgV7.Hosts[aliasName] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
continue
}
}
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
hostCfgV6.AccessKeyID == "" ||
hostCfgV6.SecretAccessKey == "" {
// Ignore default entries. configV7.loadDefaults() will re-insert them back.
} else if host == "https://s3.amazonaws.com" {
// Only one entry can exist for "s3" domain.
cfgV7.Hosts["s3"] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else if host == "https://storage.googleapis.com" {
// Only one entry can exist for "gcs" domain.
cfgV7.Hosts["gcs"] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
} else {
// Assign a generic "cloud1", cloud2..." key
// for all other entries that has valid keys set.
alias := fmt.Sprintf("cloud%d", aliasIndex)
aliasIndex++
cfgV7.Hosts[alias] = hostConfigV7{
URL: host,
AccessKey: hostCfgV6.AccessKeyID,
SecretKey: hostCfgV6.SecretAccessKey,
API: hostCfgV6.API,
}
}
}
// Load default settings.
cfgV7.loadDefaults()
mcNewCfgV7, e := quick.NewConfig(cfgV7, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `7`.")
e = mcNewCfgV7.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `7`.")
console.Infof("Successfully migrated %s from version `6` to version `7`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV6ToV7",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV6",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV6",
"(",
")",
... | // Migrate config version `6` to `7'. Remove alias map and introduce
// named Host config. Also no more glob match for host config entries. | [
"Migrate",
"config",
"version",
"6",
"to",
"7",
".",
"Remove",
"alias",
"map",
"and",
"introduce",
"named",
"Host",
"config",
".",
"Also",
"no",
"more",
"glob",
"match",
"for",
"host",
"config",
"entries",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L326-L401 | train |
minio/mc | cmd/config-migrate.go | migrateConfigV8ToV9 | func migrateConfigV8ToV9() {
if !isMcConfigExists() {
return
}
mcCfgV8, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV8())
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
if mcCfgV8.Version() != "8" {
return
}
cfgV9 := newConfigV9()
isEmpty := true
// We dropped alias support in v8. We only need to migrate host configs.
for host, hostCfgV8 := range mcCfgV8.Data().(*configV8).Hosts {
// Ignore 'player', 'play' and 'dl' aliases.
if host == "player" || host == "dl" || host == "play" {
continue
}
isEmpty = false
hostCfgV9 := hostConfigV9{}
hostCfgV9.URL = hostCfgV8.URL
hostCfgV9.AccessKey = hostCfgV8.AccessKey
hostCfgV9.SecretKey = hostCfgV8.SecretKey
hostCfgV9.API = hostCfgV8.API
hostCfgV9.Lookup = "auto"
cfgV9.Hosts[host] = hostCfgV9
}
if isEmpty {
// Load default settings.
cfgV9.loadDefaults()
}
mcNewCfgV9, e := quick.NewConfig(cfgV9, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `9`.")
e = mcNewCfgV9.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `9`.")
console.Infof("Successfully migrated %s from version `8` to version `9`.\n", mustGetMcConfigPath())
} | go | func migrateConfigV8ToV9() {
if !isMcConfigExists() {
return
}
mcCfgV8, e := quick.LoadConfig(mustGetMcConfigPath(), nil, newConfigV8())
fatalIf(probe.NewError(e), "Unable to load mc config V8.")
if mcCfgV8.Version() != "8" {
return
}
cfgV9 := newConfigV9()
isEmpty := true
// We dropped alias support in v8. We only need to migrate host configs.
for host, hostCfgV8 := range mcCfgV8.Data().(*configV8).Hosts {
// Ignore 'player', 'play' and 'dl' aliases.
if host == "player" || host == "dl" || host == "play" {
continue
}
isEmpty = false
hostCfgV9 := hostConfigV9{}
hostCfgV9.URL = hostCfgV8.URL
hostCfgV9.AccessKey = hostCfgV8.AccessKey
hostCfgV9.SecretKey = hostCfgV8.SecretKey
hostCfgV9.API = hostCfgV8.API
hostCfgV9.Lookup = "auto"
cfgV9.Hosts[host] = hostCfgV9
}
if isEmpty {
// Load default settings.
cfgV9.loadDefaults()
}
mcNewCfgV9, e := quick.NewConfig(cfgV9, nil)
fatalIf(probe.NewError(e), "Unable to initialize quick config for config version `9`.")
e = mcNewCfgV9.Save(mustGetMcConfigPath())
fatalIf(probe.NewError(e), "Unable to save config version `9`.")
console.Infof("Successfully migrated %s from version `8` to version `9`.\n", mustGetMcConfigPath())
} | [
"func",
"migrateConfigV8ToV9",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"mcCfgV8",
",",
"e",
":=",
"quick",
".",
"LoadConfig",
"(",
"mustGetMcConfigPath",
"(",
")",
",",
"nil",
",",
"newConfigV8",
"(",
")",
... | // Migrate config version `8` to `9'. Add optional field virtual | [
"Migrate",
"config",
"version",
"8",
"to",
"9",
".",
"Add",
"optional",
"field",
"virtual"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-migrate.go#L443-L484 | train |
minio/mc | cmd/cp-main.go | String | func (c copyMessage) String() string {
return console.Colorize("Copy", fmt.Sprintf("`%s` -> `%s`", c.Source, c.Target))
} | go | func (c copyMessage) String() string {
return console.Colorize("Copy", fmt.Sprintf("`%s` -> `%s`", c.Source, c.Target))
} | [
"func",
"(",
"c",
"copyMessage",
")",
"String",
"(",
")",
"string",
"{",
"return",
"console",
".",
"Colorize",
"(",
"\"Copy\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"`%s` -> `%s`\"",
",",
"c",
".",
"Source",
",",
"c",
".",
"Target",
")",
")",
"\n",
"}"... | // String colorized copy message | [
"String",
"colorized",
"copy",
"message"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L139-L141 | train |
minio/mc | cmd/cp-main.go | JSON | func (c copyMessage) JSON() string {
c.Status = "success"
copyMessageBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Failed to marshal copy message.")
return string(copyMessageBytes)
} | go | func (c copyMessage) JSON() string {
c.Status = "success"
copyMessageBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Failed to marshal copy message.")
return string(copyMessageBytes)
} | [
"func",
"(",
"c",
"copyMessage",
")",
"JSON",
"(",
")",
"string",
"{",
"c",
".",
"Status",
"=",
"\"success\"",
"\n",
"copyMessageBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"c",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
"pr... | // JSON jsonified copy message | [
"JSON",
"jsonified",
"copy",
"message"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L144-L150 | train |
minio/mc | cmd/cp-main.go | String | func (c copyStatMessage) String() string {
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
if speedBox == "" {
speedBox = "0 MB"
} else {
speedBox = speedBox + "/s"
}
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
return message
} | go | func (c copyStatMessage) String() string {
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
if speedBox == "" {
speedBox = "0 MB"
} else {
speedBox = speedBox + "/s"
}
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
return message
} | [
"func",
"(",
"c",
"copyStatMessage",
")",
"String",
"(",
")",
"string",
"{",
"speedBox",
":=",
"pb",
".",
"Format",
"(",
"int64",
"(",
"c",
".",
"Speed",
")",
")",
".",
"To",
"(",
"pb",
".",
"U_BYTES",
")",
".",
"String",
"(",
")",
"\n",
"if",
... | // copyStatMessage copy accounting message | [
"copyStatMessage",
"copy",
"accounting",
"message"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L160-L170 | train |
minio/mc | cmd/cp-main.go | doCopy | func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair) URLs {
if cpURLs.Error != nil {
cpURLs.Error = cpURLs.Error.Trace()
return cpURLs
}
sourceAlias := cpURLs.SourceAlias
sourceURL := cpURLs.SourceContent.URL
targetAlias := cpURLs.TargetAlias
targetURL := cpURLs.TargetContent.URL
length := cpURLs.SourceContent.Size
if progressReader, ok := pg.(*progressBar); ok {
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
} else {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
printMsg(copyMessage{
Source: sourcePath,
Target: targetPath,
Size: length,
TotalCount: cpURLs.TotalCount,
TotalSize: cpURLs.TotalSize,
})
}
return uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB)
} | go | func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair) URLs {
if cpURLs.Error != nil {
cpURLs.Error = cpURLs.Error.Trace()
return cpURLs
}
sourceAlias := cpURLs.SourceAlias
sourceURL := cpURLs.SourceContent.URL
targetAlias := cpURLs.TargetAlias
targetURL := cpURLs.TargetContent.URL
length := cpURLs.SourceContent.Size
if progressReader, ok := pg.(*progressBar); ok {
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
} else {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
printMsg(copyMessage{
Source: sourcePath,
Target: targetPath,
Size: length,
TotalCount: cpURLs.TotalCount,
TotalSize: cpURLs.TotalSize,
})
}
return uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB)
} | [
"func",
"doCopy",
"(",
"ctx",
"context",
".",
"Context",
",",
"cpURLs",
"URLs",
",",
"pg",
"ProgressReader",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"URLs",
"{",
"if",
"cpURLs",
".",
"Error",
"!=",
"nil",
"{",
"cpURL... | // doCopy - Copy a singe file from source to destination | [
"doCopy",
"-",
"Copy",
"a",
"singe",
"file",
"from",
"source",
"to",
"destination"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L186-L212 | train |
minio/mc | cmd/cp-main.go | doCopyFake | func doCopyFake(cpURLs URLs, pg Progress) URLs {
if progressReader, ok := pg.(*progressBar); ok {
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
}
return cpURLs
} | go | func doCopyFake(cpURLs URLs, pg Progress) URLs {
if progressReader, ok := pg.(*progressBar); ok {
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
}
return cpURLs
} | [
"func",
"doCopyFake",
"(",
"cpURLs",
"URLs",
",",
"pg",
"Progress",
")",
"URLs",
"{",
"if",
"progressReader",
",",
"ok",
":=",
"pg",
".",
"(",
"*",
"progressBar",
")",
";",
"ok",
"{",
"progressReader",
".",
"ProgressBar",
".",
"Add64",
"(",
"cpURLs",
"... | // doCopyFake - Perform a fake copy to update the progress bar appropriately. | [
"doCopyFake",
"-",
"Perform",
"a",
"fake",
"copy",
"to",
"update",
"the",
"progress",
"bar",
"appropriately",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L215-L220 | train |
minio/mc | cmd/cp-main.go | doPrepareCopyURLs | func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
var totalBytes int64
var totalObjects int64
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
olderThan := session.Header.CommandStringFlags["older-than"]
newerThan := session.Header.CommandStringFlags["newer-than"]
encryptKeys := session.Header.CommandStringFlags["encrypt-key"]
encrypt := session.Header.CommandStringFlags["encrypt"]
encKeyDB, err := parseAndValidateEncryptionKeys(encryptKeys, encrypt)
fatalIf(err, "Unable to parse encryption keys.")
// Create a session data file to store the processed URLs.
dataFP := session.NewDataWriter()
var scanBar scanBarFunc
if !globalQuiet && !globalJSON { // set up progress bar
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB)
done := false
for !done {
select {
case cpURLs, ok := <-URLsCh:
if !ok { // Done with URL preparation
done = true
break
}
if cpURLs.Error != nil {
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") {
errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use `...` suffix.")
} else {
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
}
break
}
jsonData, e := json.Marshal(cpURLs)
if e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
}
// Skip objects older than --older-than parameter if specified
if olderThan != "" && isOlder(cpURLs.SourceContent.Time, olderThan) {
continue
}
// Skip objects newer than --newer-than parameter if specified
if newerThan != "" && isNewer(cpURLs.SourceContent.Time, newerThan) {
continue
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
scanBar(cpURLs.SourceContent.URL.String())
}
totalBytes += cpURLs.SourceContent.Size
totalObjects++
case <-trapCh:
cancelCopy()
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
os.Exit(0)
}
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
} | go | func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
var totalBytes int64
var totalObjects int64
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
olderThan := session.Header.CommandStringFlags["older-than"]
newerThan := session.Header.CommandStringFlags["newer-than"]
encryptKeys := session.Header.CommandStringFlags["encrypt-key"]
encrypt := session.Header.CommandStringFlags["encrypt"]
encKeyDB, err := parseAndValidateEncryptionKeys(encryptKeys, encrypt)
fatalIf(err, "Unable to parse encryption keys.")
// Create a session data file to store the processed URLs.
dataFP := session.NewDataWriter()
var scanBar scanBarFunc
if !globalQuiet && !globalJSON { // set up progress bar
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB)
done := false
for !done {
select {
case cpURLs, ok := <-URLsCh:
if !ok { // Done with URL preparation
done = true
break
}
if cpURLs.Error != nil {
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") {
errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use `...` suffix.")
} else {
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
}
break
}
jsonData, e := json.Marshal(cpURLs)
if e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
}
// Skip objects older than --older-than parameter if specified
if olderThan != "" && isOlder(cpURLs.SourceContent.Time, olderThan) {
continue
}
// Skip objects newer than --newer-than parameter if specified
if newerThan != "" && isNewer(cpURLs.SourceContent.Time, newerThan) {
continue
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
scanBar(cpURLs.SourceContent.URL.String())
}
totalBytes += cpURLs.SourceContent.Size
totalObjects++
case <-trapCh:
cancelCopy()
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
os.Exit(0)
}
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
} | [
"func",
"doPrepareCopyURLs",
"(",
"session",
"*",
"sessionV8",
",",
"trapCh",
"<-",
"chan",
"bool",
",",
"cancelCopy",
"context",
".",
"CancelFunc",
")",
"{",
"sourceURLs",
":=",
"session",
".",
"Header",
".",
"CommandArgs",
"[",
":",
"len",
"(",
"session",
... | // doPrepareCopyURLs scans the source URL and prepares a list of objects for copying. | [
"doPrepareCopyURLs",
"scans",
"the",
"source",
"URL",
"and",
"prepares",
"a",
"list",
"of",
"objects",
"for",
"copying",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L223-L307 | train |
minio/mc | cmd/cp-main.go | getMetaDataEntry | func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
metaDataMap := make(map[string]string)
for _, metaData := range strings.Split(metadataString, ",") {
metaDataEntry := strings.Split(metaData, "=")
if len(metaDataEntry) == 2 {
metaDataMap[metaDataEntry[0]] = metaDataEntry[1]
} else {
return nil, probe.NewError(ErrInvalidMetadata)
}
}
return metaDataMap, nil
} | go | func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
metaDataMap := make(map[string]string)
for _, metaData := range strings.Split(metadataString, ",") {
metaDataEntry := strings.Split(metaData, "=")
if len(metaDataEntry) == 2 {
metaDataMap[metaDataEntry[0]] = metaDataEntry[1]
} else {
return nil, probe.NewError(ErrInvalidMetadata)
}
}
return metaDataMap, nil
} | [
"func",
"getMetaDataEntry",
"(",
"metadataString",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"metaDataMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
",",
... | // validate the passed metadataString and populate the map | [
"validate",
"the",
"passed",
"metadataString",
"and",
"populate",
"the",
"map"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L471-L482 | train |
minio/mc | cmd/cp-main.go | mainCopy | func mainCopy(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// Parse metadata.
userMetaMap := make(map[string]string)
if ctx.String("attr") != "" {
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
}
// check 'copy' cli arguments.
checkCopySyntax(ctx, encKeyDB)
// Additional command speific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
recursive := ctx.Bool("recursive")
olderThan := ctx.String("older-than")
newerThan := ctx.String("newer-than")
storageClass := ctx.String("storage-class")
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
if key := ctx.String("encrypt-key"); key != "" {
sseKeys = key
}
sse := ctx.String("encrypt")
session := newSessionV8()
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
session.Header.CommandStringFlags["encrypt"] = sse
session.Header.UserMetaData = userMetaMap
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to get current working folder.")
}
// extract URLs.
session.Header.CommandArgs = ctx.Args()
e = doCopySession(session, encKeyDB)
session.Delete()
return e
} | go | func mainCopy(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// Parse metadata.
userMetaMap := make(map[string]string)
if ctx.String("attr") != "" {
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
}
// check 'copy' cli arguments.
checkCopySyntax(ctx, encKeyDB)
// Additional command speific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
recursive := ctx.Bool("recursive")
olderThan := ctx.String("older-than")
newerThan := ctx.String("newer-than")
storageClass := ctx.String("storage-class")
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
if key := ctx.String("encrypt-key"); key != "" {
sseKeys = key
}
sse := ctx.String("encrypt")
session := newSessionV8()
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
session.Header.CommandStringFlags["encrypt"] = sse
session.Header.UserMetaData = userMetaMap
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to get current working folder.")
}
// extract URLs.
session.Header.CommandArgs = ctx.Args()
e = doCopySession(session, encKeyDB)
session.Delete()
return e
} | [
"func",
"mainCopy",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"userMetaMap",
":=",
"make",
"(... | // mainCopy is the entry point for cp command. | [
"mainCopy",
"is",
"the",
"entry",
"point",
"for",
"cp",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/cp-main.go#L485-L535 | train |
minio/mc | cmd/pretty-record.go | newPrettyRecord | func newPrettyRecord(indent int, rows ...Row) PrettyRecord {
maxDescLen := 0
for _, r := range rows {
if len(r.desc) > maxDescLen {
maxDescLen = len(r.desc)
}
}
return PrettyRecord{
rows: rows,
indent: indent,
maxLen: maxDescLen,
}
} | go | func newPrettyRecord(indent int, rows ...Row) PrettyRecord {
maxDescLen := 0
for _, r := range rows {
if len(r.desc) > maxDescLen {
maxDescLen = len(r.desc)
}
}
return PrettyRecord{
rows: rows,
indent: indent,
maxLen: maxDescLen,
}
} | [
"func",
"newPrettyRecord",
"(",
"indent",
"int",
",",
"rows",
"...",
"Row",
")",
"PrettyRecord",
"{",
"maxDescLen",
":=",
"0",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"rows",
"{",
"if",
"len",
"(",
"r",
".",
"desc",
")",
">",
"maxDescLen",
"{",
... | // newPrettyRecord - creates a new pretty record | [
"newPrettyRecord",
"-",
"creates",
"a",
"new",
"pretty",
"record"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pretty-record.go#L40-L52 | train |
minio/mc | cmd/pretty-record.go | buildRecord | func (t PrettyRecord) buildRecord(contents ...string) (line string) {
// totalRows is the minimum of the number of fields config
// and the number of contents elements.
totalRows := len(contents)
if len(t.rows) < totalRows {
totalRows = len(t.rows)
}
var format, separator string
// Format fields and construct message
for i := 0; i < totalRows; i++ {
// default heading
indent := 0
format = "%s\n"
// optionally indented rows with key value pairs
if i > 0 {
indent = t.indent
format = fmt.Sprintf("%%%ds%%-%ds : %%s\n", indent, t.maxLen)
line += console.Colorize(t.rows[i].descTheme, fmt.Sprintf(format, separator, t.rows[i].desc, contents[i]))
} else {
line += console.Colorize(t.rows[i].descTheme, fmt.Sprintf(format, contents[i]))
}
}
return
} | go | func (t PrettyRecord) buildRecord(contents ...string) (line string) {
// totalRows is the minimum of the number of fields config
// and the number of contents elements.
totalRows := len(contents)
if len(t.rows) < totalRows {
totalRows = len(t.rows)
}
var format, separator string
// Format fields and construct message
for i := 0; i < totalRows; i++ {
// default heading
indent := 0
format = "%s\n"
// optionally indented rows with key value pairs
if i > 0 {
indent = t.indent
format = fmt.Sprintf("%%%ds%%-%ds : %%s\n", indent, t.maxLen)
line += console.Colorize(t.rows[i].descTheme, fmt.Sprintf(format, separator, t.rows[i].desc, contents[i]))
} else {
line += console.Colorize(t.rows[i].descTheme, fmt.Sprintf(format, contents[i]))
}
}
return
} | [
"func",
"(",
"t",
"PrettyRecord",
")",
"buildRecord",
"(",
"contents",
"...",
"string",
")",
"(",
"line",
"string",
")",
"{",
"totalRows",
":=",
"len",
"(",
"contents",
")",
"\n",
"if",
"len",
"(",
"t",
".",
"rows",
")",
"<",
"totalRows",
"{",
"total... | // buildRecord - creates a string which represents a record table given
// some fields contents. | [
"buildRecord",
"-",
"creates",
"a",
"string",
"which",
"represents",
"a",
"record",
"table",
"given",
"some",
"fields",
"contents",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pretty-record.go#L56-L80 | train |
minio/mc | cmd/admin-policy-add.go | checkAdminPolicyAddSyntax | func checkAdminPolicyAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
} | go | func checkAdminPolicyAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
} | [
"func",
"checkAdminPolicyAddSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"3",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"add\"",
",",
"1",
")",
"\n",
"}",
... | // checkAdminPolicyAddSyntax - validate all the passed arguments | [
"checkAdminPolicyAddSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-policy-add.go#L57-L61 | train |
minio/mc | cmd/admin-policy-add.go | mainAdminPolicyAdd | func mainAdminPolicyAdd(ctx *cli.Context) error {
checkAdminPolicyAddSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policy, e := ioutil.ReadFile(args.Get(2))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.AddCannedPolicy(args.Get(1), string(policy))).Trace(args...), "Cannot add new policy")
printMsg(userPolicyMessage{
op: "add",
Policy: args.Get(1),
})
return nil
} | go | func mainAdminPolicyAdd(ctx *cli.Context) error {
checkAdminPolicyAddSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
policy, e := ioutil.ReadFile(args.Get(2))
fatalIf(probe.NewError(e).Trace(args...), "Unable to get policy")
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.AddCannedPolicy(args.Get(1), string(policy))).Trace(args...), "Cannot add new policy")
printMsg(userPolicyMessage{
op: "add",
Policy: args.Get(1),
})
return nil
} | [
"func",
"mainAdminPolicyAdd",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminPolicyAddSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"PolicyMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
... | // mainAdminPolicyAdd is the handle for "mc admin policy add" command. | [
"mainAdminPolicyAdd",
"is",
"the",
"handle",
"for",
"mc",
"admin",
"policy",
"add",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-policy-add.go#L99-L123 | train |
minio/mc | cmd/error.go | fatalIf | func fatalIf(err *probe.Error, msg string, data ...interface{}) {
if err == nil {
return
}
fatal(err, msg, data...)
} | go | func fatalIf(err *probe.Error, msg string, data ...interface{}) {
if err == nil {
return
}
fatal(err, msg, data...)
} | [
"func",
"fatalIf",
"(",
"err",
"*",
"probe",
".",
"Error",
",",
"msg",
"string",
",",
"data",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"fatal",
"(",
"err",
",",
"msg",
",",
"data",
"...",
... | // fatalIf wrapper function which takes error and selectively prints stack frames if available on debug | [
"fatalIf",
"wrapper",
"function",
"which",
"takes",
"error",
"and",
"selectively",
"prints",
"stack",
"frames",
"if",
"available",
"on",
"debug"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/error.go#L46-L51 | train |
minio/mc | cmd/error.go | errorIf | func errorIf(err *probe.Error, msg string, data ...interface{}) {
if err == nil {
return
}
if globalJSON {
errorMsg := errorMessage{
Message: fmt.Sprintf(msg, data...),
Type: "error",
Cause: causeMessage{
Message: err.ToGoError().Error(),
Error: err.ToGoError(),
},
SysInfo: err.SysInfo,
}
if globalDebug {
errorMsg.CallTrace = err.CallTrace
}
json, e := json.MarshalIndent(struct {
Status string `json:"status"`
Error errorMessage `json:"error"`
}{
Status: "error",
Error: errorMsg,
}, "", " ")
if e != nil {
console.Fatalln(probe.NewError(e))
}
console.Println(string(json))
return
}
msg = fmt.Sprintf(msg, data...)
if !globalDebug {
console.Errorln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
return
}
console.Errorln(fmt.Sprintf("%s %s", msg, err))
} | go | func errorIf(err *probe.Error, msg string, data ...interface{}) {
if err == nil {
return
}
if globalJSON {
errorMsg := errorMessage{
Message: fmt.Sprintf(msg, data...),
Type: "error",
Cause: causeMessage{
Message: err.ToGoError().Error(),
Error: err.ToGoError(),
},
SysInfo: err.SysInfo,
}
if globalDebug {
errorMsg.CallTrace = err.CallTrace
}
json, e := json.MarshalIndent(struct {
Status string `json:"status"`
Error errorMessage `json:"error"`
}{
Status: "error",
Error: errorMsg,
}, "", " ")
if e != nil {
console.Fatalln(probe.NewError(e))
}
console.Println(string(json))
return
}
msg = fmt.Sprintf(msg, data...)
if !globalDebug {
console.Errorln(fmt.Sprintf("%s %s", msg, err.ToGoError()))
return
}
console.Errorln(fmt.Sprintf("%s %s", msg, err))
} | [
"func",
"errorIf",
"(",
"err",
"*",
"probe",
".",
"Error",
",",
"msg",
"string",
",",
"data",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"globalJSON",
"{",
"errorMsg",
":=",
"errorMessage",... | // errorIf synonymous with fatalIf but doesn't exit on error != nil | [
"errorIf",
"synonymous",
"with",
"fatalIf",
"but",
"doesn",
"t",
"exit",
"on",
"error",
"!",
"=",
"nil"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/error.go#L121-L157 | train |
minio/mc | pkg/colorjson/stream.go | MarshalJSON | func (m RawMessage) MarshalJSON() ([]byte, error) {
if m == nil {
return []byte("null"), nil
}
return m, nil
} | go | func (m RawMessage) MarshalJSON() ([]byte, error) {
if m == nil {
return []byte("null"), nil
}
return m, nil
} | [
"func",
"(",
"m",
"RawMessage",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"m",
"==",
"nil",
"{",
"return",
"[",
"]",
"byte",
"(",
"\"null\"",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"m",
",",
"nil",
... | // MarshalJSON returns m as the JSON encoding of m. | [
"MarshalJSON",
"returns",
"m",
"as",
"the",
"JSON",
"encoding",
"of",
"m",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/stream.go#L269-L274 | train |
minio/mc | pkg/colorjson/stream.go | tokenPrepareForDecode | func (dec *Decoder) tokenPrepareForDecode() error {
// Note: Not calling peek before switch, to avoid
// putting peek into the standard Decode path.
// peek is only called when using the Token API.
switch dec.tokenState {
case tokenArrayComma:
c, err := dec.peek()
if err != nil {
return err
}
if c != ',' {
return &SyntaxError{"expected comma after array element", dec.offset()}
}
dec.scanp++
dec.tokenState = tokenArrayValue
case tokenObjectColon:
c, err := dec.peek()
if err != nil {
return err
}
if c != ':' {
return &SyntaxError{"expected colon after object key", dec.offset()}
}
dec.scanp++
dec.tokenState = tokenObjectValue
}
return nil
} | go | func (dec *Decoder) tokenPrepareForDecode() error {
// Note: Not calling peek before switch, to avoid
// putting peek into the standard Decode path.
// peek is only called when using the Token API.
switch dec.tokenState {
case tokenArrayComma:
c, err := dec.peek()
if err != nil {
return err
}
if c != ',' {
return &SyntaxError{"expected comma after array element", dec.offset()}
}
dec.scanp++
dec.tokenState = tokenArrayValue
case tokenObjectColon:
c, err := dec.peek()
if err != nil {
return err
}
if c != ':' {
return &SyntaxError{"expected colon after object key", dec.offset()}
}
dec.scanp++
dec.tokenState = tokenObjectValue
}
return nil
} | [
"func",
"(",
"dec",
"*",
"Decoder",
")",
"tokenPrepareForDecode",
"(",
")",
"error",
"{",
"switch",
"dec",
".",
"tokenState",
"{",
"case",
"tokenArrayComma",
":",
"c",
",",
"err",
":=",
"dec",
".",
"peek",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{... | // advance tokenstate from a separator state to a value state | [
"advance",
"tokenstate",
"from",
"a",
"separator",
"state",
"to",
"a",
"value",
"state"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/stream.go#L312-L339 | train |
minio/mc | pkg/colorjson/stream.go | More | func (dec *Decoder) More() bool {
c, err := dec.peek()
return err == nil && c != ']' && c != '}'
} | go | func (dec *Decoder) More() bool {
c, err := dec.peek()
return err == nil && c != ']' && c != '}'
} | [
"func",
"(",
"dec",
"*",
"Decoder",
")",
"More",
"(",
")",
"bool",
"{",
"c",
",",
"err",
":=",
"dec",
".",
"peek",
"(",
")",
"\n",
"return",
"err",
"==",
"nil",
"&&",
"c",
"!=",
"']'",
"&&",
"c",
"!=",
"'}'",
"\n",
"}"
] | // More reports whether there is another element in the
// current array or object being parsed. | [
"More",
"reports",
"whether",
"there",
"is",
"another",
"element",
"in",
"the",
"current",
"array",
"or",
"object",
"being",
"parsed",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/stream.go#L491-L494 | train |
minio/mc | pkg/probe/probe.go | GetSysInfo | func GetSysInfo() map[string]string {
host, err := os.Hostname()
if err != nil {
host = ""
}
memstats := &runtime.MemStats{}
runtime.ReadMemStats(memstats)
return map[string]string{
"host.name": host,
"host.os": runtime.GOOS,
"host.arch": runtime.GOARCH,
"host.lang": runtime.Version(),
"host.cpus": strconv.Itoa(runtime.NumCPU()),
"mem.used": humanize.Bytes(memstats.Alloc),
"mem.total": humanize.Bytes(memstats.Sys),
"mem.heap.used": humanize.Bytes(memstats.HeapAlloc),
"mem.heap.total": humanize.Bytes(memstats.HeapSys),
}
} | go | func GetSysInfo() map[string]string {
host, err := os.Hostname()
if err != nil {
host = ""
}
memstats := &runtime.MemStats{}
runtime.ReadMemStats(memstats)
return map[string]string{
"host.name": host,
"host.os": runtime.GOOS,
"host.arch": runtime.GOARCH,
"host.lang": runtime.Version(),
"host.cpus": strconv.Itoa(runtime.NumCPU()),
"mem.used": humanize.Bytes(memstats.Alloc),
"mem.total": humanize.Bytes(memstats.Sys),
"mem.heap.used": humanize.Bytes(memstats.HeapAlloc),
"mem.heap.total": humanize.Bytes(memstats.HeapSys),
}
} | [
"func",
"GetSysInfo",
"(",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"host",
",",
"err",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"host",
"=",
"\"\"",
"\n",
"}",
"\n",
"memstats",
":=",
"&",
"runtime",
".",... | // GetSysInfo returns useful system statistics. | [
"GetSysInfo",
"returns",
"useful",
"system",
"statistics",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/probe/probe.go#L61-L79 | train |
minio/mc | pkg/probe/probe.go | Trace | func (e *Error) Trace(fields ...string) *Error {
if e == nil {
return nil
}
e.lock.Lock()
defer e.lock.Unlock()
return e.trace(fields...)
} | go | func (e *Error) Trace(fields ...string) *Error {
if e == nil {
return nil
}
e.lock.Lock()
defer e.lock.Unlock()
return e.trace(fields...)
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"Trace",
"(",
"fields",
"...",
"string",
")",
"*",
"Error",
"{",
"if",
"e",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"e",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"lock",
"."... | // Trace records the point at which it is invoked.
// Stack traces are important for debugging purposes. | [
"Trace",
"records",
"the",
"point",
"at",
"which",
"it",
"is",
"invoked",
".",
"Stack",
"traces",
"are",
"important",
"for",
"debugging",
"purposes",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/probe/probe.go#L125-L134 | train |
minio/mc | pkg/probe/probe.go | trace | func (e *Error) trace(fields ...string) *Error {
if e == nil {
return nil
}
pc, file, line, _ := runtime.Caller(2)
function := runtime.FuncForPC(pc).Name()
_, function = filepath.Split(function)
file = strings.TrimPrefix(file, rootPath+string(os.PathSeparator)) // trims project's root path.
tp := TracePoint{}
if len(fields) > 0 {
tp = TracePoint{Line: line, Filename: file, Function: function, Env: map[string][]string{"Tags": fields}}
} else {
tp = TracePoint{Line: line, Filename: file, Function: function}
}
e.CallTrace = append(e.CallTrace, tp)
return e
} | go | func (e *Error) trace(fields ...string) *Error {
if e == nil {
return nil
}
pc, file, line, _ := runtime.Caller(2)
function := runtime.FuncForPC(pc).Name()
_, function = filepath.Split(function)
file = strings.TrimPrefix(file, rootPath+string(os.PathSeparator)) // trims project's root path.
tp := TracePoint{}
if len(fields) > 0 {
tp = TracePoint{Line: line, Filename: file, Function: function, Env: map[string][]string{"Tags": fields}}
} else {
tp = TracePoint{Line: line, Filename: file, Function: function}
}
e.CallTrace = append(e.CallTrace, tp)
return e
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"trace",
"(",
"fields",
"...",
"string",
")",
"*",
"Error",
"{",
"if",
"e",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"pc",
",",
"file",
",",
"line",
",",
"_",
":=",
"runtime",
".",
"Caller",
"(",
... | // trace records caller's caller. It is intended for probe's own
// internal use. Take a look at probe.NewError for example. | [
"trace",
"records",
"caller",
"s",
"caller",
".",
"It",
"is",
"intended",
"for",
"probe",
"s",
"own",
"internal",
"use",
".",
"Take",
"a",
"look",
"at",
"probe",
".",
"NewError",
"for",
"example",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/probe/probe.go#L138-L154 | train |
minio/mc | pkg/probe/probe.go | Untrace | func (e *Error) Untrace() *Error {
if e == nil {
return nil
}
e.lock.Lock()
defer e.lock.Unlock()
l := len(e.CallTrace)
if l == 0 {
return nil
}
e.CallTrace = e.CallTrace[:l-1]
return e
} | go | func (e *Error) Untrace() *Error {
if e == nil {
return nil
}
e.lock.Lock()
defer e.lock.Unlock()
l := len(e.CallTrace)
if l == 0 {
return nil
}
e.CallTrace = e.CallTrace[:l-1]
return e
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"Untrace",
"(",
")",
"*",
"Error",
"{",
"if",
"e",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"e",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"lock",
".",
"Unlock",
"(",
")",
"... | // Untrace erases last known trace entry. | [
"Untrace",
"erases",
"last",
"known",
"trace",
"entry",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/probe/probe.go#L157-L170 | train |
minio/mc | pkg/probe/probe.go | ToGoError | func (e *Error) ToGoError() error {
if e == nil || e.Cause == nil {
return nil
}
return e.Cause
} | go | func (e *Error) ToGoError() error {
if e == nil || e.Cause == nil {
return nil
}
return e.Cause
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"ToGoError",
"(",
")",
"error",
"{",
"if",
"e",
"==",
"nil",
"||",
"e",
".",
"Cause",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"e",
".",
"Cause",
"\n",
"}"
] | // ToGoError returns original error message. | [
"ToGoError",
"returns",
"original",
"error",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/probe/probe.go#L173-L178 | train |
minio/mc | pkg/probe/probe.go | String | func (e *Error) String() string {
if e == nil || e.Cause == nil {
return "<nil>"
}
e.lock.RLock()
defer e.lock.RUnlock()
if e.Cause != nil {
str := e.Cause.Error()
callLen := len(e.CallTrace)
for i := callLen - 1; i >= 0; i-- {
if len(e.CallTrace[i].Env) > 0 {
str += fmt.Sprintf("\n (%d) %s:%d %s(..) Tags: [%s]",
i, e.CallTrace[i].Filename, e.CallTrace[i].Line, e.CallTrace[i].Function, strings.Join(e.CallTrace[i].Env["Tags"], ", "))
} else {
str += fmt.Sprintf("\n (%d) %s:%d %s(..)",
i, e.CallTrace[i].Filename, e.CallTrace[i].Line, e.CallTrace[i].Function)
}
}
str += "\n "
for key, value := range appInfo {
str += key + ":" + value + " | "
}
str += "Host:" + e.SysInfo["host.name"] + " | "
str += "OS:" + e.SysInfo["host.os"] + " | "
str += "Arch:" + e.SysInfo["host.arch"] + " | "
str += "Lang:" + e.SysInfo["host.lang"] + " | "
str += "Mem:" + e.SysInfo["mem.used"] + "/" + e.SysInfo["mem.total"] + " | "
str += "Heap:" + e.SysInfo["mem.heap.used"] + "/" + e.SysInfo["mem.heap.total"]
return str
}
return "<nil>"
} | go | func (e *Error) String() string {
if e == nil || e.Cause == nil {
return "<nil>"
}
e.lock.RLock()
defer e.lock.RUnlock()
if e.Cause != nil {
str := e.Cause.Error()
callLen := len(e.CallTrace)
for i := callLen - 1; i >= 0; i-- {
if len(e.CallTrace[i].Env) > 0 {
str += fmt.Sprintf("\n (%d) %s:%d %s(..) Tags: [%s]",
i, e.CallTrace[i].Filename, e.CallTrace[i].Line, e.CallTrace[i].Function, strings.Join(e.CallTrace[i].Env["Tags"], ", "))
} else {
str += fmt.Sprintf("\n (%d) %s:%d %s(..)",
i, e.CallTrace[i].Filename, e.CallTrace[i].Line, e.CallTrace[i].Function)
}
}
str += "\n "
for key, value := range appInfo {
str += key + ":" + value + " | "
}
str += "Host:" + e.SysInfo["host.name"] + " | "
str += "OS:" + e.SysInfo["host.os"] + " | "
str += "Arch:" + e.SysInfo["host.arch"] + " | "
str += "Lang:" + e.SysInfo["host.lang"] + " | "
str += "Mem:" + e.SysInfo["mem.used"] + "/" + e.SysInfo["mem.total"] + " | "
str += "Heap:" + e.SysInfo["mem.heap.used"] + "/" + e.SysInfo["mem.heap.total"]
return str
}
return "<nil>"
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"String",
"(",
")",
"string",
"{",
"if",
"e",
"==",
"nil",
"||",
"e",
".",
"Cause",
"==",
"nil",
"{",
"return",
"\"<nil>\"",
"\n",
"}",
"\n",
"e",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
"... | // String returns error message. | [
"String",
"returns",
"error",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/probe/probe.go#L181-L217 | train |
minio/mc | cmd/status.go | SetTotal | func (qs *QuietStatus) SetTotal(v int64) Status {
qs.accounter.Total = v
return qs
} | go | func (qs *QuietStatus) SetTotal(v int64) Status {
qs.accounter.Total = v
return qs
} | [
"func",
"(",
"qs",
"*",
"QuietStatus",
")",
"SetTotal",
"(",
"v",
"int64",
")",
"Status",
"{",
"qs",
".",
"accounter",
".",
"Total",
"=",
"v",
"\n",
"return",
"qs",
"\n",
"}"
] | // SetTotal sets the total of the progressbar, ignored for quietstatus | [
"SetTotal",
"sets",
"the",
"total",
"of",
"the",
"progressbar",
"ignored",
"for",
"quietstatus"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/status.go#L136-L139 | train |
minio/mc | cmd/status.go | Finish | func (qs *QuietStatus) Finish() {
console.Println(console.Colorize("Mirror", qs.accounter.Stat().String()))
} | go | func (qs *QuietStatus) Finish() {
console.Println(console.Colorize("Mirror", qs.accounter.Stat().String()))
} | [
"func",
"(",
"qs",
"*",
"QuietStatus",
")",
"Finish",
"(",
")",
"{",
"console",
".",
"Println",
"(",
"console",
".",
"Colorize",
"(",
"\"Mirror\"",
",",
"qs",
".",
"accounter",
".",
"Stat",
"(",
")",
".",
"String",
"(",
")",
")",
")",
"\n",
"}"
] | // Finish displays the accounting summary | [
"Finish",
"displays",
"the",
"accounting",
"summary"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/status.go#L174-L176 | train |
minio/mc | cmd/status.go | SetTotal | func (ps *ProgressStatus) SetTotal(v int64) Status {
ps.progressBar.Total = v
return ps
} | go | func (ps *ProgressStatus) SetTotal(v int64) Status {
ps.progressBar.Total = v
return ps
} | [
"func",
"(",
"ps",
"*",
"ProgressStatus",
")",
"SetTotal",
"(",
"v",
"int64",
")",
"Status",
"{",
"ps",
".",
"progressBar",
".",
"Total",
"=",
"v",
"\n",
"return",
"ps",
"\n",
"}"
] | // SetTotal sets the total of the progressbar | [
"SetTotal",
"sets",
"the",
"total",
"of",
"the",
"progressbar"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/status.go#L221-L224 | train |
minio/mc | cmd/admin-profile-stop.go | mainAdminProfileStop | func mainAdminProfileStop(ctx *cli.Context) error {
// Check for command syntax
checkAdminProfileStopSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Create profile zip file
tmpFile, e := ioutil.TempFile("", "mc-profile-")
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Ask for profile data, which will come compressed with zip format
zippedData, adminErr := client.DownloadProfilingData()
fatalIf(probe.NewError(adminErr), "Unable to download profile data.")
// Copy zip content to target download file
_, e = io.Copy(tmpFile, zippedData)
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Close everything
zippedData.Close()
tmpFile.Close()
downloadPath := "profile.zip"
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format("2006-01-02T15:04:05.999999-07:00"))
fatalIf(probe.NewError(e), "Unable to create a backup of profile.zip")
} else {
if !os.IsNotExist(e) {
fatal(probe.NewError(e), "Unable to download profile data.")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to download profile data.")
console.Infof("Profile data successfully downloaded as %s\n", downloadPath)
return nil
} | go | func mainAdminProfileStop(ctx *cli.Context) error {
// Check for command syntax
checkAdminProfileStopSyntax(ctx)
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
if err != nil {
fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.")
return nil
}
// Create profile zip file
tmpFile, e := ioutil.TempFile("", "mc-profile-")
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Ask for profile data, which will come compressed with zip format
zippedData, adminErr := client.DownloadProfilingData()
fatalIf(probe.NewError(adminErr), "Unable to download profile data.")
// Copy zip content to target download file
_, e = io.Copy(tmpFile, zippedData)
fatalIf(probe.NewError(e), "Unable to download profile data.")
// Close everything
zippedData.Close()
tmpFile.Close()
downloadPath := "profile.zip"
fi, e := os.Stat(downloadPath)
if e == nil && !fi.IsDir() {
e = moveFile(downloadPath, downloadPath+"."+time.Now().Format("2006-01-02T15:04:05.999999-07:00"))
fatalIf(probe.NewError(e), "Unable to create a backup of profile.zip")
} else {
if !os.IsNotExist(e) {
fatal(probe.NewError(e), "Unable to download profile data.")
}
}
fatalIf(probe.NewError(moveFile(tmpFile.Name(), downloadPath)), "Unable to download profile data.")
console.Infof("Profile data successfully downloaded as %s\n", downloadPath)
return nil
} | [
"func",
"mainAdminProfileStop",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminProfileStopSyntax",
"(",
"ctx",
")",
"\n",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"aliasedURL",
":=",
"args",
".",
"Get",
"(",
"0",
")",
"\... | // mainAdminProfileStop - the entry function of profile stop command | [
"mainAdminProfileStop",
"-",
"the",
"entry",
"function",
"of",
"profile",
"stop",
"command"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-profile-stop.go#L86-L133 | train |
minio/mc | pkg/colorjson/encode.go | MarshalIndent | func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
b, err := Marshal(v)
if err != nil {
return nil, err
}
if !isatty.IsTerminal(os.Stdout.Fd()) {
return b, err
}
var buf bytes.Buffer
err = Indent(&buf, b, prefix, indent)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
b, err := Marshal(v)
if err != nil {
return nil, err
}
if !isatty.IsTerminal(os.Stdout.Fd()) {
return b, err
}
var buf bytes.Buffer
err = Indent(&buf, b, prefix, indent)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"MarshalIndent",
"(",
"v",
"interface",
"{",
"}",
",",
"prefix",
",",
"indent",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"Marshal",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // MarshalIndent is like Marshal but applies Indent to format the output.
// Each JSON element in the output will begin on a new line beginning with prefix
// followed by one or more copies of indent according to the indentation nesting. | [
"MarshalIndent",
"is",
"like",
"Marshal",
"but",
"applies",
"Indent",
"to",
"format",
"the",
"output",
".",
"Each",
"JSON",
"element",
"in",
"the",
"output",
"will",
"begin",
"on",
"a",
"new",
"line",
"beginning",
"with",
"prefix",
"followed",
"by",
"one",
... | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/encode.go#L194-L208 | train |
minio/mc | pkg/colorjson/encode.go | newCondAddrEncoder | func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
return enc.encode
} | go | func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
return enc.encode
} | [
"func",
"newCondAddrEncoder",
"(",
"canAddrEnc",
",",
"elseEnc",
"encoderFunc",
")",
"encoderFunc",
"{",
"enc",
":=",
"&",
"condAddrEncoder",
"{",
"canAddrEnc",
":",
"canAddrEnc",
",",
"elseEnc",
":",
"elseEnc",
"}",
"\n",
"return",
"enc",
".",
"encode",
"\n",... | // newCondAddrEncoder returns an encoder that checks whether its value
// CanAddr and delegates to canAddrEnc if so, else to elseEnc. | [
"newCondAddrEncoder",
"returns",
"an",
"encoder",
"that",
"checks",
"whether",
"its",
"value",
"CanAddr",
"and",
"delegates",
"to",
"canAddrEnc",
"if",
"so",
"else",
"to",
"elseEnc",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/encode.go#L836-L839 | train |
minio/mc | cmd/admin-policy-remove.go | checkAdminPolicyRemoveSyntax | func checkAdminPolicyRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
}
} | go | func checkAdminPolicyRemoveSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 2 {
cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code
}
} | [
"func",
"checkAdminPolicyRemoveSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"2",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"remove\"",
",",
"1",
")",
"\n",
"... | // checkAdminPolicyRemoveSyntax - validate all the passed arguments | [
"checkAdminPolicyRemoveSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-policy-remove.go#L51-L55 | train |
minio/mc | cmd/admin-policy-remove.go | mainAdminPolicyRemove | func mainAdminPolicyRemove(ctx *cli.Context) error {
checkAdminPolicyRemoveSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.RemoveCannedPolicy(args.Get(1))).Trace(args...), "Cannot remove policy")
printMsg(userPolicyMessage{
op: "remove",
Policy: args.Get(1),
})
return nil
} | go | func mainAdminPolicyRemove(ctx *cli.Context) error {
checkAdminPolicyRemoveSyntax(ctx)
console.SetColor("PolicyMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.RemoveCannedPolicy(args.Get(1))).Trace(args...), "Cannot remove policy")
printMsg(userPolicyMessage{
op: "remove",
Policy: args.Get(1),
})
return nil
} | [
"func",
"mainAdminPolicyRemove",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminPolicyRemoveSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"PolicyMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
"... | // mainAdminPolicyRemove is the handle for "mc admin policy remove" command. | [
"mainAdminPolicyRemove",
"is",
"the",
"handle",
"for",
"mc",
"admin",
"policy",
"remove",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-policy-remove.go#L58-L79 | train |
minio/mc | cmd/stat.go | parseStat | func parseStat(c *clientContent) statMessage {
content := statMessage{}
content.Date = c.Time.Local()
// guess file type.
content.Type = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
content.Size = c.Size
content.Key = getKey(c)
content.Metadata = c.Metadata
content.ETag = strings.TrimPrefix(c.ETag, "\"")
content.ETag = strings.TrimSuffix(content.ETag, "\"")
content.Expires = c.Expires
content.EncryptionHeaders = c.EncryptionHeaders
return content
} | go | func parseStat(c *clientContent) statMessage {
content := statMessage{}
content.Date = c.Time.Local()
// guess file type.
content.Type = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
content.Size = c.Size
content.Key = getKey(c)
content.Metadata = c.Metadata
content.ETag = strings.TrimPrefix(c.ETag, "\"")
content.ETag = strings.TrimSuffix(content.ETag, "\"")
content.Expires = c.Expires
content.EncryptionHeaders = c.EncryptionHeaders
return content
} | [
"func",
"parseStat",
"(",
"c",
"*",
"clientContent",
")",
"statMessage",
"{",
"content",
":=",
"statMessage",
"{",
"}",
"\n",
"content",
".",
"Date",
"=",
"c",
".",
"Time",
".",
"Local",
"(",
")",
"\n",
"content",
".",
"Type",
"=",
"func",
"(",
")",
... | // parseStat parses client Content container into statMessage struct. | [
"parseStat",
"parses",
"client",
"Content",
"container",
"into",
"statMessage",
"struct",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/stat.go#L95-L113 | train |
minio/mc | cmd/stat.go | statURL | func statURL(targetURL string, isIncomplete, isRecursive bool, encKeyDB map[string][]prefixSSEPair) ([]*clientContent, *probe.Error) {
var stats []*clientContent
var clnt Client
clnt, err := newClient(targetURL)
if err != nil {
return nil, err
}
targetAlias, _, _ := mustExpandAlias(targetURL)
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
}
url := targetAlias + getKey(content)
if !isRecursive && !strings.HasPrefix(url, targetURL) {
return nil, errTargetNotFound(targetURL)
}
_, stat, err := url2Stat(url, true, encKeyDB)
if err != nil {
stat = content
}
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(stat.URL.Path)
prefixPath = filepath.ToSlash(prefixPath)
// Trim prefix path from the content path.
contentURL = strings.TrimPrefix(contentURL, prefixPath)
stat.URL.Path = contentURL
stats = append(stats, stat)
}
return stats, probe.NewError(cErr)
} | go | func statURL(targetURL string, isIncomplete, isRecursive bool, encKeyDB map[string][]prefixSSEPair) ([]*clientContent, *probe.Error) {
var stats []*clientContent
var clnt Client
clnt, err := newClient(targetURL)
if err != nil {
return nil, err
}
targetAlias, _, _ := mustExpandAlias(targetURL)
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
}
url := targetAlias + getKey(content)
if !isRecursive && !strings.HasPrefix(url, targetURL) {
return nil, errTargetNotFound(targetURL)
}
_, stat, err := url2Stat(url, true, encKeyDB)
if err != nil {
stat = content
}
// Convert any os specific delimiters to "/".
contentURL := filepath.ToSlash(stat.URL.Path)
prefixPath = filepath.ToSlash(prefixPath)
// Trim prefix path from the content path.
contentURL = strings.TrimPrefix(contentURL, prefixPath)
stat.URL.Path = contentURL
stats = append(stats, stat)
}
return stats, probe.NewError(cErr)
} | [
"func",
"statURL",
"(",
"targetURL",
"string",
",",
"isIncomplete",
",",
"isRecursive",
"bool",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"(",
"[",
"]",
"*",
"clientContent",
",",
"*",
"probe",
".",
"Error",
")",
"{",
... | // statURL - simple or recursive listing | [
"statURL",
"-",
"simple",
"or",
"recursive",
"listing"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/stat.go#L116-L176 | train |
minio/mc | cmd/share-list-main.go | checkShareListSyntax | func checkShareListSyntax(ctx *cli.Context) {
args := ctx.Args()
if !args.Present() || (args.First() != "upload" && args.First() != "download") {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code.
}
} | go | func checkShareListSyntax(ctx *cli.Context) {
args := ctx.Args()
if !args.Present() || (args.First() != "upload" && args.First() != "download") {
cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code.
}
} | [
"func",
"checkShareListSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"if",
"!",
"args",
".",
"Present",
"(",
")",
"||",
"(",
"args",
".",
"First",
"(",
")",
"!=",
"\"upload\"",
"&&",
... | // validate command-line args. | [
"validate",
"command",
"-",
"line",
"args",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-list-main.go#L58-L63 | train |
minio/mc | cmd/share-list-main.go | doShareList | func doShareList(cmd string) *probe.Error {
if cmd != "upload" && cmd != "download" {
return probe.NewError(fmt.Errorf("Unknown argument `%s` passed", cmd))
}
// Fetch defaults.
uploadsFile := getShareUploadsFile()
downloadsFile := getShareDownloadsFile()
// Load previously saved upload-shares.
shareDB := newShareDBV1()
// if upload - read uploads file.
if cmd == "upload" {
if err := shareDB.Load(uploadsFile); err != nil {
return err.Trace(uploadsFile)
}
}
// if download - read downloads file.
if cmd == "download" {
if err := shareDB.Load(downloadsFile); err != nil {
return err.Trace(downloadsFile)
}
}
// Print previously shared entries.
for shareURL, share := range shareDB.Shares {
printMsg(shareMesssage{
ObjectURL: share.URL,
ShareURL: shareURL,
TimeLeft: share.Expiry - time.Since(share.Date),
ContentType: share.ContentType,
})
}
return nil
} | go | func doShareList(cmd string) *probe.Error {
if cmd != "upload" && cmd != "download" {
return probe.NewError(fmt.Errorf("Unknown argument `%s` passed", cmd))
}
// Fetch defaults.
uploadsFile := getShareUploadsFile()
downloadsFile := getShareDownloadsFile()
// Load previously saved upload-shares.
shareDB := newShareDBV1()
// if upload - read uploads file.
if cmd == "upload" {
if err := shareDB.Load(uploadsFile); err != nil {
return err.Trace(uploadsFile)
}
}
// if download - read downloads file.
if cmd == "download" {
if err := shareDB.Load(downloadsFile); err != nil {
return err.Trace(downloadsFile)
}
}
// Print previously shared entries.
for shareURL, share := range shareDB.Shares {
printMsg(shareMesssage{
ObjectURL: share.URL,
ShareURL: shareURL,
TimeLeft: share.Expiry - time.Since(share.Date),
ContentType: share.ContentType,
})
}
return nil
} | [
"func",
"doShareList",
"(",
"cmd",
"string",
")",
"*",
"probe",
".",
"Error",
"{",
"if",
"cmd",
"!=",
"\"upload\"",
"&&",
"cmd",
"!=",
"\"download\"",
"{",
"return",
"probe",
".",
"NewError",
"(",
"fmt",
".",
"Errorf",
"(",
"\"Unknown argument `%s` passed\""... | // doShareList list shared url's. | [
"doShareList",
"list",
"shared",
"url",
"s",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-list-main.go#L66-L102 | train |
minio/mc | cmd/share-list-main.go | mainShareList | func mainShareList(ctx *cli.Context) error {
// validate command-line args.
checkShareListSyntax(ctx)
// Additional command speific theme customization.
shareSetColor()
// Initialize share config folder.
initShareConfig()
// List shares.
fatalIf(doShareList(ctx.Args().First()).Trace(), "Unable to list previously shared URLs.")
return nil
} | go | func mainShareList(ctx *cli.Context) error {
// validate command-line args.
checkShareListSyntax(ctx)
// Additional command speific theme customization.
shareSetColor()
// Initialize share config folder.
initShareConfig()
// List shares.
fatalIf(doShareList(ctx.Args().First()).Trace(), "Unable to list previously shared URLs.")
return nil
} | [
"func",
"mainShareList",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkShareListSyntax",
"(",
"ctx",
")",
"\n",
"shareSetColor",
"(",
")",
"\n",
"initShareConfig",
"(",
")",
"\n",
"fatalIf",
"(",
"doShareList",
"(",
"ctx",
".",
"Args",
... | // main entry point for share list. | [
"main",
"entry",
"point",
"for",
"share",
"list",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-list-main.go#L105-L119 | train |
minio/mc | cmd/share-db-v1.go | newShareDBV1 | func newShareDBV1() *shareDBV1 {
s := &shareDBV1{
Version: "1",
}
s.Shares = make(map[string]shareEntryV1)
s.mutex = &sync.Mutex{}
return s
} | go | func newShareDBV1() *shareDBV1 {
s := &shareDBV1{
Version: "1",
}
s.Shares = make(map[string]shareEntryV1)
s.mutex = &sync.Mutex{}
return s
} | [
"func",
"newShareDBV1",
"(",
")",
"*",
"shareDBV1",
"{",
"s",
":=",
"&",
"shareDBV1",
"{",
"Version",
":",
"\"1\"",
",",
"}",
"\n",
"s",
".",
"Shares",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"shareEntryV1",
")",
"\n",
"s",
".",
"mutex",
"=",
... | // Instantiate a new uploads structure for persistence. | [
"Instantiate",
"a",
"new",
"uploads",
"structure",
"for",
"persistence",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-db-v1.go#L46-L53 | train |
minio/mc | cmd/share-db-v1.go | Set | func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration, contentType string) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.Shares[shareURL] = shareEntryV1{
URL: objectURL,
Date: UTCNow(),
Expiry: expiry,
ContentType: contentType,
}
} | go | func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration, contentType string) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.Shares[shareURL] = shareEntryV1{
URL: objectURL,
Date: UTCNow(),
Expiry: expiry,
ContentType: contentType,
}
} | [
"func",
"(",
"s",
"*",
"shareDBV1",
")",
"Set",
"(",
"objectURL",
"string",
",",
"shareURL",
"string",
",",
"expiry",
"time",
".",
"Duration",
",",
"contentType",
"string",
")",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
... | // Set upload info for each share. | [
"Set",
"upload",
"info",
"for",
"each",
"share",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-db-v1.go#L56-L66 | train |
minio/mc | cmd/share-db-v1.go | Delete | func (s *shareDBV1) Delete(objectURL string) {
s.mutex.Lock()
defer s.mutex.Unlock()
delete(s.Shares, objectURL)
} | go | func (s *shareDBV1) Delete(objectURL string) {
s.mutex.Lock()
defer s.mutex.Unlock()
delete(s.Shares, objectURL)
} | [
"func",
"(",
"s",
"*",
"shareDBV1",
")",
"Delete",
"(",
"objectURL",
"string",
")",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"Shares",
",",
"objectURL... | // Delete upload info if it exists. | [
"Delete",
"upload",
"info",
"if",
"it",
"exists",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-db-v1.go#L69-L74 | train |
minio/mc | cmd/share-db-v1.go | deleteAllExpired | func (s *shareDBV1) deleteAllExpired() {
for shareURL, share := range s.Shares {
if (share.Expiry - time.Since(share.Date)) <= 0 {
// Expired entry. Safe to drop.
delete(s.Shares, shareURL)
}
}
} | go | func (s *shareDBV1) deleteAllExpired() {
for shareURL, share := range s.Shares {
if (share.Expiry - time.Since(share.Date)) <= 0 {
// Expired entry. Safe to drop.
delete(s.Shares, shareURL)
}
}
} | [
"func",
"(",
"s",
"*",
"shareDBV1",
")",
"deleteAllExpired",
"(",
")",
"{",
"for",
"shareURL",
",",
"share",
":=",
"range",
"s",
".",
"Shares",
"{",
"if",
"(",
"share",
".",
"Expiry",
"-",
"time",
".",
"Since",
"(",
"share",
".",
"Date",
")",
")",
... | // Delete all expired uploads. | [
"Delete",
"all",
"expired",
"uploads",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-db-v1.go#L77-L84 | train |
minio/mc | cmd/share-db-v1.go | Load | func (s *shareDBV1) Load(filename string) *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
// Check if the db file exist.
if _, e := os.Stat(filename); e != nil {
return probe.NewError(e)
}
// Initialize and load using quick package.
qs, e := quick.NewConfig(newShareDBV1(), nil)
if e != nil {
return probe.NewError(e).Trace(filename)
}
e = qs.Load(filename)
if e != nil {
return probe.NewError(e).Trace(filename)
}
// Copy map over.
for k, v := range qs.Data().(*shareDBV1).Shares {
s.Shares[k] = v
}
// Filter out expired entries and save changes back to disk.
s.deleteAllExpired()
s.save(filename)
return nil
} | go | func (s *shareDBV1) Load(filename string) *probe.Error {
s.mutex.Lock()
defer s.mutex.Unlock()
// Check if the db file exist.
if _, e := os.Stat(filename); e != nil {
return probe.NewError(e)
}
// Initialize and load using quick package.
qs, e := quick.NewConfig(newShareDBV1(), nil)
if e != nil {
return probe.NewError(e).Trace(filename)
}
e = qs.Load(filename)
if e != nil {
return probe.NewError(e).Trace(filename)
}
// Copy map over.
for k, v := range qs.Data().(*shareDBV1).Shares {
s.Shares[k] = v
}
// Filter out expired entries and save changes back to disk.
s.deleteAllExpired()
s.save(filename)
return nil
} | [
"func",
"(",
"s",
"*",
"shareDBV1",
")",
"Load",
"(",
"filename",
"string",
")",
"*",
"probe",
".",
"Error",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"e",
... | // Load shareDB entries from disk. Any entries held in memory are reset. | [
"Load",
"shareDB",
"entries",
"from",
"disk",
".",
"Any",
"entries",
"held",
"in",
"memory",
"are",
"reset",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-db-v1.go#L87-L116 | train |
minio/mc | cmd/print.go | printMsg | func printMsg(msg message) {
if !globalJSON {
console.Println(msg.String())
} else {
console.Println(msg.JSON())
}
} | go | func printMsg(msg message) {
if !globalJSON {
console.Println(msg.String())
} else {
console.Println(msg.JSON())
}
} | [
"func",
"printMsg",
"(",
"msg",
"message",
")",
"{",
"if",
"!",
"globalJSON",
"{",
"console",
".",
"Println",
"(",
"msg",
".",
"String",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"console",
".",
"Println",
"(",
"msg",
".",
"JSON",
"(",
")",
")",
"\n... | // printMsg prints message string or JSON structure depending on the type of output console. | [
"printMsg",
"prints",
"message",
"string",
"or",
"JSON",
"structure",
"depending",
"on",
"the",
"type",
"of",
"output",
"console",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/print.go#L28-L34 | train |
minio/mc | cmd/admin-user-add.go | checkAdminUserAddSyntax | func checkAdminUserAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 4 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
} | go | func checkAdminUserAddSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 4 {
cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code
}
} | [
"func",
"checkAdminUserAddSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"4",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"add\"",
",",
"1",
")",
"\n",
"}",
"\... | // checkAdminUserAddSyntax - validate all the passed arguments | [
"checkAdminUserAddSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-add.go#L54-L58 | train |
minio/mc | cmd/admin-user-add.go | mainAdminUserAdd | func mainAdminUserAdd(ctx *cli.Context) error {
checkAdminUserAddSyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.AddUser(args.Get(1), args.Get(2))).Trace(args...), "Cannot add new user")
fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(3))).Trace(args...), "Cannot set user policy for new user")
printMsg(userMessage{
op: "add",
AccessKey: args.Get(1),
SecretKey: args.Get(2),
UserStatus: "enabled",
})
return nil
} | go | func mainAdminUserAdd(ctx *cli.Context) error {
checkAdminUserAddSyntax(ctx)
console.SetColor("UserMessage", color.New(color.FgGreen))
// Get the alias parameter from cli
args := ctx.Args()
aliasedURL := args.Get(0)
// Create a new MinIO Admin Client
client, err := newAdminClient(aliasedURL)
fatalIf(err, "Cannot get a configured admin connection.")
fatalIf(probe.NewError(client.AddUser(args.Get(1), args.Get(2))).Trace(args...), "Cannot add new user")
fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(3))).Trace(args...), "Cannot set user policy for new user")
printMsg(userMessage{
op: "add",
AccessKey: args.Get(1),
SecretKey: args.Get(2),
UserStatus: "enabled",
})
return nil
} | [
"func",
"mainAdminUserAdd",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminUserAddSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"UserMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
")",
... | // mainAdminUserAdd is the handle for "mc admin user add" command. | [
"mainAdminUserAdd",
"is",
"the",
"handle",
"for",
"mc",
"admin",
"user",
"add",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-add.go#L106-L131 | train |
minio/mc | cmd/admin-config-set.go | checkAdminConfigSetSyntax | func checkAdminConfigSetSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
}
} | go | func checkAdminConfigSetSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "set", 1) // last argument is exit code
}
} | [
"func",
"checkAdminConfigSetSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"2",
"{",
"cli",
".",
"ShowCommandHel... | // checkAdminConfigSetSyntax - validate all the passed arguments | [
"checkAdminConfigSetSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-config-set.go#L86-L90 | train |
minio/mc | cmd/admin-config-set.go | mainAdminConfigSet | func mainAdminConfigSet(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigSetSyntax(ctx)
// Set color preference of command outputs
console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold))
// 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.")
// Call get config API
fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server configuration file.")
// Print set config result
printMsg(configSetMessage{
setConfigStatus: true,
})
return nil
} | go | func mainAdminConfigSet(ctx *cli.Context) error {
// Check command arguments
checkAdminConfigSetSyntax(ctx)
// Set color preference of command outputs
console.SetColor("SetConfigSuccess", color.New(color.FgGreen, color.Bold))
console.SetColor("SetConfigFailure", color.New(color.FgRed, color.Bold))
// 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.")
// Call get config API
fatalIf(probe.NewError(client.SetConfig(os.Stdin)), "Cannot set server configuration file.")
// Print set config result
printMsg(configSetMessage{
setConfigStatus: true,
})
return nil
} | [
"func",
"mainAdminConfigSet",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkAdminConfigSetSyntax",
"(",
"ctx",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"SetConfigSuccess\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
",",... | // main config set function | [
"main",
"config",
"set",
"function"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-config-set.go#L93-L119 | train |
minio/mc | cmd/utils.go | newRandomID | func newRandomID(n int) string {
rand.Seed(UTCNow().UnixNano())
sid := make([]rune, n)
for i := range sid {
sid[i] = letters[rand.Intn(len(letters))]
}
return string(sid)
} | go | func newRandomID(n int) string {
rand.Seed(UTCNow().UnixNano())
sid := make([]rune, n)
for i := range sid {
sid[i] = letters[rand.Intn(len(letters))]
}
return string(sid)
} | [
"func",
"newRandomID",
"(",
"n",
"int",
")",
"string",
"{",
"rand",
".",
"Seed",
"(",
"UTCNow",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"sid",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"n",
")",
"\n",
"for",
"i",
":=",
"range",
"sid",
... | // newRandomID generates a random id of regular lower case and uppercase english characters. | [
"newRandomID",
"generates",
"a",
"random",
"id",
"of",
"regular",
"lower",
"case",
"and",
"uppercase",
"english",
"characters",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L70-L77 | train |
minio/mc | cmd/utils.go | dumpTLSCertificates | func dumpTLSCertificates(t *tls.ConnectionState) {
for _, cert := range t.PeerCertificates {
console.Debugln("TLS Certificate found: ")
if len(cert.Issuer.Country) > 0 {
console.Debugln(" >> Country: " + cert.Issuer.Country[0])
}
if len(cert.Issuer.Organization) > 0 {
console.Debugln(" >> Organization: " + cert.Issuer.Organization[0])
}
console.Debugln(" >> Expires: " + cert.NotAfter.String())
}
} | go | func dumpTLSCertificates(t *tls.ConnectionState) {
for _, cert := range t.PeerCertificates {
console.Debugln("TLS Certificate found: ")
if len(cert.Issuer.Country) > 0 {
console.Debugln(" >> Country: " + cert.Issuer.Country[0])
}
if len(cert.Issuer.Organization) > 0 {
console.Debugln(" >> Organization: " + cert.Issuer.Organization[0])
}
console.Debugln(" >> Expires: " + cert.NotAfter.String())
}
} | [
"func",
"dumpTLSCertificates",
"(",
"t",
"*",
"tls",
".",
"ConnectionState",
")",
"{",
"for",
"_",
",",
"cert",
":=",
"range",
"t",
".",
"PeerCertificates",
"{",
"console",
".",
"Debugln",
"(",
"\"TLS Certificate found: \"",
")",
"\n",
"if",
"len",
"(",
"c... | // dumpTlsCertificates prints some fields of the certificates received from the server.
// Fields will be inspected by the user, so they must be conscise and useful | [
"dumpTlsCertificates",
"prints",
"some",
"fields",
"of",
"the",
"certificates",
"received",
"from",
"the",
"server",
".",
"Fields",
"will",
"be",
"inspected",
"by",
"the",
"user",
"so",
"they",
"must",
"be",
"conscise",
"and",
"useful"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L99-L110 | train |
minio/mc | cmd/utils.go | splitStr | func splitStr(path, sep string, n int) []string {
splits := strings.SplitN(path, sep, n)
// Add empty strings if we found elements less than nr
for i := n - len(splits); i > 0; i-- {
splits = append(splits, "")
}
return splits
} | go | func splitStr(path, sep string, n int) []string {
splits := strings.SplitN(path, sep, n)
// Add empty strings if we found elements less than nr
for i := n - len(splits); i > 0; i-- {
splits = append(splits, "")
}
return splits
} | [
"func",
"splitStr",
"(",
"path",
",",
"sep",
"string",
",",
"n",
"int",
")",
"[",
"]",
"string",
"{",
"splits",
":=",
"strings",
".",
"SplitN",
"(",
"path",
",",
"sep",
",",
"n",
")",
"\n",
"for",
"i",
":=",
"n",
"-",
"len",
"(",
"splits",
")",... | // splitStr splits a string into n parts, empty strings are added
// if we are not able to reach n elements | [
"splitStr",
"splits",
"a",
"string",
"into",
"n",
"parts",
"empty",
"strings",
"are",
"added",
"if",
"we",
"are",
"not",
"able",
"to",
"reach",
"n",
"elements"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L119-L126 | train |
minio/mc | cmd/utils.go | newS3Config | func newS3Config(urlStr string, hostCfg *hostConfigV9) *Config {
// We have a valid alias and hostConfig. We populate the
// credentials from the match found in the config file.
s3Config := new(Config)
s3Config.AppName = "mc"
s3Config.AppVersion = Version
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
s3Config.Debug = globalDebug
s3Config.Insecure = globalInsecure
s3Config.HostURL = urlStr
if hostCfg != nil {
s3Config.AccessKey = hostCfg.AccessKey
s3Config.SecretKey = hostCfg.SecretKey
s3Config.Signature = hostCfg.API
}
s3Config.Lookup = getLookupType(hostCfg.Lookup)
return s3Config
} | go | func newS3Config(urlStr string, hostCfg *hostConfigV9) *Config {
// We have a valid alias and hostConfig. We populate the
// credentials from the match found in the config file.
s3Config := new(Config)
s3Config.AppName = "mc"
s3Config.AppVersion = Version
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
s3Config.Debug = globalDebug
s3Config.Insecure = globalInsecure
s3Config.HostURL = urlStr
if hostCfg != nil {
s3Config.AccessKey = hostCfg.AccessKey
s3Config.SecretKey = hostCfg.SecretKey
s3Config.Signature = hostCfg.API
}
s3Config.Lookup = getLookupType(hostCfg.Lookup)
return s3Config
} | [
"func",
"newS3Config",
"(",
"urlStr",
"string",
",",
"hostCfg",
"*",
"hostConfigV9",
")",
"*",
"Config",
"{",
"s3Config",
":=",
"new",
"(",
"Config",
")",
"\n",
"s3Config",
".",
"AppName",
"=",
"\"mc\"",
"\n",
"s3Config",
".",
"AppVersion",
"=",
"Version",... | // newS3Config simply creates a new Config struct using the passed
// parameters. | [
"newS3Config",
"simply",
"creates",
"a",
"new",
"Config",
"struct",
"using",
"the",
"passed",
"parameters",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L130-L149 | train |
minio/mc | cmd/utils.go | lineTrunc | func lineTrunc(content string, maxLen int) string {
runes := []rune(content)
rlen := len(runes)
if rlen <= maxLen {
return content
}
halfLen := maxLen / 2
fstPart := string(runes[0:halfLen])
sndPart := string(runes[rlen-halfLen:])
return fstPart + "…" + sndPart
} | go | func lineTrunc(content string, maxLen int) string {
runes := []rune(content)
rlen := len(runes)
if rlen <= maxLen {
return content
}
halfLen := maxLen / 2
fstPart := string(runes[0:halfLen])
sndPart := string(runes[rlen-halfLen:])
return fstPart + "…" + sndPart
} | [
"func",
"lineTrunc",
"(",
"content",
"string",
",",
"maxLen",
"int",
")",
"string",
"{",
"runes",
":=",
"[",
"]",
"rune",
"(",
"content",
")",
"\n",
"rlen",
":=",
"len",
"(",
"runes",
")",
"\n",
"if",
"rlen",
"<=",
"maxLen",
"{",
"return",
"content",... | // lineTrunc - truncates a string to the given maximum length by
// adding ellipsis in the middle | [
"lineTrunc",
"-",
"truncates",
"a",
"string",
"to",
"the",
"given",
"maximum",
"length",
"by",
"adding",
"ellipsis",
"in",
"the",
"middle"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L153-L163 | train |
minio/mc | cmd/utils.go | isOlder | func isOlder(ti time.Time, olderRef string) bool {
objectAge := UTCNow().Sub(ti)
var e error
var olderThan time.Duration
if olderRef != "" {
olderThan, e = ioutils.ParseDurationTime(olderRef)
fatalIf(probe.NewError(e), "Unable to parse olderThan=`"+olderRef+"`.")
}
return objectAge < olderThan
} | go | func isOlder(ti time.Time, olderRef string) bool {
objectAge := UTCNow().Sub(ti)
var e error
var olderThan time.Duration
if olderRef != "" {
olderThan, e = ioutils.ParseDurationTime(olderRef)
fatalIf(probe.NewError(e), "Unable to parse olderThan=`"+olderRef+"`.")
}
return objectAge < olderThan
} | [
"func",
"isOlder",
"(",
"ti",
"time",
".",
"Time",
",",
"olderRef",
"string",
")",
"bool",
"{",
"objectAge",
":=",
"UTCNow",
"(",
")",
".",
"Sub",
"(",
"ti",
")",
"\n",
"var",
"e",
"error",
"\n",
"var",
"olderThan",
"time",
".",
"Duration",
"\n",
"... | // isOlder returns true if the passed object is older than olderRef | [
"isOlder",
"returns",
"true",
"if",
"the",
"passed",
"object",
"is",
"older",
"than",
"olderRef"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L166-L175 | train |
minio/mc | cmd/utils.go | isNewer | func isNewer(ti time.Time, newerRef string) bool {
objectAge := UTCNow().Sub(ti)
var e error
var newerThan time.Duration
if newerRef != "" {
newerThan, e = ioutils.ParseDurationTime(newerRef)
fatalIf(probe.NewError(e), "Unable to parse newerThan=`"+newerRef+"`.")
}
return objectAge >= newerThan
} | go | func isNewer(ti time.Time, newerRef string) bool {
objectAge := UTCNow().Sub(ti)
var e error
var newerThan time.Duration
if newerRef != "" {
newerThan, e = ioutils.ParseDurationTime(newerRef)
fatalIf(probe.NewError(e), "Unable to parse newerThan=`"+newerRef+"`.")
}
return objectAge >= newerThan
} | [
"func",
"isNewer",
"(",
"ti",
"time",
".",
"Time",
",",
"newerRef",
"string",
")",
"bool",
"{",
"objectAge",
":=",
"UTCNow",
"(",
")",
".",
"Sub",
"(",
"ti",
")",
"\n",
"var",
"e",
"error",
"\n",
"var",
"newerThan",
"time",
".",
"Duration",
"\n",
"... | // isNewer returns true if the passed object is newer than newerRef | [
"isNewer",
"returns",
"true",
"if",
"the",
"passed",
"object",
"is",
"newer",
"than",
"newerRef"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L178-L187 | train |
minio/mc | cmd/utils.go | getLookupType | func getLookupType(l string) minio.BucketLookupType {
l = strings.ToLower(l)
switch l {
case "dns":
return minio.BucketLookupDNS
case "path":
return minio.BucketLookupPath
}
return minio.BucketLookupAuto
} | go | func getLookupType(l string) minio.BucketLookupType {
l = strings.ToLower(l)
switch l {
case "dns":
return minio.BucketLookupDNS
case "path":
return minio.BucketLookupPath
}
return minio.BucketLookupAuto
} | [
"func",
"getLookupType",
"(",
"l",
"string",
")",
"minio",
".",
"BucketLookupType",
"{",
"l",
"=",
"strings",
".",
"ToLower",
"(",
"l",
")",
"\n",
"switch",
"l",
"{",
"case",
"\"dns\"",
":",
"return",
"minio",
".",
"BucketLookupDNS",
"\n",
"case",
"\"pat... | // getLookupType returns the minio.BucketLookupType for lookup
// option entered on the command line | [
"getLookupType",
"returns",
"the",
"minio",
".",
"BucketLookupType",
"for",
"lookup",
"option",
"entered",
"on",
"the",
"command",
"line"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L191-L200 | train |
minio/mc | cmd/utils.go | parseAndValidateEncryptionKeys | func parseAndValidateEncryptionKeys(sseKeys string, sse string) (encMap map[string][]prefixSSEPair, err *probe.Error) {
encMap, err = parseEncryptionKeys(sseKeys)
if err != nil {
return nil, err
}
if sse != "" {
for _, prefix := range strings.Split(sse, ",") {
alias, _ := url2Alias(prefix)
encMap[alias] = append(encMap[alias], prefixSSEPair{
Prefix: prefix,
SSE: encrypt.NewSSE(),
})
}
}
for alias, ps := range encMap {
if hostCfg := mustGetHostConfig(alias); hostCfg == nil {
for _, p := range ps {
return nil, probe.NewError(errors.New("SSE prefix " + p.Prefix + " has invalid alias"))
}
}
}
return encMap, nil
} | go | func parseAndValidateEncryptionKeys(sseKeys string, sse string) (encMap map[string][]prefixSSEPair, err *probe.Error) {
encMap, err = parseEncryptionKeys(sseKeys)
if err != nil {
return nil, err
}
if sse != "" {
for _, prefix := range strings.Split(sse, ",") {
alias, _ := url2Alias(prefix)
encMap[alias] = append(encMap[alias], prefixSSEPair{
Prefix: prefix,
SSE: encrypt.NewSSE(),
})
}
}
for alias, ps := range encMap {
if hostCfg := mustGetHostConfig(alias); hostCfg == nil {
for _, p := range ps {
return nil, probe.NewError(errors.New("SSE prefix " + p.Prefix + " has invalid alias"))
}
}
}
return encMap, nil
} | [
"func",
"parseAndValidateEncryptionKeys",
"(",
"sseKeys",
"string",
",",
"sse",
"string",
")",
"(",
"encMap",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
",",
"err",
"*",
"probe",
".",
"Error",
")",
"{",
"encMap",
",",
"err",
"=",
"parseEncryptio... | // parse and validate encryption keys entered on command line | [
"parse",
"and",
"validate",
"encryption",
"keys",
"entered",
"on",
"command",
"line"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L209-L231 | train |
minio/mc | cmd/utils.go | getSSE | func getSSE(resource string, encKeys []prefixSSEPair) encrypt.ServerSide {
for _, k := range encKeys {
if strings.HasPrefix(resource, k.Prefix) {
return k.SSE
}
}
return nil
} | go | func getSSE(resource string, encKeys []prefixSSEPair) encrypt.ServerSide {
for _, k := range encKeys {
if strings.HasPrefix(resource, k.Prefix) {
return k.SSE
}
}
return nil
} | [
"func",
"getSSE",
"(",
"resource",
"string",
",",
"encKeys",
"[",
"]",
"prefixSSEPair",
")",
"encrypt",
".",
"ServerSide",
"{",
"for",
"_",
",",
"k",
":=",
"range",
"encKeys",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"resource",
",",
"k",
".",
"Pre... | // get SSE Key if object prefix matches with given resource. | [
"get",
"SSE",
"Key",
"if",
"object",
"prefix",
"matches",
"with",
"given",
"resource",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/utils.go#L295-L302 | train |
minio/mc | cmd/config.go | getMcConfigDir | func getMcConfigDir() (string, *probe.Error) {
if mcCustomConfigDir != "" {
return mcCustomConfigDir, nil
}
homeDir, e := homedir.Dir()
if e != nil {
return "", probe.NewError(e)
}
var configDir string
// For windows the path is slightly different
if runtime.GOOS == "windows" {
configDir = filepath.Join(homeDir, globalMCConfigWindowsDir)
} else {
configDir = filepath.Join(homeDir, globalMCConfigDir)
}
return configDir, nil
} | go | func getMcConfigDir() (string, *probe.Error) {
if mcCustomConfigDir != "" {
return mcCustomConfigDir, nil
}
homeDir, e := homedir.Dir()
if e != nil {
return "", probe.NewError(e)
}
var configDir string
// For windows the path is slightly different
if runtime.GOOS == "windows" {
configDir = filepath.Join(homeDir, globalMCConfigWindowsDir)
} else {
configDir = filepath.Join(homeDir, globalMCConfigDir)
}
return configDir, nil
} | [
"func",
"getMcConfigDir",
"(",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"if",
"mcCustomConfigDir",
"!=",
"\"\"",
"{",
"return",
"mcCustomConfigDir",
",",
"nil",
"\n",
"}",
"\n",
"homeDir",
",",
"e",
":=",
"homedir",
".",
"Dir",
"(... | // getMcConfigDir - construct MinIO Client config folder. | [
"getMcConfigDir",
"-",
"construct",
"MinIO",
"Client",
"config",
"folder",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L41-L57 | train |
minio/mc | cmd/config.go | mustGetMcConfigDir | func mustGetMcConfigDir() (configDir string) {
configDir, err := getMcConfigDir()
fatalIf(err.Trace(), "Unable to get mcConfigDir.")
return configDir
} | go | func mustGetMcConfigDir() (configDir string) {
configDir, err := getMcConfigDir()
fatalIf(err.Trace(), "Unable to get mcConfigDir.")
return configDir
} | [
"func",
"mustGetMcConfigDir",
"(",
")",
"(",
"configDir",
"string",
")",
"{",
"configDir",
",",
"err",
":=",
"getMcConfigDir",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
")",
",",
"\"Unable to get mcConfigDir.\"",
")",
"\n",
"return",
"configD... | // mustGetMcConfigDir - construct MinIO Client config folder or fail | [
"mustGetMcConfigDir",
"-",
"construct",
"MinIO",
"Client",
"config",
"folder",
"or",
"fail"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L60-L65 | train |
minio/mc | cmd/config.go | createMcConfigDir | func createMcConfigDir() *probe.Error {
p, err := getMcConfigDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | go | func createMcConfigDir() *probe.Error {
p, err := getMcConfigDir()
if err != nil {
return err.Trace()
}
if e := os.MkdirAll(p, 0700); e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"createMcConfigDir",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"p",
",",
"err",
":=",
"getMcConfigDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
".",
"Trace",
"(",
")",
"\n",
"}",
"\n",
"if",
"e",
":=",
"os",
".",
... | // createMcConfigDir - create MinIO Client config folder | [
"createMcConfigDir",
"-",
"create",
"MinIO",
"Client",
"config",
"folder"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L68-L77 | train |
minio/mc | cmd/config.go | getMcConfigPath | func getMcConfigPath() (string, *probe.Error) {
if mcCustomConfigDir != "" {
return filepath.Join(mcCustomConfigDir, globalMCConfigFile), nil
}
dir, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(dir, globalMCConfigFile), nil
} | go | func getMcConfigPath() (string, *probe.Error) {
if mcCustomConfigDir != "" {
return filepath.Join(mcCustomConfigDir, globalMCConfigFile), nil
}
dir, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
return filepath.Join(dir, globalMCConfigFile), nil
} | [
"func",
"getMcConfigPath",
"(",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"if",
"mcCustomConfigDir",
"!=",
"\"\"",
"{",
"return",
"filepath",
".",
"Join",
"(",
"mcCustomConfigDir",
",",
"globalMCConfigFile",
")",
",",
"nil",
"\n",
"}",... | // getMcConfigPath - construct MinIO Client configuration path | [
"getMcConfigPath",
"-",
"construct",
"MinIO",
"Client",
"configuration",
"path"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L80-L89 | train |
minio/mc | cmd/config.go | loadMcConfigFactory | func loadMcConfigFactory() func() (*configV9, *probe.Error) {
// Load once and cache in a closure.
cfgCache, err := loadConfigV9()
// loadMcConfig - reads configuration file and returns config.
return func() (*configV9, *probe.Error) {
return cfgCache, err
}
} | go | func loadMcConfigFactory() func() (*configV9, *probe.Error) {
// Load once and cache in a closure.
cfgCache, err := loadConfigV9()
// loadMcConfig - reads configuration file and returns config.
return func() (*configV9, *probe.Error) {
return cfgCache, err
}
} | [
"func",
"loadMcConfigFactory",
"(",
")",
"func",
"(",
")",
"(",
"*",
"configV9",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"cfgCache",
",",
"err",
":=",
"loadConfigV9",
"(",
")",
"\n",
"return",
"func",
"(",
")",
"(",
"*",
"configV9",
",",
"*",
"p... | // loadMcConfigCached - returns loadMcConfig with a closure for config cache. | [
"loadMcConfigCached",
"-",
"returns",
"loadMcConfig",
"with",
"a",
"closure",
"for",
"config",
"cache",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L107-L115 | train |
minio/mc | cmd/config.go | saveMcConfig | func saveMcConfig(config *configV9) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
err := createMcConfigDir()
if err != nil {
return err.Trace(mustGetMcConfigDir())
}
// Save the config.
if err := saveConfigV9(config); err != nil {
return err.Trace(mustGetMcConfigPath())
}
// Refresh the config cache.
loadMcConfig = loadMcConfigFactory()
return nil
} | go | func saveMcConfig(config *configV9) *probe.Error {
if config == nil {
return errInvalidArgument().Trace()
}
err := createMcConfigDir()
if err != nil {
return err.Trace(mustGetMcConfigDir())
}
// Save the config.
if err := saveConfigV9(config); err != nil {
return err.Trace(mustGetMcConfigPath())
}
// Refresh the config cache.
loadMcConfig = loadMcConfigFactory()
return nil
} | [
"func",
"saveMcConfig",
"(",
"config",
"*",
"configV9",
")",
"*",
"probe",
".",
"Error",
"{",
"if",
"config",
"==",
"nil",
"{",
"return",
"errInvalidArgument",
"(",
")",
".",
"Trace",
"(",
")",
"\n",
"}",
"\n",
"err",
":=",
"createMcConfigDir",
"(",
")... | // saveMcConfig - saves configuration file and returns error if any. | [
"saveMcConfig",
"-",
"saves",
"configuration",
"file",
"and",
"returns",
"error",
"if",
"any",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L121-L139 | train |
minio/mc | cmd/config.go | isMcConfigExists | func isMcConfigExists() bool {
configFile, err := getMcConfigPath()
if err != nil {
return false
}
if _, e := os.Stat(configFile); e != nil {
return false
}
return true
} | go | func isMcConfigExists() bool {
configFile, err := getMcConfigPath()
if err != nil {
return false
}
if _, e := os.Stat(configFile); e != nil {
return false
}
return true
} | [
"func",
"isMcConfigExists",
"(",
")",
"bool",
"{",
"configFile",
",",
"err",
":=",
"getMcConfigPath",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"_",
",",
"e",
":=",
"os",
".",
"Stat",
"(",
"configFile",
... | // isMcConfigExists returns err if config doesn't exist. | [
"isMcConfigExists",
"returns",
"err",
"if",
"config",
"doesn",
"t",
"exist",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L142-L151 | train |
minio/mc | cmd/config.go | getHostConfig | func getHostConfig(alias string) (*hostConfigV9, *probe.Error) {
mcCfg, err := loadMcConfig()
if err != nil {
return nil, err.Trace(alias)
}
// if host is exact return quickly.
if _, ok := mcCfg.Hosts[alias]; ok {
hostCfg := mcCfg.Hosts[alias]
return &hostCfg, nil
}
// return error if cannot be matched.
return nil, errNoMatchingHost(alias).Trace(alias)
} | go | func getHostConfig(alias string) (*hostConfigV9, *probe.Error) {
mcCfg, err := loadMcConfig()
if err != nil {
return nil, err.Trace(alias)
}
// if host is exact return quickly.
if _, ok := mcCfg.Hosts[alias]; ok {
hostCfg := mcCfg.Hosts[alias]
return &hostCfg, nil
}
// return error if cannot be matched.
return nil, errNoMatchingHost(alias).Trace(alias)
} | [
"func",
"getHostConfig",
"(",
"alias",
"string",
")",
"(",
"*",
"hostConfigV9",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"mcCfg",
",",
"err",
":=",
"loadMcConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
".",
"... | // getHostConfig retrieves host specific configuration such as access keys, signature type. | [
"getHostConfig",
"retrieves",
"host",
"specific",
"configuration",
"such",
"as",
"access",
"keys",
"signature",
"type",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L159-L173 | train |
minio/mc | cmd/config.go | mustGetHostConfig | func mustGetHostConfig(alias string) *hostConfigV9 {
hostCfg, _ := getHostConfig(alias)
// If alias is not found,
// look for it in the environment variable.
if hostCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostPrefix + alias); ok {
hostCfg, _ = expandAliasFromEnv(envConfig)
}
}
if hostCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostsDeprecatedPrefix + alias); ok {
errorIf(errInvalidArgument().Trace(mcEnvHostsDeprecatedPrefix+alias), "`MC_HOSTS_<alias>` environment variable is deprecated. Please use `MC_HOST_<alias>` instead for the same functionality.")
hostCfg, _ = expandAliasFromEnv(envConfig)
}
}
return hostCfg
} | go | func mustGetHostConfig(alias string) *hostConfigV9 {
hostCfg, _ := getHostConfig(alias)
// If alias is not found,
// look for it in the environment variable.
if hostCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostPrefix + alias); ok {
hostCfg, _ = expandAliasFromEnv(envConfig)
}
}
if hostCfg == nil {
if envConfig, ok := os.LookupEnv(mcEnvHostsDeprecatedPrefix + alias); ok {
errorIf(errInvalidArgument().Trace(mcEnvHostsDeprecatedPrefix+alias), "`MC_HOSTS_<alias>` environment variable is deprecated. Please use `MC_HOST_<alias>` instead for the same functionality.")
hostCfg, _ = expandAliasFromEnv(envConfig)
}
}
return hostCfg
} | [
"func",
"mustGetHostConfig",
"(",
"alias",
"string",
")",
"*",
"hostConfigV9",
"{",
"hostCfg",
",",
"_",
":=",
"getHostConfig",
"(",
"alias",
")",
"\n",
"if",
"hostCfg",
"==",
"nil",
"{",
"if",
"envConfig",
",",
"ok",
":=",
"os",
".",
"LookupEnv",
"(",
... | // mustGetHostConfig retrieves host specific configuration such as access keys, signature type. | [
"mustGetHostConfig",
"retrieves",
"host",
"specific",
"configuration",
"such",
"as",
"access",
"keys",
"signature",
"type",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L176-L192 | train |
minio/mc | cmd/config.go | expandAlias | func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9, err *probe.Error) {
// Extract alias from the URL.
alias, path := url2Alias(aliasedURL)
var envConfig string
var ok bool
if envConfig, ok = os.LookupEnv(mcEnvHostPrefix + alias); !ok {
envConfig, ok = os.LookupEnv(mcEnvHostsDeprecatedPrefix + alias)
if ok {
errorIf(errInvalidArgument().Trace(mcEnvHostsDeprecatedPrefix+alias), "`MC_HOSTS_<alias>` environment variable is deprecated. Please use `MC_HOST_<alias>` instead for the same functionality.")
}
}
if ok {
hostCfg, err = expandAliasFromEnv(envConfig)
if err != nil {
return "", "", nil, err.Trace(aliasedURL)
}
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
}
// Find the matching alias entry and expand the URL.
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
}
return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is.
} | go | func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9, err *probe.Error) {
// Extract alias from the URL.
alias, path := url2Alias(aliasedURL)
var envConfig string
var ok bool
if envConfig, ok = os.LookupEnv(mcEnvHostPrefix + alias); !ok {
envConfig, ok = os.LookupEnv(mcEnvHostsDeprecatedPrefix + alias)
if ok {
errorIf(errInvalidArgument().Trace(mcEnvHostsDeprecatedPrefix+alias), "`MC_HOSTS_<alias>` environment variable is deprecated. Please use `MC_HOST_<alias>` instead for the same functionality.")
}
}
if ok {
hostCfg, err = expandAliasFromEnv(envConfig)
if err != nil {
return "", "", nil, err.Trace(aliasedURL)
}
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
}
// Find the matching alias entry and expand the URL.
if hostCfg = mustGetHostConfig(alias); hostCfg != nil {
return alias, urlJoinPath(hostCfg.URL, path), hostCfg, nil
}
return "", aliasedURL, nil, nil // No matching entry found. Return original URL as is.
} | [
"func",
"expandAlias",
"(",
"aliasedURL",
"string",
")",
"(",
"alias",
"string",
",",
"urlStr",
"string",
",",
"hostCfg",
"*",
"hostConfigV9",
",",
"err",
"*",
"probe",
".",
"Error",
")",
"{",
"alias",
",",
"path",
":=",
"url2Alias",
"(",
"aliasedURL",
"... | // expandAlias expands aliased URL if any match is found, returns as is otherwise. | [
"expandAlias",
"expands",
"aliased",
"URL",
"if",
"any",
"match",
"is",
"found",
"returns",
"as",
"is",
"otherwise",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L281-L308 | train |
minio/mc | cmd/config.go | mustExpandAlias | func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9) {
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, hostCfg
} | go | func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV9) {
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
return alias, urlStr, hostCfg
} | [
"func",
"mustExpandAlias",
"(",
"aliasedURL",
"string",
")",
"(",
"alias",
"string",
",",
"urlStr",
"string",
",",
"hostCfg",
"*",
"hostConfigV9",
")",
"{",
"alias",
",",
"urlStr",
",",
"hostCfg",
",",
"_",
"=",
"expandAlias",
"(",
"aliasedURL",
")",
"\n",... | // mustExpandAlias expands aliased URL if any match is found, returns as is otherwise. | [
"mustExpandAlias",
"expands",
"aliased",
"URL",
"if",
"any",
"match",
"is",
"found",
"returns",
"as",
"is",
"otherwise",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config.go#L311-L314 | train |
minio/mc | cmd/config-fix.go | newBrokenConfigV3 | func newBrokenConfigV3() *brokenConfigV3 {
conf := new(brokenConfigV3)
conf.Version = "3"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]brokenHostConfigV3)
return conf
} | go | func newBrokenConfigV3() *brokenConfigV3 {
conf := new(brokenConfigV3)
conf.Version = "3"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]brokenHostConfigV3)
return conf
} | [
"func",
"newBrokenConfigV3",
"(",
")",
"*",
"brokenConfigV3",
"{",
"conf",
":=",
"new",
"(",
"brokenConfigV3",
")",
"\n",
"conf",
".",
"Version",
"=",
"\"3\"",
"\n",
"conf",
".",
"Aliases",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\... | // newConfigV3 - get new config broken version 3. | [
"newConfigV3",
"-",
"get",
"new",
"config",
"broken",
"version",
"3",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-fix.go#L55-L61 | train |
minio/mc | cmd/config-old.go | newConfigV3 | func newConfigV3() *configV3 {
conf := new(configV3)
conf.Version = "3"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV3)
return conf
} | go | func newConfigV3() *configV3 {
conf := new(configV3)
conf.Version = "3"
conf.Aliases = make(map[string]string)
conf.Hosts = make(map[string]hostConfigV3)
return conf
} | [
"func",
"newConfigV3",
"(",
")",
"*",
"configV3",
"{",
"conf",
":=",
"new",
"(",
"configV3",
")",
"\n",
"conf",
".",
"Version",
"=",
"\"3\"",
"\n",
"conf",
".",
"Aliases",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"conf",
".... | // newConfigV3 - get new config version 3. | [
"newConfigV3",
"-",
"get",
"new",
"config",
"version",
"3",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-old.go#L91-L97 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.