repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
minio/mc
cmd/policy-main.go
checkPolicySyntax
func checkPolicySyntax(ctx *cli.Context) { argsLength := len(ctx.Args()) // Always print a help message when we have extra arguments if argsLength > 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code. } // Always print a help message when no arguments specified if argsLength < 1 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } firstArg := ctx.Args().Get(0) // More syntax checking switch accessPerms(firstArg) { case accessNone, accessDownload, accessUpload, accessPublic: // Always expect two arguments when a policy permission is provided if argsLength != 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } case "list": // Always expect an argument after list cmd if argsLength != 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } case "links": // Always expect an argument after links cmd if argsLength != 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } default: if argsLength == 2 && filepath.Ext(string(firstArg)) != ".json" { fatalIf(errDummy().Trace(), "Unrecognized permission `"+string(firstArg)+"`. Allowed values are [none, download, upload, public].") } } }
go
func checkPolicySyntax(ctx *cli.Context) { argsLength := len(ctx.Args()) // Always print a help message when we have extra arguments if argsLength > 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code. } // Always print a help message when no arguments specified if argsLength < 1 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } firstArg := ctx.Args().Get(0) // More syntax checking switch accessPerms(firstArg) { case accessNone, accessDownload, accessUpload, accessPublic: // Always expect two arguments when a policy permission is provided if argsLength != 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } case "list": // Always expect an argument after list cmd if argsLength != 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } case "links": // Always expect an argument after links cmd if argsLength != 2 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) } default: if argsLength == 2 && filepath.Ext(string(firstArg)) != ".json" { fatalIf(errDummy().Trace(), "Unrecognized permission `"+string(firstArg)+"`. Allowed values are [none, download, upload, public].") } } }
[ "func", "checkPolicySyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "argsLength", ":=", "len", "(", "ctx", ".", "Args", "(", ")", ")", "\n", "// Always print a help message when we have extra arguments", "if", "argsLength", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code.", "\n", "}", "\n", "// Always print a help message when no arguments specified", "if", "argsLength", "<", "1", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "\n", "}", "\n\n", "firstArg", ":=", "ctx", ".", "Args", "(", ")", ".", "Get", "(", "0", ")", "\n\n", "// More syntax checking", "switch", "accessPerms", "(", "firstArg", ")", "{", "case", "accessNone", ",", "accessDownload", ",", "accessUpload", ",", "accessPublic", ":", "// Always expect two arguments when a policy permission is provided", "if", "argsLength", "!=", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "// Always expect an argument after list cmd", "if", "argsLength", "!=", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "// Always expect an argument after links cmd", "if", "argsLength", "!=", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "\n", "}", "\n\n", "default", ":", "if", "argsLength", "==", "2", "&&", "filepath", ".", "Ext", "(", "string", "(", "firstArg", ")", ")", "!=", "\"", "\"", "{", "fatalIf", "(", "errDummy", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "string", "(", "firstArg", ")", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// checkPolicySyntax check for incoming syntax.
[ "checkPolicySyntax", "check", "for", "incoming", "syntax", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L169-L206
train
minio/mc
cmd/policy-main.go
accessPermToString
func accessPermToString(perm accessPerms) string { policy := "" switch perm { case accessNone: policy = "none" case accessDownload: policy = "readonly" case accessUpload: policy = "writeonly" case accessPublic: policy = "readwrite" case accessCustom: policy = "custom" } return policy }
go
func accessPermToString(perm accessPerms) string { policy := "" switch perm { case accessNone: policy = "none" case accessDownload: policy = "readonly" case accessUpload: policy = "writeonly" case accessPublic: policy = "readwrite" case accessCustom: policy = "custom" } return policy }
[ "func", "accessPermToString", "(", "perm", "accessPerms", ")", "string", "{", "policy", ":=", "\"", "\"", "\n", "switch", "perm", "{", "case", "accessNone", ":", "policy", "=", "\"", "\"", "\n", "case", "accessDownload", ":", "policy", "=", "\"", "\"", "\n", "case", "accessUpload", ":", "policy", "=", "\"", "\"", "\n", "case", "accessPublic", ":", "policy", "=", "\"", "\"", "\n", "case", "accessCustom", ":", "policy", "=", "\"", "\"", "\n", "}", "\n", "return", "policy", "\n", "}" ]
// Convert an accessPerms to a string recognizable by minio-go
[ "Convert", "an", "accessPerms", "to", "a", "string", "recognizable", "by", "minio", "-", "go" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L209-L224
train
minio/mc
cmd/policy-main.go
doSetAccess
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) } policy := accessPermToString(targetPERMS) if err = clnt.SetAccess(policy, false); err != nil { return err.Trace(targetURL, string(targetPERMS)) } return nil }
go
func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) } policy := accessPermToString(targetPERMS) if err = clnt.SetAccess(policy, false); err != nil { return err.Trace(targetURL, string(targetPERMS)) } return nil }
[ "func", "doSetAccess", "(", "targetURL", "string", ",", "targetPERMS", "accessPerms", ")", "*", "probe", ".", "Error", "{", "clnt", ",", "err", ":=", "newClient", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n", "policy", ":=", "accessPermToString", "(", "targetPERMS", ")", "\n", "if", "err", "=", "clnt", ".", "SetAccess", "(", "policy", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "targetURL", ",", "string", "(", "targetPERMS", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// doSetAccess do set access.
[ "doSetAccess", "do", "set", "access", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L227-L237
train
minio/mc
cmd/policy-main.go
doSetAccessJSON
func doSetAccessJSON(targetURL string, targetPERMS accessPerms) *probe.Error { clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) } fileReader, e := os.Open(string(targetPERMS)) if e != nil { fatalIf(probe.NewError(e).Trace(), "Unable to set policy for `"+targetURL+"`.") } defer fileReader.Close() const maxJSONSize = 120 * 1024 // 120KiB configBuf := make([]byte, maxJSONSize+1) n, e := io.ReadFull(fileReader, configBuf) if e == nil { return probe.NewError(bytes.ErrTooLarge).Trace(targetURL) } if e != io.ErrUnexpectedEOF { return probe.NewError(e).Trace(targetURL) } configBytes := configBuf[:n] if err = clnt.SetAccess(string(configBytes), true); err != nil { return err.Trace(targetURL, string(targetPERMS)) } return nil }
go
func doSetAccessJSON(targetURL string, targetPERMS accessPerms) *probe.Error { clnt, err := newClient(targetURL) if err != nil { return err.Trace(targetURL) } fileReader, e := os.Open(string(targetPERMS)) if e != nil { fatalIf(probe.NewError(e).Trace(), "Unable to set policy for `"+targetURL+"`.") } defer fileReader.Close() const maxJSONSize = 120 * 1024 // 120KiB configBuf := make([]byte, maxJSONSize+1) n, e := io.ReadFull(fileReader, configBuf) if e == nil { return probe.NewError(bytes.ErrTooLarge).Trace(targetURL) } if e != io.ErrUnexpectedEOF { return probe.NewError(e).Trace(targetURL) } configBytes := configBuf[:n] if err = clnt.SetAccess(string(configBytes), true); err != nil { return err.Trace(targetURL, string(targetPERMS)) } return nil }
[ "func", "doSetAccessJSON", "(", "targetURL", "string", ",", "targetPERMS", "accessPerms", ")", "*", "probe", ".", "Error", "{", "clnt", ",", "err", ":=", "newClient", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n", "fileReader", ",", "e", ":=", "os", ".", "Open", "(", "string", "(", "targetPERMS", ")", ")", "\n", "if", "e", "!=", "nil", "{", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "defer", "fileReader", ".", "Close", "(", ")", "\n\n", "const", "maxJSONSize", "=", "120", "*", "1024", "// 120KiB", "\n", "configBuf", ":=", "make", "(", "[", "]", "byte", ",", "maxJSONSize", "+", "1", ")", "\n\n", "n", ",", "e", ":=", "io", ".", "ReadFull", "(", "fileReader", ",", "configBuf", ")", "\n", "if", "e", "==", "nil", "{", "return", "probe", ".", "NewError", "(", "bytes", ".", "ErrTooLarge", ")", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n", "if", "e", "!=", "io", ".", "ErrUnexpectedEOF", "{", "return", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n\n", "configBytes", ":=", "configBuf", "[", ":", "n", "]", "\n", "if", "err", "=", "clnt", ".", "SetAccess", "(", "string", "(", "configBytes", ")", ",", "true", ")", ";", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "targetURL", ",", "string", "(", "targetPERMS", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// doSetAccessJSON do set access JSON.
[ "doSetAccessJSON", "do", "set", "access", "JSON", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L240-L267
train
minio/mc
cmd/policy-main.go
doGetAccess
func doGetAccess(targetURL string) (perms accessPerms, policyStr string, err *probe.Error) { clnt, err := newClient(targetURL) if err != nil { return "", "", err.Trace(targetURL) } perm, policyJSON, err := clnt.GetAccess() if err != nil { return "", "", err.Trace(targetURL) } return stringToAccessPerm(perm), policyJSON, nil }
go
func doGetAccess(targetURL string) (perms accessPerms, policyStr string, err *probe.Error) { clnt, err := newClient(targetURL) if err != nil { return "", "", err.Trace(targetURL) } perm, policyJSON, err := clnt.GetAccess() if err != nil { return "", "", err.Trace(targetURL) } return stringToAccessPerm(perm), policyJSON, nil }
[ "func", "doGetAccess", "(", "targetURL", "string", ")", "(", "perms", "accessPerms", ",", "policyStr", "string", ",", "err", "*", "probe", ".", "Error", ")", "{", "clnt", ",", "err", ":=", "newClient", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "err", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n", "perm", ",", "policyJSON", ",", "err", ":=", "clnt", ".", "GetAccess", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "err", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n", "return", "stringToAccessPerm", "(", "perm", ")", ",", "policyJSON", ",", "nil", "\n", "}" ]
// doGetAccess do get access.
[ "doGetAccess", "do", "get", "access", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L288-L298
train
minio/mc
cmd/policy-main.go
doGetAccessRules
func doGetAccessRules(targetURL string) (r map[string]string, err *probe.Error) { clnt, err := newClient(targetURL) if err != nil { return map[string]string{}, err.Trace(targetURL) } return clnt.GetAccessRules() }
go
func doGetAccessRules(targetURL string) (r map[string]string, err *probe.Error) { clnt, err := newClient(targetURL) if err != nil { return map[string]string{}, err.Trace(targetURL) } return clnt.GetAccessRules() }
[ "func", "doGetAccessRules", "(", "targetURL", "string", ")", "(", "r", "map", "[", "string", "]", "string", ",", "err", "*", "probe", ".", "Error", ")", "{", "clnt", ",", "err", ":=", "newClient", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "map", "[", "string", "]", "string", "{", "}", ",", "err", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n", "return", "clnt", ".", "GetAccessRules", "(", ")", "\n", "}" ]
// doGetAccessRules do get access rules.
[ "doGetAccessRules", "do", "get", "access", "rules", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L301-L307
train
minio/mc
cmd/policy-main.go
runPolicyListCmd
func runPolicyListCmd(args cli.Args) { targetURL := args.First() policies, err := doGetAccessRules(targetURL) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to list policies of a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to list policies of target `"+targetURL+"`.") } } for k, v := range policies { printMsg(policyRules{Resource: k, Allow: v}) } }
go
func runPolicyListCmd(args cli.Args) { targetURL := args.First() policies, err := doGetAccessRules(targetURL) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to list policies of a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to list policies of target `"+targetURL+"`.") } } for k, v := range policies { printMsg(policyRules{Resource: k, Allow: v}) } }
[ "func", "runPolicyListCmd", "(", "args", "cli", ".", "Args", ")", "{", "targetURL", ":=", "args", ".", "First", "(", ")", "\n", "policies", ",", "err", ":=", "doGetAccessRules", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "ToGoError", "(", ")", ".", "(", "type", ")", "{", "case", "APINotImplemented", ":", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "default", ":", "fatalIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "policies", "{", "printMsg", "(", "policyRules", "{", "Resource", ":", "k", ",", "Allow", ":", "v", "}", ")", "\n", "}", "\n", "}" ]
// Run policy list command
[ "Run", "policy", "list", "command" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L310-L324
train
minio/mc
cmd/policy-main.go
runPolicyLinksCmd
func runPolicyLinksCmd(args cli.Args, recursive bool) { // Get alias/bucket/prefix argument targetURL := args.First() // Fetch all policies associated to the passed url policies, err := doGetAccessRules(targetURL) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to list policies of a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to list policies of target `"+targetURL+"`.") } } // Extract alias from the passed argument, we'll need it to // construct new pathes to list public objects alias, path := url2Alias(targetURL) isRecursive := recursive isIncomplete := false // Iterate over policy rules to fetch public urls, then search // for objects under those urls for k, v := range policies { // Trim the asterisk in policy rules policyPath := strings.TrimSuffix(k, "*") // Check if current policy prefix is related to the url passed by the user if !strings.HasPrefix(policyPath, path) { continue } // Check if the found policy has read permission perm := stringToAccessPerm(v) if perm != accessDownload && perm != accessPublic { continue } // Construct the new path to search for public objects newURL := alias + "/" + policyPath clnt, err := newClient(newURL) fatalIf(err.Trace(newURL), "Unable to initialize target `"+targetURL+"`.") // Search for public objects for content := range clnt.List(isRecursive, isIncomplete, DirFirst) { if content.Err != nil { errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") continue } if content.Type.IsDir() && isRecursive { continue } // Encode public URL u, e := url.Parse(content.URL.String()) errorIf(probe.NewError(e), "Unable to parse url `"+content.URL.String()+"`.") publicURL := u.String() // Construct the message to be displayed to the user msg := policyLinksMessage{ Status: "success", URL: publicURL, } // Print the found object printMsg(msg) } } }
go
func runPolicyLinksCmd(args cli.Args, recursive bool) { // Get alias/bucket/prefix argument targetURL := args.First() // Fetch all policies associated to the passed url policies, err := doGetAccessRules(targetURL) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to list policies of a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to list policies of target `"+targetURL+"`.") } } // Extract alias from the passed argument, we'll need it to // construct new pathes to list public objects alias, path := url2Alias(targetURL) isRecursive := recursive isIncomplete := false // Iterate over policy rules to fetch public urls, then search // for objects under those urls for k, v := range policies { // Trim the asterisk in policy rules policyPath := strings.TrimSuffix(k, "*") // Check if current policy prefix is related to the url passed by the user if !strings.HasPrefix(policyPath, path) { continue } // Check if the found policy has read permission perm := stringToAccessPerm(v) if perm != accessDownload && perm != accessPublic { continue } // Construct the new path to search for public objects newURL := alias + "/" + policyPath clnt, err := newClient(newURL) fatalIf(err.Trace(newURL), "Unable to initialize target `"+targetURL+"`.") // Search for public objects for content := range clnt.List(isRecursive, isIncomplete, DirFirst) { if content.Err != nil { errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") continue } if content.Type.IsDir() && isRecursive { continue } // Encode public URL u, e := url.Parse(content.URL.String()) errorIf(probe.NewError(e), "Unable to parse url `"+content.URL.String()+"`.") publicURL := u.String() // Construct the message to be displayed to the user msg := policyLinksMessage{ Status: "success", URL: publicURL, } // Print the found object printMsg(msg) } } }
[ "func", "runPolicyLinksCmd", "(", "args", "cli", ".", "Args", ",", "recursive", "bool", ")", "{", "// Get alias/bucket/prefix argument", "targetURL", ":=", "args", ".", "First", "(", ")", "\n\n", "// Fetch all policies associated to the passed url", "policies", ",", "err", ":=", "doGetAccessRules", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "ToGoError", "(", ")", ".", "(", "type", ")", "{", "case", "APINotImplemented", ":", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "default", ":", "fatalIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// Extract alias from the passed argument, we'll need it to", "// construct new pathes to list public objects", "alias", ",", "path", ":=", "url2Alias", "(", "targetURL", ")", "\n\n", "isRecursive", ":=", "recursive", "\n", "isIncomplete", ":=", "false", "\n\n", "// Iterate over policy rules to fetch public urls, then search", "// for objects under those urls", "for", "k", ",", "v", ":=", "range", "policies", "{", "// Trim the asterisk in policy rules", "policyPath", ":=", "strings", ".", "TrimSuffix", "(", "k", ",", "\"", "\"", ")", "\n", "// Check if current policy prefix is related to the url passed by the user", "if", "!", "strings", ".", "HasPrefix", "(", "policyPath", ",", "path", ")", "{", "continue", "\n", "}", "\n", "// Check if the found policy has read permission", "perm", ":=", "stringToAccessPerm", "(", "v", ")", "\n", "if", "perm", "!=", "accessDownload", "&&", "perm", "!=", "accessPublic", "{", "continue", "\n", "}", "\n", "// Construct the new path to search for public objects", "newURL", ":=", "alias", "+", "\"", "\"", "+", "policyPath", "\n", "clnt", ",", "err", ":=", "newClient", "(", "newURL", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "newURL", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "// Search for public objects", "for", "content", ":=", "range", "clnt", ".", "List", "(", "isRecursive", ",", "isIncomplete", ",", "DirFirst", ")", "{", "if", "content", ".", "Err", "!=", "nil", "{", "errorIf", "(", "content", ".", "Err", ".", "Trace", "(", "clnt", ".", "GetURL", "(", ")", ".", "String", "(", ")", ")", ",", "\"", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "if", "content", ".", "Type", ".", "IsDir", "(", ")", "&&", "isRecursive", "{", "continue", "\n", "}", "\n\n", "// Encode public URL", "u", ",", "e", ":=", "url", ".", "Parse", "(", "content", ".", "URL", ".", "String", "(", ")", ")", "\n", "errorIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", "+", "content", ".", "URL", ".", "String", "(", ")", "+", "\"", "\"", ")", "\n", "publicURL", ":=", "u", ".", "String", "(", ")", "\n\n", "// Construct the message to be displayed to the user", "msg", ":=", "policyLinksMessage", "{", "Status", ":", "\"", "\"", ",", "URL", ":", "publicURL", ",", "}", "\n", "// Print the found object", "printMsg", "(", "msg", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Run policy links command
[ "Run", "policy", "links", "command" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L327-L392
train
minio/mc
cmd/policy-main.go
runPolicyCmd
func runPolicyCmd(args cli.Args) { var operation, policyStr string var probeErr *probe.Error perms := accessPerms(args.Get(0)) targetURL := args.Get(1) if perms.isValidAccessPERM() { probeErr = doSetAccess(targetURL, perms) operation = "set" } else if perms.isValidAccessFile() { probeErr = doSetAccessJSON(targetURL, perms) operation = "setJSON" } else { targetURL = args.First() perms, policyStr, probeErr = doGetAccess(targetURL) operation = "get" } // Upon error exit. if probeErr != nil { switch probeErr.ToGoError().(type) { case APINotImplemented: fatalIf(probeErr.Trace(), "Unable to "+operation+" policy of a non S3 url `"+targetURL+"`.") default: fatalIf(probeErr.Trace(targetURL, string(perms)), "Unable to "+operation+" policy `"+string(perms)+"` for `"+targetURL+"`.") } } policyJSON := map[string]interface{}{} if policyStr != "" { e := json.Unmarshal([]byte(policyStr), &policyJSON) fatalIf(probe.NewError(e), "Cannot unmarshal custom policy file.") } printMsg(policyMessage{ Status: "success", Operation: operation, Bucket: targetURL, Perms: perms, Policy: policyJSON, }) }
go
func runPolicyCmd(args cli.Args) { var operation, policyStr string var probeErr *probe.Error perms := accessPerms(args.Get(0)) targetURL := args.Get(1) if perms.isValidAccessPERM() { probeErr = doSetAccess(targetURL, perms) operation = "set" } else if perms.isValidAccessFile() { probeErr = doSetAccessJSON(targetURL, perms) operation = "setJSON" } else { targetURL = args.First() perms, policyStr, probeErr = doGetAccess(targetURL) operation = "get" } // Upon error exit. if probeErr != nil { switch probeErr.ToGoError().(type) { case APINotImplemented: fatalIf(probeErr.Trace(), "Unable to "+operation+" policy of a non S3 url `"+targetURL+"`.") default: fatalIf(probeErr.Trace(targetURL, string(perms)), "Unable to "+operation+" policy `"+string(perms)+"` for `"+targetURL+"`.") } } policyJSON := map[string]interface{}{} if policyStr != "" { e := json.Unmarshal([]byte(policyStr), &policyJSON) fatalIf(probe.NewError(e), "Cannot unmarshal custom policy file.") } printMsg(policyMessage{ Status: "success", Operation: operation, Bucket: targetURL, Perms: perms, Policy: policyJSON, }) }
[ "func", "runPolicyCmd", "(", "args", "cli", ".", "Args", ")", "{", "var", "operation", ",", "policyStr", "string", "\n", "var", "probeErr", "*", "probe", ".", "Error", "\n", "perms", ":=", "accessPerms", "(", "args", ".", "Get", "(", "0", ")", ")", "\n", "targetURL", ":=", "args", ".", "Get", "(", "1", ")", "\n", "if", "perms", ".", "isValidAccessPERM", "(", ")", "{", "probeErr", "=", "doSetAccess", "(", "targetURL", ",", "perms", ")", "\n", "operation", "=", "\"", "\"", "\n", "}", "else", "if", "perms", ".", "isValidAccessFile", "(", ")", "{", "probeErr", "=", "doSetAccessJSON", "(", "targetURL", ",", "perms", ")", "\n", "operation", "=", "\"", "\"", "\n", "}", "else", "{", "targetURL", "=", "args", ".", "First", "(", ")", "\n", "perms", ",", "policyStr", ",", "probeErr", "=", "doGetAccess", "(", "targetURL", ")", "\n", "operation", "=", "\"", "\"", "\n", "}", "\n", "// Upon error exit.", "if", "probeErr", "!=", "nil", "{", "switch", "probeErr", ".", "ToGoError", "(", ")", ".", "(", "type", ")", "{", "case", "APINotImplemented", ":", "fatalIf", "(", "probeErr", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "operation", "+", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "default", ":", "fatalIf", "(", "probeErr", ".", "Trace", "(", "targetURL", ",", "string", "(", "perms", ")", ")", ",", "\"", "\"", "+", "operation", "+", "\"", "\"", "+", "string", "(", "perms", ")", "+", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "policyJSON", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "policyStr", "!=", "\"", "\"", "{", "e", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "policyStr", ")", ",", "&", "policyJSON", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "printMsg", "(", "policyMessage", "{", "Status", ":", "\"", "\"", ",", "Operation", ":", "operation", ",", "Bucket", ":", "targetURL", ",", "Perms", ":", "perms", ",", "Policy", ":", "policyJSON", ",", "}", ")", "\n", "}" ]
// Run policy cmd to fetch set permission
[ "Run", "policy", "cmd", "to", "fetch", "set", "permission" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L395-L434
train
minio/mc
cmd/session-list.go
listSessions
func listSessions() *probe.Error { var bySessions []*sessionV8 for _, sid := range getSessionIDs() { session, err := loadSessionV8(sid) if err != nil { continue // Skip 'broken' session during listing } session.Close() // Session close right here. bySessions = append(bySessions, session) } // sort sessions based on time. sort.Sort(bySessionWhen(bySessions)) for _, session := range bySessions { printMsg(session) } return nil }
go
func listSessions() *probe.Error { var bySessions []*sessionV8 for _, sid := range getSessionIDs() { session, err := loadSessionV8(sid) if err != nil { continue // Skip 'broken' session during listing } session.Close() // Session close right here. bySessions = append(bySessions, session) } // sort sessions based on time. sort.Sort(bySessionWhen(bySessions)) for _, session := range bySessions { printMsg(session) } return nil }
[ "func", "listSessions", "(", ")", "*", "probe", ".", "Error", "{", "var", "bySessions", "[", "]", "*", "sessionV8", "\n", "for", "_", ",", "sid", ":=", "range", "getSessionIDs", "(", ")", "{", "session", ",", "err", ":=", "loadSessionV8", "(", "sid", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "// Skip 'broken' session during listing", "\n", "}", "\n", "session", ".", "Close", "(", ")", "// Session close right here.", "\n", "bySessions", "=", "append", "(", "bySessions", ",", "session", ")", "\n", "}", "\n", "// sort sessions based on time.", "sort", ".", "Sort", "(", "bySessionWhen", "(", "bySessions", ")", ")", "\n", "for", "_", ",", "session", ":=", "range", "bySessions", "{", "printMsg", "(", "session", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// listSessions list all current sessions.
[ "listSessions", "list", "all", "current", "sessions", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-list.go#L50-L66
train
minio/mc
pkg/console/console.go
consolePrintln
func consolePrintln(tag string, c *color.Color, a ...interface{}) { privateMutex.Lock() defer privateMutex.Unlock() switch tag { case "Debug": // if no arguments are given do not invoke debug printer. if len(a) == 0 { return } output := color.Output color.Output = stderrColoredOutput if isatty.IsTerminal(os.Stderr.Fd()) { c.Print(ProgramName() + ": <DEBUG> ") c.Println(a...) } else { fmt.Fprint(color.Output, ProgramName()+": <DEBUG> ") fmt.Fprintln(color.Output, a...) } color.Output = output case "Fatal": fallthrough case "Error": // if no arguments are given do not invoke fatal and error printer. if len(a) == 0 { return } output := color.Output color.Output = stderrColoredOutput if isatty.IsTerminal(os.Stderr.Fd()) { c.Print(ProgramName() + ": <ERROR> ") c.Println(a...) } else { fmt.Fprint(color.Output, ProgramName()+": <ERROR> ") fmt.Fprintln(color.Output, a...) } color.Output = output case "Info": // if no arguments are given do not invoke info printer. if len(a) == 0 { return } if isatty.IsTerminal(os.Stdout.Fd()) { c.Print(ProgramName() + ": ") c.Println(a...) } else { fmt.Fprint(color.Output, ProgramName()+": ") fmt.Fprintln(color.Output, a...) } default: if isatty.IsTerminal(os.Stdout.Fd()) { c.Println(a...) } else { fmt.Fprintln(color.Output, a...) } } }
go
func consolePrintln(tag string, c *color.Color, a ...interface{}) { privateMutex.Lock() defer privateMutex.Unlock() switch tag { case "Debug": // if no arguments are given do not invoke debug printer. if len(a) == 0 { return } output := color.Output color.Output = stderrColoredOutput if isatty.IsTerminal(os.Stderr.Fd()) { c.Print(ProgramName() + ": <DEBUG> ") c.Println(a...) } else { fmt.Fprint(color.Output, ProgramName()+": <DEBUG> ") fmt.Fprintln(color.Output, a...) } color.Output = output case "Fatal": fallthrough case "Error": // if no arguments are given do not invoke fatal and error printer. if len(a) == 0 { return } output := color.Output color.Output = stderrColoredOutput if isatty.IsTerminal(os.Stderr.Fd()) { c.Print(ProgramName() + ": <ERROR> ") c.Println(a...) } else { fmt.Fprint(color.Output, ProgramName()+": <ERROR> ") fmt.Fprintln(color.Output, a...) } color.Output = output case "Info": // if no arguments are given do not invoke info printer. if len(a) == 0 { return } if isatty.IsTerminal(os.Stdout.Fd()) { c.Print(ProgramName() + ": ") c.Println(a...) } else { fmt.Fprint(color.Output, ProgramName()+": ") fmt.Fprintln(color.Output, a...) } default: if isatty.IsTerminal(os.Stdout.Fd()) { c.Println(a...) } else { fmt.Fprintln(color.Output, a...) } } }
[ "func", "consolePrintln", "(", "tag", "string", ",", "c", "*", "color", ".", "Color", ",", "a", "...", "interface", "{", "}", ")", "{", "privateMutex", ".", "Lock", "(", ")", "\n", "defer", "privateMutex", ".", "Unlock", "(", ")", "\n\n", "switch", "tag", "{", "case", "\"", "\"", ":", "// if no arguments are given do not invoke debug printer.", "if", "len", "(", "a", ")", "==", "0", "{", "return", "\n", "}", "\n", "output", ":=", "color", ".", "Output", "\n", "color", ".", "Output", "=", "stderrColoredOutput", "\n", "if", "isatty", ".", "IsTerminal", "(", "os", ".", "Stderr", ".", "Fd", "(", ")", ")", "{", "c", ".", "Print", "(", "ProgramName", "(", ")", "+", "\"", "\"", ")", "\n", "c", ".", "Println", "(", "a", "...", ")", "\n", "}", "else", "{", "fmt", ".", "Fprint", "(", "color", ".", "Output", ",", "ProgramName", "(", ")", "+", "\"", "\"", ")", "\n", "fmt", ".", "Fprintln", "(", "color", ".", "Output", ",", "a", "...", ")", "\n", "}", "\n", "color", ".", "Output", "=", "output", "\n", "case", "\"", "\"", ":", "fallthrough", "\n", "case", "\"", "\"", ":", "// if no arguments are given do not invoke fatal and error printer.", "if", "len", "(", "a", ")", "==", "0", "{", "return", "\n", "}", "\n", "output", ":=", "color", ".", "Output", "\n", "color", ".", "Output", "=", "stderrColoredOutput", "\n", "if", "isatty", ".", "IsTerminal", "(", "os", ".", "Stderr", ".", "Fd", "(", ")", ")", "{", "c", ".", "Print", "(", "ProgramName", "(", ")", "+", "\"", "\"", ")", "\n", "c", ".", "Println", "(", "a", "...", ")", "\n", "}", "else", "{", "fmt", ".", "Fprint", "(", "color", ".", "Output", ",", "ProgramName", "(", ")", "+", "\"", "\"", ")", "\n", "fmt", ".", "Fprintln", "(", "color", ".", "Output", ",", "a", "...", ")", "\n", "}", "\n", "color", ".", "Output", "=", "output", "\n", "case", "\"", "\"", ":", "// if no arguments are given do not invoke info printer.", "if", "len", "(", "a", ")", "==", "0", "{", "return", "\n", "}", "\n", "if", "isatty", ".", "IsTerminal", "(", "os", ".", "Stdout", ".", "Fd", "(", ")", ")", "{", "c", ".", "Print", "(", "ProgramName", "(", ")", "+", "\"", "\"", ")", "\n", "c", ".", "Println", "(", "a", "...", ")", "\n", "}", "else", "{", "fmt", ".", "Fprint", "(", "color", ".", "Output", ",", "ProgramName", "(", ")", "+", "\"", "\"", ")", "\n", "fmt", ".", "Fprintln", "(", "color", ".", "Output", ",", "a", "...", ")", "\n", "}", "\n", "default", ":", "if", "isatty", ".", "IsTerminal", "(", "os", ".", "Stdout", ".", "Fd", "(", ")", ")", "{", "c", ".", "Println", "(", "a", "...", ")", "\n", "}", "else", "{", "fmt", ".", "Fprintln", "(", "color", ".", "Output", ",", "a", "...", ")", "\n", "}", "\n", "}", "\n", "}" ]
// consolePrintln - same as print with a new line.
[ "consolePrintln", "-", "same", "as", "print", "with", "a", "new", "line", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/console/console.go#L284-L340
train
minio/mc
pkg/console/console.go
DisplayTable
func (t *Table) DisplayTable(rows [][]string) error { numRows := len(rows) numCols := len(rows[0]) if numRows != len(t.RowColors) { return fmt.Errorf("row count and row-colors mismatch") } // Compute max. column widths maxColWidths := make([]int, numCols) for _, row := range rows { if len(row) != len(t.AlignRight) { return fmt.Errorf("col count and align-right mismatch") } for i, v := range row { if len([]rune(v)) > maxColWidths[i] { maxColWidths[i] = len([]rune(v)) } } } // Compute per-cell text with padding and alignment applied. paddedText := make([][]string, numRows) for r, row := range rows { paddedText[r] = make([]string, numCols) for c, cell := range row { if t.AlignRight[c] { fmtStr := fmt.Sprintf("%%%ds", maxColWidths[c]) paddedText[r][c] = fmt.Sprintf(fmtStr, cell) } else { extraWidth := maxColWidths[c] - len([]rune(cell)) fmtStr := fmt.Sprintf("%%s%%%ds", extraWidth) paddedText[r][c] = fmt.Sprintf(fmtStr, cell, "") } } } // Draw table top border segments := make([]string, numCols) for i, c := range maxColWidths { segments[i] = strings.Repeat("─", c+2) } indentText := strings.Repeat(" ", t.TableIndentWidth) border := fmt.Sprintf("%s┌%s┐", indentText, strings.Join(segments, "┬")) fmt.Println(border) // Print the table with colors for r, row := range paddedText { fmt.Print(indentText + "│ ") for c, text := range row { t.RowColors[r].Print(text) if c != numCols-1 { fmt.Print(" │ ") } } fmt.Println(" │") } // Draw table bottom border border = fmt.Sprintf("%s└%s┘", indentText, strings.Join(segments, "┴")) fmt.Println(border) return nil }
go
func (t *Table) DisplayTable(rows [][]string) error { numRows := len(rows) numCols := len(rows[0]) if numRows != len(t.RowColors) { return fmt.Errorf("row count and row-colors mismatch") } // Compute max. column widths maxColWidths := make([]int, numCols) for _, row := range rows { if len(row) != len(t.AlignRight) { return fmt.Errorf("col count and align-right mismatch") } for i, v := range row { if len([]rune(v)) > maxColWidths[i] { maxColWidths[i] = len([]rune(v)) } } } // Compute per-cell text with padding and alignment applied. paddedText := make([][]string, numRows) for r, row := range rows { paddedText[r] = make([]string, numCols) for c, cell := range row { if t.AlignRight[c] { fmtStr := fmt.Sprintf("%%%ds", maxColWidths[c]) paddedText[r][c] = fmt.Sprintf(fmtStr, cell) } else { extraWidth := maxColWidths[c] - len([]rune(cell)) fmtStr := fmt.Sprintf("%%s%%%ds", extraWidth) paddedText[r][c] = fmt.Sprintf(fmtStr, cell, "") } } } // Draw table top border segments := make([]string, numCols) for i, c := range maxColWidths { segments[i] = strings.Repeat("─", c+2) } indentText := strings.Repeat(" ", t.TableIndentWidth) border := fmt.Sprintf("%s┌%s┐", indentText, strings.Join(segments, "┬")) fmt.Println(border) // Print the table with colors for r, row := range paddedText { fmt.Print(indentText + "│ ") for c, text := range row { t.RowColors[r].Print(text) if c != numCols-1 { fmt.Print(" │ ") } } fmt.Println(" │") } // Draw table bottom border border = fmt.Sprintf("%s└%s┘", indentText, strings.Join(segments, "┴")) fmt.Println(border) return nil }
[ "func", "(", "t", "*", "Table", ")", "DisplayTable", "(", "rows", "[", "]", "[", "]", "string", ")", "error", "{", "numRows", ":=", "len", "(", "rows", ")", "\n", "numCols", ":=", "len", "(", "rows", "[", "0", "]", ")", "\n", "if", "numRows", "!=", "len", "(", "t", ".", "RowColors", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Compute max. column widths", "maxColWidths", ":=", "make", "(", "[", "]", "int", ",", "numCols", ")", "\n", "for", "_", ",", "row", ":=", "range", "rows", "{", "if", "len", "(", "row", ")", "!=", "len", "(", "t", ".", "AlignRight", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ",", "v", ":=", "range", "row", "{", "if", "len", "(", "[", "]", "rune", "(", "v", ")", ")", ">", "maxColWidths", "[", "i", "]", "{", "maxColWidths", "[", "i", "]", "=", "len", "(", "[", "]", "rune", "(", "v", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Compute per-cell text with padding and alignment applied.", "paddedText", ":=", "make", "(", "[", "]", "[", "]", "string", ",", "numRows", ")", "\n", "for", "r", ",", "row", ":=", "range", "rows", "{", "paddedText", "[", "r", "]", "=", "make", "(", "[", "]", "string", ",", "numCols", ")", "\n", "for", "c", ",", "cell", ":=", "range", "row", "{", "if", "t", ".", "AlignRight", "[", "c", "]", "{", "fmtStr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "maxColWidths", "[", "c", "]", ")", "\n", "paddedText", "[", "r", "]", "[", "c", "]", "=", "fmt", ".", "Sprintf", "(", "fmtStr", ",", "cell", ")", "\n", "}", "else", "{", "extraWidth", ":=", "maxColWidths", "[", "c", "]", "-", "len", "(", "[", "]", "rune", "(", "cell", ")", ")", "\n", "fmtStr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "extraWidth", ")", "\n", "paddedText", "[", "r", "]", "[", "c", "]", "=", "fmt", ".", "Sprintf", "(", "fmtStr", ",", "cell", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Draw table top border", "segments", ":=", "make", "(", "[", "]", "string", ",", "numCols", ")", "\n", "for", "i", ",", "c", ":=", "range", "maxColWidths", "{", "segments", "[", "i", "]", "=", "strings", ".", "Repeat", "(", "\"", " ", "c", "2", ")", "", "", "\n", "}", "\n", "indentText", ":=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "t", ".", "TableIndentWidth", ")", "\n", "border", ":=", "fmt", ".", "Sprintf", "(", "\"", "n", "d", "ntText, st", "r", "ngs.Joi", "n", "(seg", "m", "ents, \"┬", "\"", ")", "", "", "", "\n", "fmt", ".", "Println", "(", "border", ")", "\n\n", "// Print the table with colors", "for", "r", ",", "row", ":=", "range", "paddedText", "{", "fmt", ".", "Print", "(", "indentText", "+", "\"", "", "", "\n", "for", "c", ",", "text", ":=", "range", "row", "{", "t", ".", "RowColors", "[", "r", "]", ".", "Print", "(", "text", ")", "\n", "if", "c", "!=", "numCols", "-", "1", "{", "fmt", ".", "Print", "(", "\"", "", "", "\n", "}", "\n", "}", "\n", "fmt", ".", "Println", "(", "\"", "", "", "\n", "}", "\n\n", "// Draw table bottom border", "border", "=", "fmt", ".", "Sprintf", "(", "\"", "n", "d", "ntText, st", "r", "ngs.Joi", "n", "(seg", "m", "ents, \"┴", "\"", ")", "", "", "", "\n", "fmt", ".", "Println", "(", "border", ")", "\n\n", "return", "nil", "\n", "}" ]
// DisplayTable - prints the table
[ "DisplayTable", "-", "prints", "the", "table" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/console/console.go#L378-L440
train
minio/mc
cmd/event-remove.go
checkEventRemoveSyntax
func checkEventRemoveSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code } if len(ctx.Args()) == 1 && !ctx.Bool("force") { fatalIf(probe.NewError(errors.New("")), "--force flag needs to be passed to remove all bucket notifications.") } }
go
func checkEventRemoveSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code } if len(ctx.Args()) == 1 && !ctx.Bool("force") { fatalIf(probe.NewError(errors.New("")), "--force flag needs to be passed to remove all bucket notifications.") } }
[ "func", "checkEventRemoveSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "1", "&&", "!", "ctx", ".", "Bool", "(", "\"", "\"", ")", "{", "fatalIf", "(", "probe", ".", "NewError", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// checkEventRemoveSyntax - validate all the passed arguments
[ "checkEventRemoveSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/event-remove.go#L64-L71
train
minio/mc
cmd/event-remove.go
JSON
func (u eventRemoveMessage) JSON() string { u.Status = "success" eventRemoveMessageJSONBytes, e := json.MarshalIndent(u, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(eventRemoveMessageJSONBytes) }
go
func (u eventRemoveMessage) JSON() string { u.Status = "success" eventRemoveMessageJSONBytes, e := json.MarshalIndent(u, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(eventRemoveMessageJSONBytes) }
[ "func", "(", "u", "eventRemoveMessage", ")", "JSON", "(", ")", "string", "{", "u", ".", "Status", "=", "\"", "\"", "\n", "eventRemoveMessageJSONBytes", ",", "e", ":=", "json", ".", "MarshalIndent", "(", "u", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n", "return", "string", "(", "eventRemoveMessageJSONBytes", ")", "\n", "}" ]
// JSON jsonified remove message.
[ "JSON", "jsonified", "remove", "message", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/event-remove.go#L80-L85
train
minio/mc
cmd/accounting-reader.go
newAccounter
func newAccounter(total int64) *accounter { acct := &accounter{ Total: total, startTime: time.Now(), startValue: 0, refreshRate: time.Millisecond * 200, isFinished: make(chan struct{}), currentValue: -1, } go acct.writer() return acct }
go
func newAccounter(total int64) *accounter { acct := &accounter{ Total: total, startTime: time.Now(), startValue: 0, refreshRate: time.Millisecond * 200, isFinished: make(chan struct{}), currentValue: -1, } go acct.writer() return acct }
[ "func", "newAccounter", "(", "total", "int64", ")", "*", "accounter", "{", "acct", ":=", "&", "accounter", "{", "Total", ":", "total", ",", "startTime", ":", "time", ".", "Now", "(", ")", ",", "startValue", ":", "0", ",", "refreshRate", ":", "time", ".", "Millisecond", "*", "200", ",", "isFinished", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "currentValue", ":", "-", "1", ",", "}", "\n", "go", "acct", ".", "writer", "(", ")", "\n", "return", "acct", "\n", "}" ]
// Instantiate a new accounter.
[ "Instantiate", "a", "new", "accounter", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L44-L55
train
minio/mc
cmd/accounting-reader.go
write
func (a *accounter) write(current int64) float64 { fromStart := time.Since(a.startTime) currentFromStart := current - a.startValue if currentFromStart > 0 { speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second)) return speed } return 0.0 }
go
func (a *accounter) write(current int64) float64 { fromStart := time.Since(a.startTime) currentFromStart := current - a.startValue if currentFromStart > 0 { speed := float64(currentFromStart) / (float64(fromStart) / float64(time.Second)) return speed } return 0.0 }
[ "func", "(", "a", "*", "accounter", ")", "write", "(", "current", "int64", ")", "float64", "{", "fromStart", ":=", "time", ".", "Since", "(", "a", ".", "startTime", ")", "\n", "currentFromStart", ":=", "current", "-", "a", ".", "startValue", "\n", "if", "currentFromStart", ">", "0", "{", "speed", ":=", "float64", "(", "currentFromStart", ")", "/", "(", "float64", "(", "fromStart", ")", "/", "float64", "(", "time", ".", "Second", ")", ")", "\n", "return", "speed", "\n", "}", "\n", "return", "0.0", "\n", "}" ]
// write calculate the final speed.
[ "write", "calculate", "the", "final", "speed", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L58-L66
train
minio/mc
cmd/accounting-reader.go
writer
func (a *accounter) writer() { a.Update() for { select { case <-a.isFinished: return case <-time.After(a.refreshRate): a.Update() } } }
go
func (a *accounter) writer() { a.Update() for { select { case <-a.isFinished: return case <-time.After(a.refreshRate): a.Update() } } }
[ "func", "(", "a", "*", "accounter", ")", "writer", "(", ")", "{", "a", ".", "Update", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "a", ".", "isFinished", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "a", ".", "refreshRate", ")", ":", "a", ".", "Update", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// writer update new accounting data for a specified refreshRate.
[ "writer", "update", "new", "accounting", "data", "for", "a", "specified", "refreshRate", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L69-L79
train
minio/mc
cmd/accounting-reader.go
Stat
func (a *accounter) Stat() accountStat { var acntStat accountStat a.finishOnce.Do(func() { close(a.isFinished) acntStat.Total = a.Total acntStat.Transferred = atomic.LoadInt64(&a.current) acntStat.Speed = a.write(atomic.LoadInt64(&a.current)) }) return acntStat }
go
func (a *accounter) Stat() accountStat { var acntStat accountStat a.finishOnce.Do(func() { close(a.isFinished) acntStat.Total = a.Total acntStat.Transferred = atomic.LoadInt64(&a.current) acntStat.Speed = a.write(atomic.LoadInt64(&a.current)) }) return acntStat }
[ "func", "(", "a", "*", "accounter", ")", "Stat", "(", ")", "accountStat", "{", "var", "acntStat", "accountStat", "\n", "a", ".", "finishOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "a", ".", "isFinished", ")", "\n", "acntStat", ".", "Total", "=", "a", ".", "Total", "\n", "acntStat", ".", "Transferred", "=", "atomic", ".", "LoadInt64", "(", "&", "a", ".", "current", ")", "\n", "acntStat", ".", "Speed", "=", "a", ".", "write", "(", "atomic", ".", "LoadInt64", "(", "&", "a", ".", "current", ")", ")", "\n", "}", ")", "\n", "return", "acntStat", "\n", "}" ]
// Stat provides current stats captured.
[ "Stat", "provides", "current", "stats", "captured", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L110-L119
train
minio/mc
cmd/accounting-reader.go
Update
func (a *accounter) Update() { c := atomic.LoadInt64(&a.current) if c != a.currentValue { a.write(c) a.currentValue = c } }
go
func (a *accounter) Update() { c := atomic.LoadInt64(&a.current) if c != a.currentValue { a.write(c) a.currentValue = c } }
[ "func", "(", "a", "*", "accounter", ")", "Update", "(", ")", "{", "c", ":=", "atomic", ".", "LoadInt64", "(", "&", "a", ".", "current", ")", "\n", "if", "c", "!=", "a", ".", "currentValue", "{", "a", ".", "write", "(", "c", ")", "\n", "a", ".", "currentValue", "=", "c", "\n", "}", "\n", "}" ]
// Update update with new values loaded atomically.
[ "Update", "update", "with", "new", "values", "loaded", "atomically", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L122-L128
train
minio/mc
cmd/accounting-reader.go
Set
func (a *accounter) Set(n int64) *accounter { atomic.StoreInt64(&a.current, n) return a }
go
func (a *accounter) Set(n int64) *accounter { atomic.StoreInt64(&a.current, n) return a }
[ "func", "(", "a", "*", "accounter", ")", "Set", "(", "n", "int64", ")", "*", "accounter", "{", "atomic", ".", "StoreInt64", "(", "&", "a", ".", "current", ",", "n", ")", "\n", "return", "a", "\n", "}" ]
// Set sets the current value atomically.
[ "Set", "sets", "the", "current", "value", "atomically", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L131-L134
train
minio/mc
cmd/accounting-reader.go
Add
func (a *accounter) Add(n int64) int64 { return atomic.AddInt64(&a.current, n) }
go
func (a *accounter) Add(n int64) int64 { return atomic.AddInt64(&a.current, n) }
[ "func", "(", "a", "*", "accounter", ")", "Add", "(", "n", "int64", ")", "int64", "{", "return", "atomic", ".", "AddInt64", "(", "&", "a", ".", "current", ",", "n", ")", "\n", "}" ]
// Add add to current value atomically.
[ "Add", "add", "to", "current", "value", "atomically", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L142-L144
train
minio/mc
cmd/accounting-reader.go
Read
func (a *accounter) Read(p []byte) (n int, err error) { n = len(p) a.Add(int64(n)) return }
go
func (a *accounter) Read(p []byte) (n int, err error) { n = len(p) a.Add(int64(n)) return }
[ "func", "(", "a", "*", "accounter", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "n", "=", "len", "(", "p", ")", "\n", "a", ".", "Add", "(", "int64", "(", "n", ")", ")", "\n", "return", "\n", "}" ]
// Read implements Reader which internally updates current value.
[ "Read", "implements", "Reader", "which", "internally", "updates", "current", "value", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/accounting-reader.go#L147-L151
train
minio/mc
cmd/mirror-main.go
String
func (m mirrorMessage) String() string { return console.Colorize("Mirror", fmt.Sprintf("`%s` -> `%s`", m.Source, m.Target)) }
go
func (m mirrorMessage) String() string { return console.Colorize("Mirror", fmt.Sprintf("`%s` -> `%s`", m.Source, m.Target)) }
[ "func", "(", "m", "mirrorMessage", ")", "String", "(", ")", "string", "{", "return", "console", ".", "Colorize", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "Source", ",", "m", ".", "Target", ")", ")", "\n", "}" ]
// String colorized mirror message
[ "String", "colorized", "mirror", "message" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L202-L204
train
minio/mc
cmd/mirror-main.go
JSON
func (m mirrorMessage) JSON() string { m.Status = "success" mirrorMessageBytes, e := json.MarshalIndent(m, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(mirrorMessageBytes) }
go
func (m mirrorMessage) JSON() string { m.Status = "success" mirrorMessageBytes, e := json.MarshalIndent(m, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(mirrorMessageBytes) }
[ "func", "(", "m", "mirrorMessage", ")", "JSON", "(", ")", "string", "{", "m", ".", "Status", "=", "\"", "\"", "\n", "mirrorMessageBytes", ",", "e", ":=", "json", ".", "MarshalIndent", "(", "m", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n\n", "return", "string", "(", "mirrorMessageBytes", ")", "\n", "}" ]
// JSON jsonified mirror message
[ "JSON", "jsonified", "mirror", "message" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L207-L213
train
minio/mc
cmd/mirror-main.go
doRemove
func (mj *mirrorJob) doRemove(sURLs URLs) URLs { if mj.isFake { return sURLs.WithError(nil) } // Construct proper path with alias. targetWithAlias := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path) clnt, pErr := newClient(targetWithAlias) if pErr != nil { return sURLs.WithError(pErr) } contentCh := make(chan *clientContent, 1) contentCh <- &clientContent{URL: *newClientURL(sURLs.TargetContent.URL.Path)} close(contentCh) isRemoveBucket := false errorCh := clnt.Remove(false, isRemoveBucket, contentCh) for pErr := range errorCh { if pErr != nil { switch pErr.ToGoError().(type) { case PathInsufficientPermission: // Ignore Permission error. continue } return sURLs.WithError(pErr) } } return sURLs.WithError(nil) }
go
func (mj *mirrorJob) doRemove(sURLs URLs) URLs { if mj.isFake { return sURLs.WithError(nil) } // Construct proper path with alias. targetWithAlias := filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path) clnt, pErr := newClient(targetWithAlias) if pErr != nil { return sURLs.WithError(pErr) } contentCh := make(chan *clientContent, 1) contentCh <- &clientContent{URL: *newClientURL(sURLs.TargetContent.URL.Path)} close(contentCh) isRemoveBucket := false errorCh := clnt.Remove(false, isRemoveBucket, contentCh) for pErr := range errorCh { if pErr != nil { switch pErr.ToGoError().(type) { case PathInsufficientPermission: // Ignore Permission error. continue } return sURLs.WithError(pErr) } } return sURLs.WithError(nil) }
[ "func", "(", "mj", "*", "mirrorJob", ")", "doRemove", "(", "sURLs", "URLs", ")", "URLs", "{", "if", "mj", ".", "isFake", "{", "return", "sURLs", ".", "WithError", "(", "nil", ")", "\n", "}", "\n\n", "// Construct proper path with alias.", "targetWithAlias", ":=", "filepath", ".", "Join", "(", "sURLs", ".", "TargetAlias", ",", "sURLs", ".", "TargetContent", ".", "URL", ".", "Path", ")", "\n", "clnt", ",", "pErr", ":=", "newClient", "(", "targetWithAlias", ")", "\n", "if", "pErr", "!=", "nil", "{", "return", "sURLs", ".", "WithError", "(", "pErr", ")", "\n", "}", "\n\n", "contentCh", ":=", "make", "(", "chan", "*", "clientContent", ",", "1", ")", "\n", "contentCh", "<-", "&", "clientContent", "{", "URL", ":", "*", "newClientURL", "(", "sURLs", ".", "TargetContent", ".", "URL", ".", "Path", ")", "}", "\n", "close", "(", "contentCh", ")", "\n", "isRemoveBucket", ":=", "false", "\n", "errorCh", ":=", "clnt", ".", "Remove", "(", "false", ",", "isRemoveBucket", ",", "contentCh", ")", "\n", "for", "pErr", ":=", "range", "errorCh", "{", "if", "pErr", "!=", "nil", "{", "switch", "pErr", ".", "ToGoError", "(", ")", ".", "(", "type", ")", "{", "case", "PathInsufficientPermission", ":", "// Ignore Permission error.", "continue", "\n", "}", "\n", "return", "sURLs", ".", "WithError", "(", "pErr", ")", "\n", "}", "\n", "}", "\n\n", "return", "sURLs", ".", "WithError", "(", "nil", ")", "\n", "}" ]
// doRemove - removes files on target.
[ "doRemove", "-", "removes", "files", "on", "target", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L216-L245
train
minio/mc
cmd/mirror-main.go
doMirror
func (mj *mirrorJob) doMirror(ctx context.Context, cancelMirror context.CancelFunc, sURLs URLs) URLs { if sURLs.Error != nil { // Erroneous sURLs passed. return sURLs.WithError(sURLs.Error.Trace()) } //s For a fake mirror make sure we update respective progress bars // and accounting readers under relevant conditions. if mj.isFake { mj.status.Add(sURLs.SourceContent.Size) return sURLs.WithError(nil) } sourceAlias := sURLs.SourceAlias sourceURL := sURLs.SourceContent.URL targetAlias := sURLs.TargetAlias targetURL := sURLs.TargetContent.URL length := sURLs.SourceContent.Size mj.status.SetCaption(sourceURL.String() + ": ") if mj.storageClass != "" { if sURLs.TargetContent.Metadata == nil { sURLs.TargetContent.Metadata = make(map[string]string) } sURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = mj.storageClass } sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path)) mj.status.PrintMsg(mirrorMessage{ Source: sourcePath, Target: targetPath, Size: length, TotalCount: sURLs.TotalCount, TotalSize: sURLs.TotalSize, }) return uploadSourceToTargetURL(ctx, sURLs, mj.status, mj.encKeyDB) }
go
func (mj *mirrorJob) doMirror(ctx context.Context, cancelMirror context.CancelFunc, sURLs URLs) URLs { if sURLs.Error != nil { // Erroneous sURLs passed. return sURLs.WithError(sURLs.Error.Trace()) } //s For a fake mirror make sure we update respective progress bars // and accounting readers under relevant conditions. if mj.isFake { mj.status.Add(sURLs.SourceContent.Size) return sURLs.WithError(nil) } sourceAlias := sURLs.SourceAlias sourceURL := sURLs.SourceContent.URL targetAlias := sURLs.TargetAlias targetURL := sURLs.TargetContent.URL length := sURLs.SourceContent.Size mj.status.SetCaption(sourceURL.String() + ": ") if mj.storageClass != "" { if sURLs.TargetContent.Metadata == nil { sURLs.TargetContent.Metadata = make(map[string]string) } sURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = mj.storageClass } sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path)) targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path)) mj.status.PrintMsg(mirrorMessage{ Source: sourcePath, Target: targetPath, Size: length, TotalCount: sURLs.TotalCount, TotalSize: sURLs.TotalSize, }) return uploadSourceToTargetURL(ctx, sURLs, mj.status, mj.encKeyDB) }
[ "func", "(", "mj", "*", "mirrorJob", ")", "doMirror", "(", "ctx", "context", ".", "Context", ",", "cancelMirror", "context", ".", "CancelFunc", ",", "sURLs", "URLs", ")", "URLs", "{", "if", "sURLs", ".", "Error", "!=", "nil", "{", "// Erroneous sURLs passed.", "return", "sURLs", ".", "WithError", "(", "sURLs", ".", "Error", ".", "Trace", "(", ")", ")", "\n", "}", "\n\n", "//s For a fake mirror make sure we update respective progress bars", "// and accounting readers under relevant conditions.", "if", "mj", ".", "isFake", "{", "mj", ".", "status", ".", "Add", "(", "sURLs", ".", "SourceContent", ".", "Size", ")", "\n", "return", "sURLs", ".", "WithError", "(", "nil", ")", "\n", "}", "\n\n", "sourceAlias", ":=", "sURLs", ".", "SourceAlias", "\n", "sourceURL", ":=", "sURLs", ".", "SourceContent", ".", "URL", "\n", "targetAlias", ":=", "sURLs", ".", "TargetAlias", "\n", "targetURL", ":=", "sURLs", ".", "TargetContent", ".", "URL", "\n", "length", ":=", "sURLs", ".", "SourceContent", ".", "Size", "\n\n", "mj", ".", "status", ".", "SetCaption", "(", "sourceURL", ".", "String", "(", ")", "+", "\"", "\"", ")", "\n\n", "if", "mj", ".", "storageClass", "!=", "\"", "\"", "{", "if", "sURLs", ".", "TargetContent", ".", "Metadata", "==", "nil", "{", "sURLs", ".", "TargetContent", ".", "Metadata", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "sURLs", ".", "TargetContent", ".", "Metadata", "[", "\"", "\"", "]", "=", "mj", ".", "storageClass", "\n", "}", "\n\n", "sourcePath", ":=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Join", "(", "sourceAlias", ",", "sourceURL", ".", "Path", ")", ")", "\n", "targetPath", ":=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Join", "(", "targetAlias", ",", "targetURL", ".", "Path", ")", ")", "\n", "mj", ".", "status", ".", "PrintMsg", "(", "mirrorMessage", "{", "Source", ":", "sourcePath", ",", "Target", ":", "targetPath", ",", "Size", ":", "length", ",", "TotalCount", ":", "sURLs", ".", "TotalCount", ",", "TotalSize", ":", "sURLs", ".", "TotalSize", ",", "}", ")", "\n", "return", "uploadSourceToTargetURL", "(", "ctx", ",", "sURLs", ",", "mj", ".", "status", ",", "mj", ".", "encKeyDB", ")", "\n", "}" ]
// doMirror - Mirror an object to multiple destination. URLs status contains a copy of sURLs and error if any.
[ "doMirror", "-", "Mirror", "an", "object", "to", "multiple", "destination", ".", "URLs", "status", "contains", "a", "copy", "of", "sURLs", "and", "error", "if", "any", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L248-L286
train
minio/mc
cmd/mirror-main.go
monitorMirrorStatus
func (mj *mirrorJob) monitorMirrorStatus() (errDuringMirror bool) { // now we want to start the progress bar mj.status.Start() defer mj.status.Finish() for sURLs := range mj.statusCh { if sURLs.Error != nil { switch { case sURLs.SourceContent != nil: if !isErrIgnored(sURLs.Error) { errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()), fmt.Sprintf("Failed to copy `%s`.", sURLs.SourceContent.URL.String())) errDuringMirror = true } case sURLs.TargetContent != nil: // When sURLs.SourceContent is nil, we know that we have an error related to removing errorIf(sURLs.Error.Trace(sURLs.TargetContent.URL.String()), fmt.Sprintf("Failed to remove `%s`.", sURLs.TargetContent.URL.String())) errDuringMirror = true default: errorIf(sURLs.Error.Trace(), "Failed to perform mirroring action.") errDuringMirror = true } } if sURLs.SourceContent != nil { } else if sURLs.TargetContent != nil { // Construct user facing message and path. targetPath := filepath.ToSlash(filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path)) size := sURLs.TargetContent.Size mj.status.PrintMsg(rmMessage{Key: targetPath, Size: size}) } } return }
go
func (mj *mirrorJob) monitorMirrorStatus() (errDuringMirror bool) { // now we want to start the progress bar mj.status.Start() defer mj.status.Finish() for sURLs := range mj.statusCh { if sURLs.Error != nil { switch { case sURLs.SourceContent != nil: if !isErrIgnored(sURLs.Error) { errorIf(sURLs.Error.Trace(sURLs.SourceContent.URL.String()), fmt.Sprintf("Failed to copy `%s`.", sURLs.SourceContent.URL.String())) errDuringMirror = true } case sURLs.TargetContent != nil: // When sURLs.SourceContent is nil, we know that we have an error related to removing errorIf(sURLs.Error.Trace(sURLs.TargetContent.URL.String()), fmt.Sprintf("Failed to remove `%s`.", sURLs.TargetContent.URL.String())) errDuringMirror = true default: errorIf(sURLs.Error.Trace(), "Failed to perform mirroring action.") errDuringMirror = true } } if sURLs.SourceContent != nil { } else if sURLs.TargetContent != nil { // Construct user facing message and path. targetPath := filepath.ToSlash(filepath.Join(sURLs.TargetAlias, sURLs.TargetContent.URL.Path)) size := sURLs.TargetContent.Size mj.status.PrintMsg(rmMessage{Key: targetPath, Size: size}) } } return }
[ "func", "(", "mj", "*", "mirrorJob", ")", "monitorMirrorStatus", "(", ")", "(", "errDuringMirror", "bool", ")", "{", "// now we want to start the progress bar", "mj", ".", "status", ".", "Start", "(", ")", "\n", "defer", "mj", ".", "status", ".", "Finish", "(", ")", "\n\n", "for", "sURLs", ":=", "range", "mj", ".", "statusCh", "{", "if", "sURLs", ".", "Error", "!=", "nil", "{", "switch", "{", "case", "sURLs", ".", "SourceContent", "!=", "nil", ":", "if", "!", "isErrIgnored", "(", "sURLs", ".", "Error", ")", "{", "errorIf", "(", "sURLs", ".", "Error", ".", "Trace", "(", "sURLs", ".", "SourceContent", ".", "URL", ".", "String", "(", ")", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sURLs", ".", "SourceContent", ".", "URL", ".", "String", "(", ")", ")", ")", "\n", "errDuringMirror", "=", "true", "\n", "}", "\n", "case", "sURLs", ".", "TargetContent", "!=", "nil", ":", "// When sURLs.SourceContent is nil, we know that we have an error related to removing", "errorIf", "(", "sURLs", ".", "Error", ".", "Trace", "(", "sURLs", ".", "TargetContent", ".", "URL", ".", "String", "(", ")", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sURLs", ".", "TargetContent", ".", "URL", ".", "String", "(", ")", ")", ")", "\n", "errDuringMirror", "=", "true", "\n", "default", ":", "errorIf", "(", "sURLs", ".", "Error", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "errDuringMirror", "=", "true", "\n", "}", "\n", "}", "\n\n", "if", "sURLs", ".", "SourceContent", "!=", "nil", "{", "}", "else", "if", "sURLs", ".", "TargetContent", "!=", "nil", "{", "// Construct user facing message and path.", "targetPath", ":=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Join", "(", "sURLs", ".", "TargetAlias", ",", "sURLs", ".", "TargetContent", ".", "URL", ".", "Path", ")", ")", "\n", "size", ":=", "sURLs", ".", "TargetContent", ".", "Size", "\n", "mj", ".", "status", ".", "PrintMsg", "(", "rmMessage", "{", "Key", ":", "targetPath", ",", "Size", ":", "size", "}", ")", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// Update progress status
[ "Update", "progress", "status" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L289-L324
train
minio/mc
cmd/mirror-main.go
startMirror
func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.CancelFunc) { var totalBytes int64 var totalObjects int64 stopParallel := func() { close(mj.queueCh) mj.parallel.wait() } URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, mj.excludeOptions, mj.encKeyDB) for { select { case sURLs, ok := <-URLsCh: if !ok { stopParallel() return } if sURLs.Error != nil { stopParallel() mj.statusCh <- sURLs return } if sURLs.SourceContent != nil { if mj.olderThan != "" && isOlder(sURLs.SourceContent.Time, mj.olderThan) { continue } if mj.newerThan != "" && isNewer(sURLs.SourceContent.Time, mj.newerThan) { continue } // copy totalBytes += sURLs.SourceContent.Size } totalObjects++ mj.TotalBytes = totalBytes mj.TotalObjects = totalObjects mj.status.SetTotal(totalBytes) // Save total count. sURLs.TotalCount = mj.TotalObjects // Save totalSize. sURLs.TotalSize = mj.TotalBytes if sURLs.SourceContent != nil { mj.queueCh <- func() URLs { return mj.doMirror(ctx, cancelMirror, sURLs) } } else if sURLs.TargetContent != nil && mj.isRemove { mj.queueCh <- func() URLs { return mj.doRemove(sURLs) } } case <-mj.trapCh: stopParallel() cancelMirror() return } } }
go
func (mj *mirrorJob) startMirror(ctx context.Context, cancelMirror context.CancelFunc) { var totalBytes int64 var totalObjects int64 stopParallel := func() { close(mj.queueCh) mj.parallel.wait() } URLsCh := prepareMirrorURLs(mj.sourceURL, mj.targetURL, mj.isFake, mj.isOverwrite, mj.isRemove, mj.excludeOptions, mj.encKeyDB) for { select { case sURLs, ok := <-URLsCh: if !ok { stopParallel() return } if sURLs.Error != nil { stopParallel() mj.statusCh <- sURLs return } if sURLs.SourceContent != nil { if mj.olderThan != "" && isOlder(sURLs.SourceContent.Time, mj.olderThan) { continue } if mj.newerThan != "" && isNewer(sURLs.SourceContent.Time, mj.newerThan) { continue } // copy totalBytes += sURLs.SourceContent.Size } totalObjects++ mj.TotalBytes = totalBytes mj.TotalObjects = totalObjects mj.status.SetTotal(totalBytes) // Save total count. sURLs.TotalCount = mj.TotalObjects // Save totalSize. sURLs.TotalSize = mj.TotalBytes if sURLs.SourceContent != nil { mj.queueCh <- func() URLs { return mj.doMirror(ctx, cancelMirror, sURLs) } } else if sURLs.TargetContent != nil && mj.isRemove { mj.queueCh <- func() URLs { return mj.doRemove(sURLs) } } case <-mj.trapCh: stopParallel() cancelMirror() return } } }
[ "func", "(", "mj", "*", "mirrorJob", ")", "startMirror", "(", "ctx", "context", ".", "Context", ",", "cancelMirror", "context", ".", "CancelFunc", ")", "{", "var", "totalBytes", "int64", "\n", "var", "totalObjects", "int64", "\n\n", "stopParallel", ":=", "func", "(", ")", "{", "close", "(", "mj", ".", "queueCh", ")", "\n", "mj", ".", "parallel", ".", "wait", "(", ")", "\n", "}", "\n\n", "URLsCh", ":=", "prepareMirrorURLs", "(", "mj", ".", "sourceURL", ",", "mj", ".", "targetURL", ",", "mj", ".", "isFake", ",", "mj", ".", "isOverwrite", ",", "mj", ".", "isRemove", ",", "mj", ".", "excludeOptions", ",", "mj", ".", "encKeyDB", ")", "\n\n", "for", "{", "select", "{", "case", "sURLs", ",", "ok", ":=", "<-", "URLsCh", ":", "if", "!", "ok", "{", "stopParallel", "(", ")", "\n", "return", "\n", "}", "\n", "if", "sURLs", ".", "Error", "!=", "nil", "{", "stopParallel", "(", ")", "\n", "mj", ".", "statusCh", "<-", "sURLs", "\n", "return", "\n", "}", "\n\n", "if", "sURLs", ".", "SourceContent", "!=", "nil", "{", "if", "mj", ".", "olderThan", "!=", "\"", "\"", "&&", "isOlder", "(", "sURLs", ".", "SourceContent", ".", "Time", ",", "mj", ".", "olderThan", ")", "{", "continue", "\n", "}", "\n", "if", "mj", ".", "newerThan", "!=", "\"", "\"", "&&", "isNewer", "(", "sURLs", ".", "SourceContent", ".", "Time", ",", "mj", ".", "newerThan", ")", "{", "continue", "\n", "}", "\n", "// copy", "totalBytes", "+=", "sURLs", ".", "SourceContent", ".", "Size", "\n", "}", "\n\n", "totalObjects", "++", "\n", "mj", ".", "TotalBytes", "=", "totalBytes", "\n", "mj", ".", "TotalObjects", "=", "totalObjects", "\n", "mj", ".", "status", ".", "SetTotal", "(", "totalBytes", ")", "\n\n", "// Save total count.", "sURLs", ".", "TotalCount", "=", "mj", ".", "TotalObjects", "\n", "// Save totalSize.", "sURLs", ".", "TotalSize", "=", "mj", ".", "TotalBytes", "\n\n", "if", "sURLs", ".", "SourceContent", "!=", "nil", "{", "mj", ".", "queueCh", "<-", "func", "(", ")", "URLs", "{", "return", "mj", ".", "doMirror", "(", "ctx", ",", "cancelMirror", ",", "sURLs", ")", "\n", "}", "\n", "}", "else", "if", "sURLs", ".", "TargetContent", "!=", "nil", "&&", "mj", ".", "isRemove", "{", "mj", ".", "queueCh", "<-", "func", "(", ")", "URLs", "{", "return", "mj", ".", "doRemove", "(", "sURLs", ")", "\n", "}", "\n", "}", "\n", "case", "<-", "mj", ".", "trapCh", ":", "stopParallel", "(", ")", "\n", "cancelMirror", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// Fetch urls that need to be mirrored
[ "Fetch", "urls", "that", "need", "to", "be", "mirrored" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L487-L547
train
minio/mc
cmd/mirror-main.go
mirror
func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc) bool { var wg sync.WaitGroup // Starts watcher loop for watching for new events. if mj.isWatch { wg.Add(1) go func() { defer wg.Done() mj.watchMirror(ctx, cancelMirror) }() } // Start mirroring. wg.Add(1) go func() { defer wg.Done() mj.startMirror(ctx, cancelMirror) }() // Close statusCh when both watch & mirror quits go func() { wg.Wait() close(mj.statusCh) }() return mj.monitorMirrorStatus() }
go
func (mj *mirrorJob) mirror(ctx context.Context, cancelMirror context.CancelFunc) bool { var wg sync.WaitGroup // Starts watcher loop for watching for new events. if mj.isWatch { wg.Add(1) go func() { defer wg.Done() mj.watchMirror(ctx, cancelMirror) }() } // Start mirroring. wg.Add(1) go func() { defer wg.Done() mj.startMirror(ctx, cancelMirror) }() // Close statusCh when both watch & mirror quits go func() { wg.Wait() close(mj.statusCh) }() return mj.monitorMirrorStatus() }
[ "func", "(", "mj", "*", "mirrorJob", ")", "mirror", "(", "ctx", "context", ".", "Context", ",", "cancelMirror", "context", ".", "CancelFunc", ")", "bool", "{", "var", "wg", "sync", ".", "WaitGroup", "\n\n", "// Starts watcher loop for watching for new events.", "if", "mj", ".", "isWatch", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "mj", ".", "watchMirror", "(", "ctx", ",", "cancelMirror", ")", "\n", "}", "(", ")", "\n", "}", "\n\n", "// Start mirroring.", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "mj", ".", "startMirror", "(", "ctx", ",", "cancelMirror", ")", "\n", "}", "(", ")", "\n\n", "// Close statusCh when both watch & mirror quits", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "mj", ".", "statusCh", ")", "\n", "}", "(", ")", "\n\n", "return", "mj", ".", "monitorMirrorStatus", "(", ")", "\n", "}" ]
// when using a struct for copying, we could save a lot of passing of variables
[ "when", "using", "a", "struct", "for", "copying", "we", "could", "save", "a", "lot", "of", "passing", "of", "variables" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L550-L577
train
minio/mc
cmd/mirror-main.go
copyBucketPolicies
func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error { rules, err := srcClt.GetAccessRules() if err != nil { return err } // Set found rules to target bucket if permitted for _, r := range rules { originalRule, _, err := dstClt.GetAccess() if err != nil { return err } // Set rule only if it doesn't exist in the target bucket // or force flag is activated if originalRule == "none" || isOverwrite { err = dstClt.SetAccess(r, false) if err != nil { return err } } } return nil }
go
func copyBucketPolicies(srcClt, dstClt Client, isOverwrite bool) *probe.Error { rules, err := srcClt.GetAccessRules() if err != nil { return err } // Set found rules to target bucket if permitted for _, r := range rules { originalRule, _, err := dstClt.GetAccess() if err != nil { return err } // Set rule only if it doesn't exist in the target bucket // or force flag is activated if originalRule == "none" || isOverwrite { err = dstClt.SetAccess(r, false) if err != nil { return err } } } return nil }
[ "func", "copyBucketPolicies", "(", "srcClt", ",", "dstClt", "Client", ",", "isOverwrite", "bool", ")", "*", "probe", ".", "Error", "{", "rules", ",", "err", ":=", "srcClt", ".", "GetAccessRules", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Set found rules to target bucket if permitted", "for", "_", ",", "r", ":=", "range", "rules", "{", "originalRule", ",", "_", ",", "err", ":=", "dstClt", ".", "GetAccess", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Set rule only if it doesn't exist in the target bucket", "// or force flag is activated", "if", "originalRule", "==", "\"", "\"", "||", "isOverwrite", "{", "err", "=", "dstClt", ".", "SetAccess", "(", "r", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// copyBucketPolicies - copy policies from source to dest
[ "copyBucketPolicies", "-", "copy", "policies", "from", "source", "to", "dest" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L616-L637
train
minio/mc
cmd/mirror-main.go
mainMirror
func mainMirror(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // check 'mirror' cli arguments. checkMirrorSyntax(ctx, encKeyDB) // Additional command specific theme customization. console.SetColor("Mirror", color.New(color.FgGreen, color.Bold)) args := ctx.Args() srcURL := args[0] tgtURL := args[1] if errorDetected := runMirror(srcURL, tgtURL, ctx, encKeyDB); errorDetected { return exitStatus(globalErrorExitStatus) } return nil }
go
func mainMirror(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // check 'mirror' cli arguments. checkMirrorSyntax(ctx, encKeyDB) // Additional command specific theme customization. console.SetColor("Mirror", color.New(color.FgGreen, color.Bold)) args := ctx.Args() srcURL := args[0] tgtURL := args[1] if errorDetected := runMirror(srcURL, tgtURL, ctx, encKeyDB); errorDetected { return exitStatus(globalErrorExitStatus) } return nil }
[ "func", "mainMirror", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// Parse encryption keys per command.", "encKeyDB", ",", "err", ":=", "getEncKeys", "(", "ctx", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "// check 'mirror' cli arguments.", "checkMirrorSyntax", "(", "ctx", ",", "encKeyDB", ")", "\n\n", "// Additional command specific theme customization.", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ",", "color", ".", "Bold", ")", ")", "\n\n", "args", ":=", "ctx", ".", "Args", "(", ")", "\n\n", "srcURL", ":=", "args", "[", "0", "]", "\n", "tgtURL", ":=", "args", "[", "1", "]", "\n\n", "if", "errorDetected", ":=", "runMirror", "(", "srcURL", ",", "tgtURL", ",", "ctx", ",", "encKeyDB", ")", ";", "errorDetected", "{", "return", "exitStatus", "(", "globalErrorExitStatus", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Main entry point for mirror command.
[ "Main", "entry", "point", "for", "mirror", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-main.go#L731-L752
train
minio/mc
cmd/urls.go
WithError
func (m URLs) WithError(err *probe.Error) URLs { m.Error = err return m }
go
func (m URLs) WithError(err *probe.Error) URLs { m.Error = err return m }
[ "func", "(", "m", "URLs", ")", "WithError", "(", "err", "*", "probe", ".", "Error", ")", "URLs", "{", "m", ".", "Error", "=", "err", "\n", "return", "m", "\n", "}" ]
// WithError sets the error and returns object
[ "WithError", "sets", "the", "error", "and", "returns", "object" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/urls.go#L36-L39
train
minio/mc
cmd/urls.go
Equal
func (m URLs) Equal(n URLs) bool { if m.SourceContent == nil && n.SourceContent == nil { } else if m.SourceContent != nil && n.SourceContent == nil { return false } else if m.SourceContent == nil && n.SourceContent != nil { return false } else if m.SourceContent.URL != n.SourceContent.URL { return false } if m.TargetContent == nil && n.TargetContent == nil { } else if m.TargetContent != nil && n.TargetContent == nil { return false } else if m.TargetContent == nil && n.TargetContent != nil { return false } else if m.TargetContent.URL != n.TargetContent.URL { return false } return true }
go
func (m URLs) Equal(n URLs) bool { if m.SourceContent == nil && n.SourceContent == nil { } else if m.SourceContent != nil && n.SourceContent == nil { return false } else if m.SourceContent == nil && n.SourceContent != nil { return false } else if m.SourceContent.URL != n.SourceContent.URL { return false } if m.TargetContent == nil && n.TargetContent == nil { } else if m.TargetContent != nil && n.TargetContent == nil { return false } else if m.TargetContent == nil && n.TargetContent != nil { return false } else if m.TargetContent.URL != n.TargetContent.URL { return false } return true }
[ "func", "(", "m", "URLs", ")", "Equal", "(", "n", "URLs", ")", "bool", "{", "if", "m", ".", "SourceContent", "==", "nil", "&&", "n", ".", "SourceContent", "==", "nil", "{", "}", "else", "if", "m", ".", "SourceContent", "!=", "nil", "&&", "n", ".", "SourceContent", "==", "nil", "{", "return", "false", "\n", "}", "else", "if", "m", ".", "SourceContent", "==", "nil", "&&", "n", ".", "SourceContent", "!=", "nil", "{", "return", "false", "\n", "}", "else", "if", "m", ".", "SourceContent", ".", "URL", "!=", "n", ".", "SourceContent", ".", "URL", "{", "return", "false", "\n", "}", "\n\n", "if", "m", ".", "TargetContent", "==", "nil", "&&", "n", ".", "TargetContent", "==", "nil", "{", "}", "else", "if", "m", ".", "TargetContent", "!=", "nil", "&&", "n", ".", "TargetContent", "==", "nil", "{", "return", "false", "\n", "}", "else", "if", "m", ".", "TargetContent", "==", "nil", "&&", "n", ".", "TargetContent", "!=", "nil", "{", "return", "false", "\n", "}", "else", "if", "m", ".", "TargetContent", ".", "URL", "!=", "n", ".", "TargetContent", ".", "URL", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Equal tests if both urls are equal
[ "Equal", "tests", "if", "both", "urls", "are", "equal" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/urls.go#L42-L62
train
minio/mc
cmd/common-methods.go
getEncKeys
func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) { sseServer := os.Getenv("MC_ENCRYPT") if prefix := ctx.String("encrypt"); prefix != "" { sseServer = prefix } sseKeys := os.Getenv("MC_ENCRYPT_KEY") if keyPrefix := ctx.String("encrypt-key"); keyPrefix != "" { if sseServer != "" && strings.Contains(keyPrefix, sseServer) { return nil, errConflictSSE(sseServer, keyPrefix).Trace(ctx.Args()...) } sseKeys = keyPrefix } encKeyDB, err := parseAndValidateEncryptionKeys(sseKeys, sseServer) if err != nil { return nil, err.Trace(sseKeys) } return encKeyDB, nil }
go
func getEncKeys(ctx *cli.Context) (map[string][]prefixSSEPair, *probe.Error) { sseServer := os.Getenv("MC_ENCRYPT") if prefix := ctx.String("encrypt"); prefix != "" { sseServer = prefix } sseKeys := os.Getenv("MC_ENCRYPT_KEY") if keyPrefix := ctx.String("encrypt-key"); keyPrefix != "" { if sseServer != "" && strings.Contains(keyPrefix, sseServer) { return nil, errConflictSSE(sseServer, keyPrefix).Trace(ctx.Args()...) } sseKeys = keyPrefix } encKeyDB, err := parseAndValidateEncryptionKeys(sseKeys, sseServer) if err != nil { return nil, err.Trace(sseKeys) } return encKeyDB, nil }
[ "func", "getEncKeys", "(", "ctx", "*", "cli", ".", "Context", ")", "(", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ",", "*", "probe", ".", "Error", ")", "{", "sseServer", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "prefix", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", ";", "prefix", "!=", "\"", "\"", "{", "sseServer", "=", "prefix", "\n", "}", "\n\n", "sseKeys", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "keyPrefix", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", ";", "keyPrefix", "!=", "\"", "\"", "{", "if", "sseServer", "!=", "\"", "\"", "&&", "strings", ".", "Contains", "(", "keyPrefix", ",", "sseServer", ")", "{", "return", "nil", ",", "errConflictSSE", "(", "sseServer", ",", "keyPrefix", ")", ".", "Trace", "(", "ctx", ".", "Args", "(", ")", "...", ")", "\n", "}", "\n", "sseKeys", "=", "keyPrefix", "\n", "}", "\n\n", "encKeyDB", ",", "err", ":=", "parseAndValidateEncryptionKeys", "(", "sseKeys", ",", "sseServer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "sseKeys", ")", "\n", "}", "\n\n", "return", "encKeyDB", ",", "nil", "\n", "}" ]
// parse and return encryption key pairs per alias.
[ "parse", "and", "return", "encryption", "key", "pairs", "per", "alias", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L36-L56
train
minio/mc
cmd/common-methods.go
isAliasURLDir
func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool { // If the target url exists, check if it is a directory // and return immediately. _, targetContent, err := url2Stat(aliasURL, false, keys) if err == nil { return targetContent.Type.IsDir() } _, expandedURL, _ := mustExpandAlias(aliasURL) // Check if targetURL is an FS or S3 aliased url if expandedURL == aliasURL { // This is an FS url, check if the url has a separator at the end return strings.HasSuffix(aliasURL, string(filepath.Separator)) } // This is an S3 url, then: // *) If alias format is specified, return false // *) If alias/bucket is specified, return true // *) If alias/bucket/prefix, check if prefix has // has a trailing slash. pathURL := filepath.ToSlash(aliasURL) fields := strings.Split(pathURL, "/") switch len(fields) { // Nothing or alias format case 0, 1: return false // alias/bucket format case 2: return true } // default case.. // alias/bucket/prefix format return strings.HasSuffix(pathURL, "/") }
go
func isAliasURLDir(aliasURL string, keys map[string][]prefixSSEPair) bool { // If the target url exists, check if it is a directory // and return immediately. _, targetContent, err := url2Stat(aliasURL, false, keys) if err == nil { return targetContent.Type.IsDir() } _, expandedURL, _ := mustExpandAlias(aliasURL) // Check if targetURL is an FS or S3 aliased url if expandedURL == aliasURL { // This is an FS url, check if the url has a separator at the end return strings.HasSuffix(aliasURL, string(filepath.Separator)) } // This is an S3 url, then: // *) If alias format is specified, return false // *) If alias/bucket is specified, return true // *) If alias/bucket/prefix, check if prefix has // has a trailing slash. pathURL := filepath.ToSlash(aliasURL) fields := strings.Split(pathURL, "/") switch len(fields) { // Nothing or alias format case 0, 1: return false // alias/bucket format case 2: return true } // default case.. // alias/bucket/prefix format return strings.HasSuffix(pathURL, "/") }
[ "func", "isAliasURLDir", "(", "aliasURL", "string", ",", "keys", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ")", "bool", "{", "// If the target url exists, check if it is a directory", "// and return immediately.", "_", ",", "targetContent", ",", "err", ":=", "url2Stat", "(", "aliasURL", ",", "false", ",", "keys", ")", "\n", "if", "err", "==", "nil", "{", "return", "targetContent", ".", "Type", ".", "IsDir", "(", ")", "\n", "}", "\n\n", "_", ",", "expandedURL", ",", "_", ":=", "mustExpandAlias", "(", "aliasURL", ")", "\n\n", "// Check if targetURL is an FS or S3 aliased url", "if", "expandedURL", "==", "aliasURL", "{", "// This is an FS url, check if the url has a separator at the end", "return", "strings", ".", "HasSuffix", "(", "aliasURL", ",", "string", "(", "filepath", ".", "Separator", ")", ")", "\n", "}", "\n\n", "// This is an S3 url, then:", "// *) If alias format is specified, return false", "// *) If alias/bucket is specified, return true", "// *) If alias/bucket/prefix, check if prefix has", "//\t has a trailing slash.", "pathURL", ":=", "filepath", ".", "ToSlash", "(", "aliasURL", ")", "\n", "fields", ":=", "strings", ".", "Split", "(", "pathURL", ",", "\"", "\"", ")", "\n", "switch", "len", "(", "fields", ")", "{", "// Nothing or alias format", "case", "0", ",", "1", ":", "return", "false", "\n", "// alias/bucket format", "case", "2", ":", "return", "true", "\n", "}", "// default case..", "\n\n", "// alias/bucket/prefix format", "return", "strings", ".", "HasSuffix", "(", "pathURL", ",", "\"", "\"", ")", "\n", "}" ]
// Check if the passed URL represents a folder. It may or may not exist yet. // If it exists, we can easily check if it is a folder, if it doesn't exist, // we can guess if the url is a folder from how it looks.
[ "Check", "if", "the", "passed", "URL", "represents", "a", "folder", ".", "It", "may", "or", "may", "not", "exist", "yet", ".", "If", "it", "exists", "we", "can", "easily", "check", "if", "it", "is", "a", "folder", "if", "it", "doesn", "t", "exist", "we", "can", "guess", "if", "the", "url", "is", "a", "folder", "from", "how", "it", "looks", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L61-L95
train
minio/mc
cmd/common-methods.go
getSourceStreamMetadataFromURL
func getSourceStreamMetadataFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) } sseKey := getSSE(urlStr, encKeyDB[alias]) return getSourceStream(alias, urlStrFull, true, sseKey) }
go
func getSourceStreamMetadataFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) } sseKey := getSSE(urlStr, encKeyDB[alias]) return getSourceStream(alias, urlStrFull, true, sseKey) }
[ "func", "getSourceStreamMetadataFromURL", "(", "urlStr", "string", ",", "encKeyDB", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ")", "(", "reader", "io", ".", "ReadCloser", ",", "metadata", "map", "[", "string", "]", "string", ",", "err", "*", "probe", ".", "Error", ")", "{", "alias", ",", "urlStrFull", ",", "_", ",", "err", ":=", "expandAlias", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", ".", "Trace", "(", "urlStr", ")", "\n", "}", "\n", "sseKey", ":=", "getSSE", "(", "urlStr", ",", "encKeyDB", "[", "alias", "]", ")", "\n", "return", "getSourceStream", "(", "alias", ",", "urlStrFull", ",", "true", ",", "sseKey", ")", "\n", "}" ]
// getSourceStreamMetadataFromURL gets a reader from URL.
[ "getSourceStreamMetadataFromURL", "gets", "a", "reader", "from", "URL", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L98-L106
train
minio/mc
cmd/common-methods.go
getSourceStreamFromURL
func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, err.Trace(urlStr) } sse := getSSE(urlStr, encKeyDB[alias]) reader, _, err = getSourceStream(alias, urlStrFull, false, sse) return reader, err }
go
func getSourceStreamFromURL(urlStr string, encKeyDB map[string][]prefixSSEPair) (reader io.ReadCloser, err *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return nil, err.Trace(urlStr) } sse := getSSE(urlStr, encKeyDB[alias]) reader, _, err = getSourceStream(alias, urlStrFull, false, sse) return reader, err }
[ "func", "getSourceStreamFromURL", "(", "urlStr", "string", ",", "encKeyDB", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ")", "(", "reader", "io", ".", "ReadCloser", ",", "err", "*", "probe", ".", "Error", ")", "{", "alias", ",", "urlStrFull", ",", "_", ",", "err", ":=", "expandAlias", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "urlStr", ")", "\n", "}", "\n", "sse", ":=", "getSSE", "(", "urlStr", ",", "encKeyDB", "[", "alias", "]", ")", "\n", "reader", ",", "_", ",", "err", "=", "getSourceStream", "(", "alias", ",", "urlStrFull", ",", "false", ",", "sse", ")", "\n", "return", "reader", ",", "err", "\n", "}" ]
// getSourceStreamFromURL gets a reader from URL.
[ "getSourceStreamFromURL", "gets", "a", "reader", "from", "URL", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L109-L117
train
minio/mc
cmd/common-methods.go
getSourceStream
func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) { sourceClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return nil, nil, err.Trace(alias, urlStr) } reader, err = sourceClnt.Get(sse) if err != nil { return nil, nil, err.Trace(alias, urlStr) } metadata = make(map[string]string) if fetchStat { st, err := sourceClnt.Stat(false, true, sse) if err != nil { return nil, nil, err.Trace(alias, urlStr) } for k, v := range st.Metadata { if httpguts.ValidHeaderFieldName(k) && httpguts.ValidHeaderFieldValue(v) { metadata[k] = v } } // If our reader is a seeker try to detect content-type further. if s, ok := reader.(io.ReadSeeker); ok { // All unrecognized files have `application/octet-stream` // So we continue our detection process. if ctype := metadata["Content-Type"]; ctype == "application/octet-stream" { // Read a chunk to decide between utf-8 text and binary var buf [512]byte n, _ := io.ReadFull(reader, buf[:]) if n > 0 { kind, e := filetype.Match(buf[:n]) if e != nil { return nil, nil, probe.NewError(e) } // rewind to output whole file if _, e := s.Seek(0, io.SeekStart); e != nil { return nil, nil, probe.NewError(e) } ctype = kind.MIME.Value if ctype == "" { ctype = "application/octet-stream" } metadata["Content-Type"] = ctype } } } } return reader, metadata, nil }
go
func getSourceStream(alias string, urlStr string, fetchStat bool, sse encrypt.ServerSide) (reader io.ReadCloser, metadata map[string]string, err *probe.Error) { sourceClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return nil, nil, err.Trace(alias, urlStr) } reader, err = sourceClnt.Get(sse) if err != nil { return nil, nil, err.Trace(alias, urlStr) } metadata = make(map[string]string) if fetchStat { st, err := sourceClnt.Stat(false, true, sse) if err != nil { return nil, nil, err.Trace(alias, urlStr) } for k, v := range st.Metadata { if httpguts.ValidHeaderFieldName(k) && httpguts.ValidHeaderFieldValue(v) { metadata[k] = v } } // If our reader is a seeker try to detect content-type further. if s, ok := reader.(io.ReadSeeker); ok { // All unrecognized files have `application/octet-stream` // So we continue our detection process. if ctype := metadata["Content-Type"]; ctype == "application/octet-stream" { // Read a chunk to decide between utf-8 text and binary var buf [512]byte n, _ := io.ReadFull(reader, buf[:]) if n > 0 { kind, e := filetype.Match(buf[:n]) if e != nil { return nil, nil, probe.NewError(e) } // rewind to output whole file if _, e := s.Seek(0, io.SeekStart); e != nil { return nil, nil, probe.NewError(e) } ctype = kind.MIME.Value if ctype == "" { ctype = "application/octet-stream" } metadata["Content-Type"] = ctype } } } } return reader, metadata, nil }
[ "func", "getSourceStream", "(", "alias", "string", ",", "urlStr", "string", ",", "fetchStat", "bool", ",", "sse", "encrypt", ".", "ServerSide", ")", "(", "reader", "io", ".", "ReadCloser", ",", "metadata", "map", "[", "string", "]", "string", ",", "err", "*", "probe", ".", "Error", ")", "{", "sourceClnt", ",", "err", ":=", "newClientFromAlias", "(", "alias", ",", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "reader", ",", "err", "=", "sourceClnt", ".", "Get", "(", "sse", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "metadata", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "if", "fetchStat", "{", "st", ",", "err", ":=", "sourceClnt", ".", "Stat", "(", "false", ",", "true", ",", "sse", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "st", ".", "Metadata", "{", "if", "httpguts", ".", "ValidHeaderFieldName", "(", "k", ")", "&&", "httpguts", ".", "ValidHeaderFieldValue", "(", "v", ")", "{", "metadata", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "// If our reader is a seeker try to detect content-type further.", "if", "s", ",", "ok", ":=", "reader", ".", "(", "io", ".", "ReadSeeker", ")", ";", "ok", "{", "// All unrecognized files have `application/octet-stream`", "// So we continue our detection process.", "if", "ctype", ":=", "metadata", "[", "\"", "\"", "]", ";", "ctype", "==", "\"", "\"", "{", "// Read a chunk to decide between utf-8 text and binary", "var", "buf", "[", "512", "]", "byte", "\n", "n", ",", "_", ":=", "io", ".", "ReadFull", "(", "reader", ",", "buf", "[", ":", "]", ")", "\n", "if", "n", ">", "0", "{", "kind", ",", "e", ":=", "filetype", ".", "Match", "(", "buf", "[", ":", "n", "]", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "// rewind to output whole file", "if", "_", ",", "e", ":=", "s", ".", "Seek", "(", "0", ",", "io", ".", "SeekStart", ")", ";", "e", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "ctype", "=", "kind", ".", "MIME", ".", "Value", "\n", "if", "ctype", "==", "\"", "\"", "{", "ctype", "=", "\"", "\"", "\n", "}", "\n", "metadata", "[", "\"", "\"", "]", "=", "ctype", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "reader", ",", "metadata", ",", "nil", "\n", "}" ]
// getSourceStream gets a reader from URL.
[ "getSourceStream", "gets", "a", "reader", "from", "URL", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L120-L168
train
minio/mc
cmd/common-methods.go
putTargetStream
func putTargetStream(ctx context.Context, alias string, urlStr string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return 0, err.Trace(alias, urlStr) } n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse) if err != nil { return n, err.Trace(alias, urlStr) } return n, nil }
go
func putTargetStream(ctx context.Context, alias string, urlStr string, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return 0, err.Trace(alias, urlStr) } n, err := targetClnt.Put(ctx, reader, size, metadata, progress, sse) if err != nil { return n, err.Trace(alias, urlStr) } return n, nil }
[ "func", "putTargetStream", "(", "ctx", "context", ".", "Context", ",", "alias", "string", ",", "urlStr", "string", ",", "reader", "io", ".", "Reader", ",", "size", "int64", ",", "metadata", "map", "[", "string", "]", "string", ",", "progress", "io", ".", "Reader", ",", "sse", "encrypt", ".", "ServerSide", ")", "(", "int64", ",", "*", "probe", ".", "Error", ")", "{", "targetClnt", ",", "err", ":=", "newClientFromAlias", "(", "alias", ",", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "n", ",", "err", ":=", "targetClnt", ".", "Put", "(", "ctx", ",", "reader", ",", "size", ",", "metadata", ",", "progress", ",", "sse", ")", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "return", "n", ",", "nil", "\n", "}" ]
// putTargetStream writes to URL from Reader.
[ "putTargetStream", "writes", "to", "URL", "from", "Reader", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L171-L181
train
minio/mc
cmd/common-methods.go
putTargetStreamWithURL
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide) (int64, *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return 0, err.Trace(alias, urlStr) } contentType := guessURLContentType(urlStr) metadata := map[string]string{ "Content-Type": contentType, } return putTargetStream(context.Background(), alias, urlStrFull, reader, size, metadata, nil, sse) }
go
func putTargetStreamWithURL(urlStr string, reader io.Reader, size int64, sse encrypt.ServerSide) (int64, *probe.Error) { alias, urlStrFull, _, err := expandAlias(urlStr) if err != nil { return 0, err.Trace(alias, urlStr) } contentType := guessURLContentType(urlStr) metadata := map[string]string{ "Content-Type": contentType, } return putTargetStream(context.Background(), alias, urlStrFull, reader, size, metadata, nil, sse) }
[ "func", "putTargetStreamWithURL", "(", "urlStr", "string", ",", "reader", "io", ".", "Reader", ",", "size", "int64", ",", "sse", "encrypt", ".", "ServerSide", ")", "(", "int64", ",", "*", "probe", ".", "Error", ")", "{", "alias", ",", "urlStrFull", ",", "_", ",", "err", ":=", "expandAlias", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "contentType", ":=", "guessURLContentType", "(", "urlStr", ")", "\n", "metadata", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "contentType", ",", "}", "\n", "return", "putTargetStream", "(", "context", ".", "Background", "(", ")", ",", "alias", ",", "urlStrFull", ",", "reader", ",", "size", ",", "metadata", ",", "nil", ",", "sse", ")", "\n", "}" ]
// putTargetStreamWithURL writes to URL from reader. If length=-1, read until EOF.
[ "putTargetStreamWithURL", "writes", "to", "URL", "from", "reader", ".", "If", "length", "=", "-", "1", "read", "until", "EOF", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L184-L194
train
minio/mc
cmd/common-methods.go
copySourceToTargetURL
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return err.Trace(alias, urlStr) } err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata) if err != nil { return err.Trace(alias, urlStr) } return nil }
go
func copySourceToTargetURL(alias string, urlStr string, source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error { targetClnt, err := newClientFromAlias(alias, urlStr) if err != nil { return err.Trace(alias, urlStr) } err = targetClnt.Copy(source, size, progress, srcSSE, tgtSSE, metadata) if err != nil { return err.Trace(alias, urlStr) } return nil }
[ "func", "copySourceToTargetURL", "(", "alias", "string", ",", "urlStr", "string", ",", "source", "string", ",", "size", "int64", ",", "progress", "io", ".", "Reader", ",", "srcSSE", ",", "tgtSSE", "encrypt", ".", "ServerSide", ",", "metadata", "map", "[", "string", "]", "string", ")", "*", "probe", ".", "Error", "{", "targetClnt", ",", "err", ":=", "newClientFromAlias", "(", "alias", ",", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "err", "=", "targetClnt", ".", "Copy", "(", "source", ",", "size", ",", "progress", ",", "srcSSE", ",", "tgtSSE", ",", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// copySourceToTargetURL copies to targetURL from source.
[ "copySourceToTargetURL", "copies", "to", "targetURL", "from", "source", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L197-L207
train
minio/mc
cmd/common-methods.go
createUserMetadata
func createUserMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) { metadata := make(map[string]string) sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr) if err != nil { return nil, err.Trace(sourceAlias, sourceURLStr) } st, err := sourceClnt.Stat(false, true, srcSSE) if err != nil { return nil, err.Trace(sourceAlias, sourceURLStr) } for k, v := range st.Metadata { if httpguts.ValidHeaderFieldName(k) && strings.HasPrefix(k, "X-Amz-Meta-") && httpguts.ValidHeaderFieldValue(v) { metadata[k] = v } } for k, v := range urls.TargetContent.UserMetadata { metadata[k] = v } return metadata, nil }
go
func createUserMetadata(sourceAlias, sourceURLStr string, srcSSE encrypt.ServerSide, urls URLs) (map[string]string, *probe.Error) { metadata := make(map[string]string) sourceClnt, err := newClientFromAlias(sourceAlias, sourceURLStr) if err != nil { return nil, err.Trace(sourceAlias, sourceURLStr) } st, err := sourceClnt.Stat(false, true, srcSSE) if err != nil { return nil, err.Trace(sourceAlias, sourceURLStr) } for k, v := range st.Metadata { if httpguts.ValidHeaderFieldName(k) && strings.HasPrefix(k, "X-Amz-Meta-") && httpguts.ValidHeaderFieldValue(v) { metadata[k] = v } } for k, v := range urls.TargetContent.UserMetadata { metadata[k] = v } return metadata, nil }
[ "func", "createUserMetadata", "(", "sourceAlias", ",", "sourceURLStr", "string", ",", "srcSSE", "encrypt", ".", "ServerSide", ",", "urls", "URLs", ")", "(", "map", "[", "string", "]", "string", ",", "*", "probe", ".", "Error", ")", "{", "metadata", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "sourceClnt", ",", "err", ":=", "newClientFromAlias", "(", "sourceAlias", ",", "sourceURLStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "sourceAlias", ",", "sourceURLStr", ")", "\n", "}", "\n", "st", ",", "err", ":=", "sourceClnt", ".", "Stat", "(", "false", ",", "true", ",", "srcSSE", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "sourceAlias", ",", "sourceURLStr", ")", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "st", ".", "Metadata", "{", "if", "httpguts", ".", "ValidHeaderFieldName", "(", "k", ")", "&&", "strings", ".", "HasPrefix", "(", "k", ",", "\"", "\"", ")", "&&", "httpguts", ".", "ValidHeaderFieldValue", "(", "v", ")", "{", "metadata", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "urls", ".", "TargetContent", ".", "UserMetadata", "{", "metadata", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "metadata", ",", "nil", "\n", "}" ]
// createUserMetadata - returns a map of user defined function // by combining the usermetadata of object and values passed by attr keyword
[ "createUserMetadata", "-", "returns", "a", "map", "of", "user", "defined", "function", "by", "combining", "the", "usermetadata", "of", "object", "and", "values", "passed", "by", "attr", "keyword" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L211-L232
train
minio/mc
cmd/common-methods.go
uploadSourceToTargetURL
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair) URLs { sourceAlias := urls.SourceAlias sourceURL := urls.SourceContent.URL targetAlias := urls.TargetAlias targetURL := urls.TargetContent.URL length := urls.SourceContent.Size sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, urls.SourceContent.URL.Path)) targetPath := filepath.ToSlash(filepath.Join(targetAlias, urls.TargetContent.URL.Path)) srcSSE := getSSE(sourcePath, encKeyDB[sourceAlias]) tgtSSE := getSSE(targetPath, encKeyDB[targetAlias]) // Optimize for server side copy if the host is same. if sourceAlias == targetAlias { metadata, err := createUserMetadata(sourceAlias, sourceURL.String(), srcSSE, urls) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } sourcePath := filepath.ToSlash(sourceURL.Path) err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, srcSSE, tgtSSE, metadata) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } } else { // Proceed with regular stream copy. reader, metadata, err := getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } defer reader.Close() // Get metadata from target content as well if urls.TargetContent.Metadata != nil { for k, v := range urls.TargetContent.Metadata { metadata[k] = v } } // Get userMetadata from target content as well if urls.TargetContent.UserMetadata != nil { for k, v := range urls.TargetContent.UserMetadata { metadata[k] = v } } if srcSSE != nil { delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm") delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5") } _, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress, tgtSSE) if err != nil { return urls.WithError(err.Trace(targetURL.String())) } } return urls.WithError(nil) }
go
func uploadSourceToTargetURL(ctx context.Context, urls URLs, progress io.Reader, encKeyDB map[string][]prefixSSEPair) URLs { sourceAlias := urls.SourceAlias sourceURL := urls.SourceContent.URL targetAlias := urls.TargetAlias targetURL := urls.TargetContent.URL length := urls.SourceContent.Size sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, urls.SourceContent.URL.Path)) targetPath := filepath.ToSlash(filepath.Join(targetAlias, urls.TargetContent.URL.Path)) srcSSE := getSSE(sourcePath, encKeyDB[sourceAlias]) tgtSSE := getSSE(targetPath, encKeyDB[targetAlias]) // Optimize for server side copy if the host is same. if sourceAlias == targetAlias { metadata, err := createUserMetadata(sourceAlias, sourceURL.String(), srcSSE, urls) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } sourcePath := filepath.ToSlash(sourceURL.Path) err = copySourceToTargetURL(targetAlias, targetURL.String(), sourcePath, length, progress, srcSSE, tgtSSE, metadata) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } } else { // Proceed with regular stream copy. reader, metadata, err := getSourceStream(sourceAlias, sourceURL.String(), true, srcSSE) if err != nil { return urls.WithError(err.Trace(sourceURL.String())) } defer reader.Close() // Get metadata from target content as well if urls.TargetContent.Metadata != nil { for k, v := range urls.TargetContent.Metadata { metadata[k] = v } } // Get userMetadata from target content as well if urls.TargetContent.UserMetadata != nil { for k, v := range urls.TargetContent.UserMetadata { metadata[k] = v } } if srcSSE != nil { delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Algorithm") delete(metadata, "X-Amz-Server-Side-Encryption-Customer-Key-Md5") } _, err = putTargetStream(ctx, targetAlias, targetURL.String(), reader, length, metadata, progress, tgtSSE) if err != nil { return urls.WithError(err.Trace(targetURL.String())) } } return urls.WithError(nil) }
[ "func", "uploadSourceToTargetURL", "(", "ctx", "context", ".", "Context", ",", "urls", "URLs", ",", "progress", "io", ".", "Reader", ",", "encKeyDB", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ")", "URLs", "{", "sourceAlias", ":=", "urls", ".", "SourceAlias", "\n", "sourceURL", ":=", "urls", ".", "SourceContent", ".", "URL", "\n", "targetAlias", ":=", "urls", ".", "TargetAlias", "\n", "targetURL", ":=", "urls", ".", "TargetContent", ".", "URL", "\n", "length", ":=", "urls", ".", "SourceContent", ".", "Size", "\n\n", "sourcePath", ":=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Join", "(", "sourceAlias", ",", "urls", ".", "SourceContent", ".", "URL", ".", "Path", ")", ")", "\n", "targetPath", ":=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Join", "(", "targetAlias", ",", "urls", ".", "TargetContent", ".", "URL", ".", "Path", ")", ")", "\n\n", "srcSSE", ":=", "getSSE", "(", "sourcePath", ",", "encKeyDB", "[", "sourceAlias", "]", ")", "\n", "tgtSSE", ":=", "getSSE", "(", "targetPath", ",", "encKeyDB", "[", "targetAlias", "]", ")", "\n\n", "// Optimize for server side copy if the host is same.", "if", "sourceAlias", "==", "targetAlias", "{", "metadata", ",", "err", ":=", "createUserMetadata", "(", "sourceAlias", ",", "sourceURL", ".", "String", "(", ")", ",", "srcSSE", ",", "urls", ")", "\n", "if", "err", "!=", "nil", "{", "return", "urls", ".", "WithError", "(", "err", ".", "Trace", "(", "sourceURL", ".", "String", "(", ")", ")", ")", "\n", "}", "\n\n", "sourcePath", ":=", "filepath", ".", "ToSlash", "(", "sourceURL", ".", "Path", ")", "\n", "err", "=", "copySourceToTargetURL", "(", "targetAlias", ",", "targetURL", ".", "String", "(", ")", ",", "sourcePath", ",", "length", ",", "progress", ",", "srcSSE", ",", "tgtSSE", ",", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "urls", ".", "WithError", "(", "err", ".", "Trace", "(", "sourceURL", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "}", "else", "{", "// Proceed with regular stream copy.", "reader", ",", "metadata", ",", "err", ":=", "getSourceStream", "(", "sourceAlias", ",", "sourceURL", ".", "String", "(", ")", ",", "true", ",", "srcSSE", ")", "\n", "if", "err", "!=", "nil", "{", "return", "urls", ".", "WithError", "(", "err", ".", "Trace", "(", "sourceURL", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "defer", "reader", ".", "Close", "(", ")", "\n", "// Get metadata from target content as well", "if", "urls", ".", "TargetContent", ".", "Metadata", "!=", "nil", "{", "for", "k", ",", "v", ":=", "range", "urls", ".", "TargetContent", ".", "Metadata", "{", "metadata", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "// Get userMetadata from target content as well", "if", "urls", ".", "TargetContent", ".", "UserMetadata", "!=", "nil", "{", "for", "k", ",", "v", ":=", "range", "urls", ".", "TargetContent", ".", "UserMetadata", "{", "metadata", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "if", "srcSSE", "!=", "nil", "{", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "err", "=", "putTargetStream", "(", "ctx", ",", "targetAlias", ",", "targetURL", ".", "String", "(", ")", ",", "reader", ",", "length", ",", "metadata", ",", "progress", ",", "tgtSSE", ")", "\n", "if", "err", "!=", "nil", "{", "return", "urls", ".", "WithError", "(", "err", ".", "Trace", "(", "targetURL", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "return", "urls", ".", "WithError", "(", "nil", ")", "\n", "}" ]
// uploadSourceToTargetURL - uploads to targetURL from source. // optionally optimizes copy for object sizes <= 5GiB by using // server side copy operation.
[ "uploadSourceToTargetURL", "-", "uploads", "to", "targetURL", "from", "source", ".", "optionally", "optimizes", "copy", "for", "object", "sizes", "<", "=", "5GiB", "by", "using", "server", "side", "copy", "operation", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L237-L293
train
minio/mc
cmd/common-methods.go
newClientFromAlias
func newClientFromAlias(alias, urlStr string) (Client, *probe.Error) { alias, _, hostCfg, err := expandAlias(alias) if err != nil { return nil, err.Trace(alias, urlStr) } if hostCfg == nil { // No matching host config. So we treat it like a // filesystem. fsClient, fsErr := fsNew(urlStr) if fsErr != nil { return nil, fsErr.Trace(alias, urlStr) } return fsClient, nil } s3Config := newS3Config(urlStr, hostCfg) s3Client, err := s3New(s3Config) if err != nil { return nil, err.Trace(alias, urlStr) } return s3Client, nil }
go
func newClientFromAlias(alias, urlStr string) (Client, *probe.Error) { alias, _, hostCfg, err := expandAlias(alias) if err != nil { return nil, err.Trace(alias, urlStr) } if hostCfg == nil { // No matching host config. So we treat it like a // filesystem. fsClient, fsErr := fsNew(urlStr) if fsErr != nil { return nil, fsErr.Trace(alias, urlStr) } return fsClient, nil } s3Config := newS3Config(urlStr, hostCfg) s3Client, err := s3New(s3Config) if err != nil { return nil, err.Trace(alias, urlStr) } return s3Client, nil }
[ "func", "newClientFromAlias", "(", "alias", ",", "urlStr", "string", ")", "(", "Client", ",", "*", "probe", ".", "Error", ")", "{", "alias", ",", "_", ",", "hostCfg", ",", "err", ":=", "expandAlias", "(", "alias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n\n", "if", "hostCfg", "==", "nil", "{", "// No matching host config. So we treat it like a", "// filesystem.", "fsClient", ",", "fsErr", ":=", "fsNew", "(", "urlStr", ")", "\n", "if", "fsErr", "!=", "nil", "{", "return", "nil", ",", "fsErr", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "return", "fsClient", ",", "nil", "\n", "}", "\n\n", "s3Config", ":=", "newS3Config", "(", "urlStr", ",", "hostCfg", ")", "\n\n", "s3Client", ",", "err", ":=", "s3New", "(", "s3Config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "alias", ",", "urlStr", ")", "\n", "}", "\n", "return", "s3Client", ",", "nil", "\n", "}" ]
// newClientFromAlias gives a new client interface for matching // alias entry in the mc config file. If no matching host config entry // is found, fs client is returned.
[ "newClientFromAlias", "gives", "a", "new", "client", "interface", "for", "matching", "alias", "entry", "in", "the", "mc", "config", "file", ".", "If", "no", "matching", "host", "config", "entry", "is", "found", "fs", "client", "is", "returned", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L298-L321
train
minio/mc
cmd/common-methods.go
newClient
func newClient(aliasedURL string) (Client, *probe.Error) { alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL) if err != nil { return nil, err.Trace(aliasedURL) } // Verify if the aliasedURL is a real URL, fail in those cases // indicating the user to add alias. if hostCfg == nil && urlRgx.MatchString(aliasedURL) { return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL) } return newClientFromAlias(alias, urlStrFull) }
go
func newClient(aliasedURL string) (Client, *probe.Error) { alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL) if err != nil { return nil, err.Trace(aliasedURL) } // Verify if the aliasedURL is a real URL, fail in those cases // indicating the user to add alias. if hostCfg == nil && urlRgx.MatchString(aliasedURL) { return nil, errInvalidAliasedURL(aliasedURL).Trace(aliasedURL) } return newClientFromAlias(alias, urlStrFull) }
[ "func", "newClient", "(", "aliasedURL", "string", ")", "(", "Client", ",", "*", "probe", ".", "Error", ")", "{", "alias", ",", "urlStrFull", ",", "hostCfg", ",", "err", ":=", "expandAlias", "(", "aliasedURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "aliasedURL", ")", "\n", "}", "\n", "// Verify if the aliasedURL is a real URL, fail in those cases", "// indicating the user to add alias.", "if", "hostCfg", "==", "nil", "&&", "urlRgx", ".", "MatchString", "(", "aliasedURL", ")", "{", "return", "nil", ",", "errInvalidAliasedURL", "(", "aliasedURL", ")", ".", "Trace", "(", "aliasedURL", ")", "\n", "}", "\n", "return", "newClientFromAlias", "(", "alias", ",", "urlStrFull", ")", "\n", "}" ]
// newClient gives a new client interface
[ "newClient", "gives", "a", "new", "client", "interface" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/common-methods.go#L327-L338
train
minio/mc
cmd/admin-policy-list.go
checkAdminPolicyListSyntax
func checkAdminPolicyListSyntax(ctx *cli.Context) { if len(ctx.Args()) < 1 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code } }
go
func checkAdminPolicyListSyntax(ctx *cli.Context) { if len(ctx.Args()) < 1 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code } }
[ "func", "checkAdminPolicyListSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "<", "1", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminPolicyListSyntax - validate all the passed arguments
[ "checkAdminPolicyListSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-policy-list.go#L55-L59
train
minio/mc
cmd/admin-policy-list.go
mainAdminPolicyList
func mainAdminPolicyList(ctx *cli.Context) error { checkAdminPolicyListSyntax(ctx) console.SetColor("PolicyMessage", color.New(color.FgGreen)) console.SetColor("Policy", color.New(color.FgBlue)) // 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.") policies, e := client.ListCannedPolicies() fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy") if policyName := args.Get(1); policyName != "" { if len(policies[policyName]) != 0 { printMsg(userPolicyMessage{ op: "list", Policy: policyName, PolicyJSON: policies[policyName], }) } else { fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Cannot list the policy") } } else { for k := range policies { printMsg(userPolicyMessage{ op: "list", Policy: k, }) } } return nil }
go
func mainAdminPolicyList(ctx *cli.Context) error { checkAdminPolicyListSyntax(ctx) console.SetColor("PolicyMessage", color.New(color.FgGreen)) console.SetColor("Policy", color.New(color.FgBlue)) // 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.") policies, e := client.ListCannedPolicies() fatalIf(probe.NewError(e).Trace(args...), "Cannot list policy") if policyName := args.Get(1); policyName != "" { if len(policies[policyName]) != 0 { printMsg(userPolicyMessage{ op: "list", Policy: policyName, PolicyJSON: policies[policyName], }) } else { fatalIf(probe.NewError(fmt.Errorf("%s is not found", policyName)), "Cannot list the policy") } } else { for k := range policies { printMsg(userPolicyMessage{ op: "list", Policy: k, }) } } return nil }
[ "func", "mainAdminPolicyList", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "checkAdminPolicyListSyntax", "(", "ctx", ")", "\n\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgBlue", ")", ")", "\n\n", "// Get the alias parameter from cli", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "aliasedURL", ":=", "args", ".", "Get", "(", "0", ")", "\n\n", "// Create a new MinIO Admin Client", "client", ",", "err", ":=", "newAdminClient", "(", "aliasedURL", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "policies", ",", "e", ":=", "client", ".", "ListCannedPolicies", "(", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "args", "...", ")", ",", "\"", "\"", ")", "\n\n", "if", "policyName", ":=", "args", ".", "Get", "(", "1", ")", ";", "policyName", "!=", "\"", "\"", "{", "if", "len", "(", "policies", "[", "policyName", "]", ")", "!=", "0", "{", "printMsg", "(", "userPolicyMessage", "{", "op", ":", "\"", "\"", ",", "Policy", ":", "policyName", ",", "PolicyJSON", ":", "policies", "[", "policyName", "]", ",", "}", ")", "\n", "}", "else", "{", "fatalIf", "(", "probe", ".", "NewError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "policyName", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "for", "k", ":=", "range", "policies", "{", "printMsg", "(", "userPolicyMessage", "{", "op", ":", "\"", "\"", ",", "Policy", ":", "k", ",", "}", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mainAdminPolicyList is the handle for "mc admin policy add" command.
[ "mainAdminPolicyList", "is", "the", "handle", "for", "mc", "admin", "policy", "add", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-policy-list.go#L62-L98
train
minio/mc
cmd/mirror-url.go
prepareMirrorURLs
func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, encKeyDB map[string][]prefixSSEPair) <-chan URLs { URLsCh := make(chan URLs) go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, excludeOptions, URLsCh, encKeyDB) return URLsCh }
go
func prepareMirrorURLs(sourceURL string, targetURL string, isFake, isOverwrite, isRemove bool, excludeOptions []string, encKeyDB map[string][]prefixSSEPair) <-chan URLs { URLsCh := make(chan URLs) go deltaSourceTarget(sourceURL, targetURL, isFake, isOverwrite, isRemove, excludeOptions, URLsCh, encKeyDB) return URLsCh }
[ "func", "prepareMirrorURLs", "(", "sourceURL", "string", ",", "targetURL", "string", ",", "isFake", ",", "isOverwrite", ",", "isRemove", "bool", ",", "excludeOptions", "[", "]", "string", ",", "encKeyDB", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ")", "<-", "chan", "URLs", "{", "URLsCh", ":=", "make", "(", "chan", "URLs", ")", "\n", "go", "deltaSourceTarget", "(", "sourceURL", ",", "targetURL", ",", "isFake", ",", "isOverwrite", ",", "isRemove", ",", "excludeOptions", ",", "URLsCh", ",", "encKeyDB", ")", "\n", "return", "URLsCh", "\n", "}" ]
// Prepares urls that need to be copied or removed based on requested options.
[ "Prepares", "urls", "that", "need", "to", "be", "copied", "or", "removed", "based", "on", "requested", "options", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/mirror-url.go#L190-L194
train
minio/mc
cmd/admin-profile-start.go
mainAdminProfileStart
func mainAdminProfileStart(ctx *cli.Context) error { // Check for command syntax checkAdminProfileStartSyntax(ctx) // Get the alias parameter from cli args := ctx.Args() aliasedURL := args.Get(0) profilerType := ctx.String("type") // Create a new MinIO Admin Client client, err := newAdminClient(aliasedURL) if err != nil { fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.") return nil } // Start profile _, cmdErr := client.StartProfiling(madmin.ProfilerType(profilerType)) fatalIf(probe.NewError(cmdErr), "Unable to start profile.") console.Infoln("Profile data successfully started.") return nil }
go
func mainAdminProfileStart(ctx *cli.Context) error { // Check for command syntax checkAdminProfileStartSyntax(ctx) // Get the alias parameter from cli args := ctx.Args() aliasedURL := args.Get(0) profilerType := ctx.String("type") // Create a new MinIO Admin Client client, err := newAdminClient(aliasedURL) if err != nil { fatalIf(err.Trace(aliasedURL), "Cannot initialize admin client.") return nil } // Start profile _, cmdErr := client.StartProfiling(madmin.ProfilerType(profilerType)) fatalIf(probe.NewError(cmdErr), "Unable to start profile.") console.Infoln("Profile data successfully started.") return nil }
[ "func", "mainAdminProfileStart", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// Check for command syntax", "checkAdminProfileStartSyntax", "(", "ctx", ")", "\n\n", "// Get the alias parameter from cli", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "aliasedURL", ":=", "args", ".", "Get", "(", "0", ")", "\n\n", "profilerType", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n\n", "// Create a new MinIO Admin Client", "client", ",", "err", ":=", "newAdminClient", "(", "aliasedURL", ")", "\n", "if", "err", "!=", "nil", "{", "fatalIf", "(", "err", ".", "Trace", "(", "aliasedURL", ")", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Start profile", "_", ",", "cmdErr", ":=", "client", ".", "StartProfiling", "(", "madmin", ".", "ProfilerType", "(", "profilerType", ")", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "cmdErr", ")", ",", "\"", "\"", ")", "\n\n", "console", ".", "Infoln", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// mainAdminProfileStart - the entry function of profile command
[ "mainAdminProfileStart", "-", "the", "entry", "function", "of", "profile", "command" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-profile-start.go#L88-L111
train
minio/mc
cmd/config-utils.go
trimTrailingSeparator
func trimTrailingSeparator(hostURL string) string { separator := string(newClientURL(hostURL).Separator) return strings.TrimSuffix(hostURL, separator) }
go
func trimTrailingSeparator(hostURL string) string { separator := string(newClientURL(hostURL).Separator) return strings.TrimSuffix(hostURL, separator) }
[ "func", "trimTrailingSeparator", "(", "hostURL", "string", ")", "string", "{", "separator", ":=", "string", "(", "newClientURL", "(", "hostURL", ")", ".", "Separator", ")", "\n", "return", "strings", ".", "TrimSuffix", "(", "hostURL", ",", "separator", ")", "\n", "}" ]
// trimTrailingSeparator - Remove trailing separator.
[ "trimTrailingSeparator", "-", "Remove", "trailing", "separator", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-utils.go#L45-L48
train
minio/mc
cmd/config-utils.go
isValidHostURL
func isValidHostURL(hostURL string) (ok bool) { if strings.TrimSpace(hostURL) != "" { url := newClientURL(hostURL) if url.Scheme == "https" || url.Scheme == "http" { if url.Path == "/" { ok = true } } } return ok }
go
func isValidHostURL(hostURL string) (ok bool) { if strings.TrimSpace(hostURL) != "" { url := newClientURL(hostURL) if url.Scheme == "https" || url.Scheme == "http" { if url.Path == "/" { ok = true } } } return ok }
[ "func", "isValidHostURL", "(", "hostURL", "string", ")", "(", "ok", "bool", ")", "{", "if", "strings", ".", "TrimSpace", "(", "hostURL", ")", "!=", "\"", "\"", "{", "url", ":=", "newClientURL", "(", "hostURL", ")", "\n", "if", "url", ".", "Scheme", "==", "\"", "\"", "||", "url", ".", "Scheme", "==", "\"", "\"", "{", "if", "url", ".", "Path", "==", "\"", "\"", "{", "ok", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "ok", "\n", "}" ]
// isValidHostURL - validate input host url.
[ "isValidHostURL", "-", "validate", "input", "host", "url", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-utils.go#L51-L61
train
minio/mc
cmd/config-utils.go
isValidAPI
func isValidAPI(api string) (ok bool) { switch strings.ToLower(api) { case "s3v2", "s3v4": ok = true } return ok }
go
func isValidAPI(api string) (ok bool) { switch strings.ToLower(api) { case "s3v2", "s3v4": ok = true } return ok }
[ "func", "isValidAPI", "(", "api", "string", ")", "(", "ok", "bool", ")", "{", "switch", "strings", ".", "ToLower", "(", "api", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "ok", "=", "true", "\n", "}", "\n", "return", "ok", "\n", "}" ]
// isValidAPI - Validates if API signature string of supported type.
[ "isValidAPI", "-", "Validates", "if", "API", "signature", "string", "of", "supported", "type", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-utils.go#L64-L70
train
minio/mc
cmd/config-utils.go
isValidLookup
func isValidLookup(lookup string) (ok bool) { l := strings.TrimSpace(lookup) l = strings.ToLower(lookup) for _, v := range []string{"dns", "path", "auto"} { if l == v { return true } } return false }
go
func isValidLookup(lookup string) (ok bool) { l := strings.TrimSpace(lookup) l = strings.ToLower(lookup) for _, v := range []string{"dns", "path", "auto"} { if l == v { return true } } return false }
[ "func", "isValidLookup", "(", "lookup", "string", ")", "(", "ok", "bool", ")", "{", "l", ":=", "strings", ".", "TrimSpace", "(", "lookup", ")", "\n", "l", "=", "strings", ".", "ToLower", "(", "lookup", ")", "\n", "for", "_", ",", "v", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "{", "if", "l", "==", "v", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isValidLookup - validates if bucket lookup is of valid type
[ "isValidLookup", "-", "validates", "if", "bucket", "lookup", "is", "of", "valid", "type" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-utils.go#L73-L82
train
minio/mc
cmd/admin-user-remove.go
checkAdminUserRemoveSyntax
func checkAdminUserRemoveSyntax(ctx *cli.Context) { if len(ctx.Args()) != 2 { cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code } }
go
func checkAdminUserRemoveSyntax(ctx *cli.Context) { if len(ctx.Args()) != 2 { cli.ShowCommandHelpAndExit(ctx, "remove", 1) // last argument is exit code } }
[ "func", "checkAdminUserRemoveSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "!=", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminUserRemoveSyntax - validate all the passed arguments
[ "checkAdminUserRemoveSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-remove.go#L48-L52
train
minio/mc
cmd/admin-user-remove.go
mainAdminUserRemove
func mainAdminUserRemove(ctx *cli.Context) error { checkAdminUserRemoveSyntax(ctx) console.SetColor("UserMessage", color.New(color.FgGreen)) // Get the alias parameter from cli args := ctx.Args() aliasedURL := args.Get(0) // Create a new MinIO Admin Client client, err := newAdminClient(aliasedURL) fatalIf(err, "Cannot get a configured admin connection.") e := client.RemoveUser(args.Get(1)) fatalIf(probe.NewError(e).Trace(args...), "Cannot remove new user") printMsg(userMessage{ op: "remove", AccessKey: args.Get(1), }) return nil }
go
func mainAdminUserRemove(ctx *cli.Context) error { checkAdminUserRemoveSyntax(ctx) console.SetColor("UserMessage", color.New(color.FgGreen)) // Get the alias parameter from cli args := ctx.Args() aliasedURL := args.Get(0) // Create a new MinIO Admin Client client, err := newAdminClient(aliasedURL) fatalIf(err, "Cannot get a configured admin connection.") e := client.RemoveUser(args.Get(1)) fatalIf(probe.NewError(e).Trace(args...), "Cannot remove new user") printMsg(userMessage{ op: "remove", AccessKey: args.Get(1), }) return nil }
[ "func", "mainAdminUserRemove", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "checkAdminUserRemoveSyntax", "(", "ctx", ")", "\n\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ")", ")", "\n\n", "// Get the alias parameter from cli", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "aliasedURL", ":=", "args", ".", "Get", "(", "0", ")", "\n\n", "// Create a new MinIO Admin Client", "client", ",", "err", ":=", "newAdminClient", "(", "aliasedURL", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "e", ":=", "client", ".", "RemoveUser", "(", "args", ".", "Get", "(", "1", ")", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "args", "...", ")", ",", "\"", "\"", ")", "\n\n", "printMsg", "(", "userMessage", "{", "op", ":", "\"", "\"", ",", "AccessKey", ":", "args", ".", "Get", "(", "1", ")", ",", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// mainAdminUserRemove is the handle for "mc admin user remove" command.
[ "mainAdminUserRemove", "is", "the", "handle", "for", "mc", "admin", "user", "remove", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-remove.go#L55-L77
train
minio/mc
cmd/admin-user-list.go
checkAdminUserListSyntax
func checkAdminUserListSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code } }
go
func checkAdminUserListSyntax(ctx *cli.Context) { if len(ctx.Args()) != 1 { cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code } }
[ "func", "checkAdminUserListSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "!=", "1", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminUserListSyntax - validate all the passed arguments
[ "checkAdminUserListSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-list.go#L48-L52
train
minio/mc
cmd/admin-user-list.go
mainAdminUserList
func mainAdminUserList(ctx *cli.Context) error { checkAdminUserListSyntax(ctx) // Additional command speific theme customization. console.SetColor("UserMessage", color.New(color.FgGreen)) console.SetColor("AccessKey", color.New(color.FgBlue)) console.SetColor("PolicyName", color.New(color.FgYellow)) console.SetColor("UserStatus", color.New(color.FgCyan)) // 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.") users, e := client.ListUsers() fatalIf(probe.NewError(e).Trace(args...), "Cannot list user") for k, v := range users { printMsg(userMessage{ op: "list", AccessKey: k, PolicyName: v.PolicyName, UserStatus: string(v.Status), }) } return nil }
go
func mainAdminUserList(ctx *cli.Context) error { checkAdminUserListSyntax(ctx) // Additional command speific theme customization. console.SetColor("UserMessage", color.New(color.FgGreen)) console.SetColor("AccessKey", color.New(color.FgBlue)) console.SetColor("PolicyName", color.New(color.FgYellow)) console.SetColor("UserStatus", color.New(color.FgCyan)) // 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.") users, e := client.ListUsers() fatalIf(probe.NewError(e).Trace(args...), "Cannot list user") for k, v := range users { printMsg(userMessage{ op: "list", AccessKey: k, PolicyName: v.PolicyName, UserStatus: string(v.Status), }) } return nil }
[ "func", "mainAdminUserList", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "checkAdminUserListSyntax", "(", "ctx", ")", "\n\n", "// Additional command speific theme customization.", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgBlue", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgYellow", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgCyan", ")", ")", "\n\n", "// Get the alias parameter from cli", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "aliasedURL", ":=", "args", ".", "Get", "(", "0", ")", "\n\n", "// Create a new MinIO Admin Client", "client", ",", "err", ":=", "newAdminClient", "(", "aliasedURL", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "users", ",", "e", ":=", "client", ".", "ListUsers", "(", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "args", "...", ")", ",", "\"", "\"", ")", "\n\n", "for", "k", ",", "v", ":=", "range", "users", "{", "printMsg", "(", "userMessage", "{", "op", ":", "\"", "\"", ",", "AccessKey", ":", "k", ",", "PolicyName", ":", "v", ".", "PolicyName", ",", "UserStatus", ":", "string", "(", "v", ".", "Status", ")", ",", "}", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mainAdminUserList is the handle for "mc admin user list" command.
[ "mainAdminUserList", "is", "the", "handle", "for", "mc", "admin", "user", "list", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-list.go#L55-L84
train
minio/mc
cmd/share-download-main.go
checkShareDownloadSyntax
func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { args := ctx.Args() if !args.Present() { cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code. } // Parse expiry. expiry := shareDefaultExpiry expireArg := ctx.String("expire") if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } // Validate expiry. if expiry.Seconds() < 1 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.") } if expiry.Seconds() > 604800 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") } // Validate if object exists only if the `--recursive` flag was NOT specified isRecursive := ctx.Bool("recursive") if !isRecursive { for _, url := range ctx.Args() { _, _, err := url2Stat(url, false, encKeyDB) if err != nil { fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") } } } }
go
func checkShareDownloadSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) { args := ctx.Args() if !args.Present() { cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code. } // Parse expiry. expiry := shareDefaultExpiry expireArg := ctx.String("expire") if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } // Validate expiry. if expiry.Seconds() < 1 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.") } if expiry.Seconds() > 604800 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") } // Validate if object exists only if the `--recursive` flag was NOT specified isRecursive := ctx.Bool("recursive") if !isRecursive { for _, url := range ctx.Args() { _, _, err := url2Stat(url, false, encKeyDB) if err != nil { fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") } } } }
[ "func", "checkShareDownloadSyntax", "(", "ctx", "*", "cli", ".", "Context", ",", "encKeyDB", "map", "[", "string", "]", "[", "]", "prefixSSEPair", ")", "{", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "if", "!", "args", ".", "Present", "(", ")", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code.", "\n", "}", "\n\n", "// Parse expiry.", "expiry", ":=", "shareDefaultExpiry", "\n", "expireArg", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "if", "expireArg", "!=", "\"", "\"", "{", "var", "e", "error", "\n", "expiry", ",", "e", "=", "time", ".", "ParseDuration", "(", "expireArg", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", "+", "expireArg", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate expiry.", "if", "expiry", ".", "Seconds", "(", ")", "<", "1", "{", "fatalIf", "(", "errDummy", "(", ")", ".", "Trace", "(", "expiry", ".", "String", "(", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "expiry", ".", "Seconds", "(", ")", ">", "604800", "{", "fatalIf", "(", "errDummy", "(", ")", ".", "Trace", "(", "expiry", ".", "String", "(", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate if object exists only if the `--recursive` flag was NOT specified", "isRecursive", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "if", "!", "isRecursive", "{", "for", "_", ",", "url", ":=", "range", "ctx", ".", "Args", "(", ")", "{", "_", ",", "_", ",", "err", ":=", "url2Stat", "(", "url", ",", "false", ",", "encKeyDB", ")", "\n", "if", "err", "!=", "nil", "{", "fatalIf", "(", "err", ".", "Trace", "(", "url", ")", ",", "\"", "\"", "+", "url", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// checkShareDownloadSyntax - validate command-line args.
[ "checkShareDownloadSyntax", "-", "validate", "command", "-", "line", "args", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-download-main.go#L70-L103
train
minio/mc
cmd/share-download-main.go
doShareDownloadURL
func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error { targetAlias, targetURLFull, _, err := expandAlias(targetURL) if err != nil { return err.Trace(targetURL) } clnt, err := newClientFromAlias(targetAlias, targetURLFull) if err != nil { return err.Trace(targetURL) } // Load previously saved upload-shares. Add new entries and write it back. shareDB := newShareDBV1() shareDownloadsFile := getShareDownloadsFile() err = shareDB.Load(shareDownloadsFile) if err != nil { return err.Trace(shareDownloadsFile) } // Generate share URL for each target. isIncomplete := false isFetchMeta := false // Channel which will receive objects whose URLs need to be shared objectsCh := make(chan *clientContent) content, err := clnt.Stat(isIncomplete, isFetchMeta, nil) if err != nil { return err.Trace(clnt.GetURL().String()) } if !content.Type.IsDir() { go func() { defer close(objectsCh) objectsCh <- content }() } else { if !strings.HasSuffix(targetURLFull, string(clnt.GetURL().Separator)) { targetURLFull = targetURLFull + string(clnt.GetURL().Separator) } clnt, err = newClientFromAlias(targetAlias, targetURLFull) if err != nil { return err.Trace(targetURLFull) } // Recursive mode: Share list of objects go func() { defer close(objectsCh) for content := range clnt.List(isRecursive, isIncomplete, DirNone) { objectsCh <- content } }() } // Iterate over all objects to generate share URL for content := range objectsCh { if content.Err != nil { return content.Err.Trace(clnt.GetURL().String()) } // if any incoming directories, we don't need to calculate. if content.Type.IsDir() { continue } objectURL := content.URL.String() newClnt, err := newClientFromAlias(targetAlias, objectURL) if err != nil { return err.Trace(objectURL) } // Generate share URL. shareURL, err := newClnt.ShareDownload(expiry) if err != nil { // add objectURL and expiry as part of the trace arguments. return err.Trace(objectURL, "expiry="+expiry.String()) } // Make new entries to shareDB. contentType := "" // Not useful for download shares. shareDB.Set(objectURL, shareURL, expiry, contentType) printMsg(shareMesssage{ ObjectURL: objectURL, ShareURL: shareURL, TimeLeft: expiry, ContentType: contentType, }) } // Save downloads and return. return shareDB.Save(shareDownloadsFile) }
go
func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration) *probe.Error { targetAlias, targetURLFull, _, err := expandAlias(targetURL) if err != nil { return err.Trace(targetURL) } clnt, err := newClientFromAlias(targetAlias, targetURLFull) if err != nil { return err.Trace(targetURL) } // Load previously saved upload-shares. Add new entries and write it back. shareDB := newShareDBV1() shareDownloadsFile := getShareDownloadsFile() err = shareDB.Load(shareDownloadsFile) if err != nil { return err.Trace(shareDownloadsFile) } // Generate share URL for each target. isIncomplete := false isFetchMeta := false // Channel which will receive objects whose URLs need to be shared objectsCh := make(chan *clientContent) content, err := clnt.Stat(isIncomplete, isFetchMeta, nil) if err != nil { return err.Trace(clnt.GetURL().String()) } if !content.Type.IsDir() { go func() { defer close(objectsCh) objectsCh <- content }() } else { if !strings.HasSuffix(targetURLFull, string(clnt.GetURL().Separator)) { targetURLFull = targetURLFull + string(clnt.GetURL().Separator) } clnt, err = newClientFromAlias(targetAlias, targetURLFull) if err != nil { return err.Trace(targetURLFull) } // Recursive mode: Share list of objects go func() { defer close(objectsCh) for content := range clnt.List(isRecursive, isIncomplete, DirNone) { objectsCh <- content } }() } // Iterate over all objects to generate share URL for content := range objectsCh { if content.Err != nil { return content.Err.Trace(clnt.GetURL().String()) } // if any incoming directories, we don't need to calculate. if content.Type.IsDir() { continue } objectURL := content.URL.String() newClnt, err := newClientFromAlias(targetAlias, objectURL) if err != nil { return err.Trace(objectURL) } // Generate share URL. shareURL, err := newClnt.ShareDownload(expiry) if err != nil { // add objectURL and expiry as part of the trace arguments. return err.Trace(objectURL, "expiry="+expiry.String()) } // Make new entries to shareDB. contentType := "" // Not useful for download shares. shareDB.Set(objectURL, shareURL, expiry, contentType) printMsg(shareMesssage{ ObjectURL: objectURL, ShareURL: shareURL, TimeLeft: expiry, ContentType: contentType, }) } // Save downloads and return. return shareDB.Save(shareDownloadsFile) }
[ "func", "doShareDownloadURL", "(", "targetURL", "string", ",", "isRecursive", "bool", ",", "expiry", "time", ".", "Duration", ")", "*", "probe", ".", "Error", "{", "targetAlias", ",", "targetURLFull", ",", "_", ",", "err", ":=", "expandAlias", "(", "targetURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n", "clnt", ",", "err", ":=", "newClientFromAlias", "(", "targetAlias", ",", "targetURLFull", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "targetURL", ")", "\n", "}", "\n\n", "// Load previously saved upload-shares. Add new entries and write it back.", "shareDB", ":=", "newShareDBV1", "(", ")", "\n", "shareDownloadsFile", ":=", "getShareDownloadsFile", "(", ")", "\n", "err", "=", "shareDB", ".", "Load", "(", "shareDownloadsFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "shareDownloadsFile", ")", "\n", "}", "\n\n", "// Generate share URL for each target.", "isIncomplete", ":=", "false", "\n", "isFetchMeta", ":=", "false", "\n", "// Channel which will receive objects whose URLs need to be shared", "objectsCh", ":=", "make", "(", "chan", "*", "clientContent", ")", "\n\n", "content", ",", "err", ":=", "clnt", ".", "Stat", "(", "isIncomplete", ",", "isFetchMeta", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "clnt", ".", "GetURL", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "if", "!", "content", ".", "Type", ".", "IsDir", "(", ")", "{", "go", "func", "(", ")", "{", "defer", "close", "(", "objectsCh", ")", "\n", "objectsCh", "<-", "content", "\n", "}", "(", ")", "\n", "}", "else", "{", "if", "!", "strings", ".", "HasSuffix", "(", "targetURLFull", ",", "string", "(", "clnt", ".", "GetURL", "(", ")", ".", "Separator", ")", ")", "{", "targetURLFull", "=", "targetURLFull", "+", "string", "(", "clnt", ".", "GetURL", "(", ")", ".", "Separator", ")", "\n", "}", "\n", "clnt", ",", "err", "=", "newClientFromAlias", "(", "targetAlias", ",", "targetURLFull", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "targetURLFull", ")", "\n", "}", "\n", "// Recursive mode: Share list of objects", "go", "func", "(", ")", "{", "defer", "close", "(", "objectsCh", ")", "\n", "for", "content", ":=", "range", "clnt", ".", "List", "(", "isRecursive", ",", "isIncomplete", ",", "DirNone", ")", "{", "objectsCh", "<-", "content", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n\n", "// Iterate over all objects to generate share URL", "for", "content", ":=", "range", "objectsCh", "{", "if", "content", ".", "Err", "!=", "nil", "{", "return", "content", ".", "Err", ".", "Trace", "(", "clnt", ".", "GetURL", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "// if any incoming directories, we don't need to calculate.", "if", "content", ".", "Type", ".", "IsDir", "(", ")", "{", "continue", "\n", "}", "\n", "objectURL", ":=", "content", ".", "URL", ".", "String", "(", ")", "\n", "newClnt", ",", "err", ":=", "newClientFromAlias", "(", "targetAlias", ",", "objectURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "objectURL", ")", "\n", "}", "\n\n", "// Generate share URL.", "shareURL", ",", "err", ":=", "newClnt", ".", "ShareDownload", "(", "expiry", ")", "\n", "if", "err", "!=", "nil", "{", "// add objectURL and expiry as part of the trace arguments.", "return", "err", ".", "Trace", "(", "objectURL", ",", "\"", "\"", "+", "expiry", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "// Make new entries to shareDB.", "contentType", ":=", "\"", "\"", "// Not useful for download shares.", "\n", "shareDB", ".", "Set", "(", "objectURL", ",", "shareURL", ",", "expiry", ",", "contentType", ")", "\n", "printMsg", "(", "shareMesssage", "{", "ObjectURL", ":", "objectURL", ",", "ShareURL", ":", "shareURL", ",", "TimeLeft", ":", "expiry", ",", "ContentType", ":", "contentType", ",", "}", ")", "\n", "}", "\n\n", "// Save downloads and return.", "return", "shareDB", ".", "Save", "(", "shareDownloadsFile", ")", "\n", "}" ]
// doShareURL share files from target.
[ "doShareURL", "share", "files", "from", "target", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-download-main.go#L106-L192
train
minio/mc
cmd/share-download-main.go
mainShareDownload
func mainShareDownload(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // check input arguments. checkShareDownloadSyntax(ctx, encKeyDB) // Initialize share config folder. initShareConfig() // Additional command speific theme customization. shareSetColor() // Set command flags from context. isRecursive := ctx.Bool("recursive") expiry := shareDefaultExpiry if ctx.String("expire") != "" { var e error expiry, e = time.ParseDuration(ctx.String("expire")) fatalIf(probe.NewError(e), "Unable to parse expire=`"+ctx.String("expire")+"`.") } for _, targetURL := range ctx.Args() { err := doShareDownloadURL(targetURL, isRecursive, expiry) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to share a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to share target `"+targetURL+"`.") } } } return nil }
go
func mainShareDownload(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // check input arguments. checkShareDownloadSyntax(ctx, encKeyDB) // Initialize share config folder. initShareConfig() // Additional command speific theme customization. shareSetColor() // Set command flags from context. isRecursive := ctx.Bool("recursive") expiry := shareDefaultExpiry if ctx.String("expire") != "" { var e error expiry, e = time.ParseDuration(ctx.String("expire")) fatalIf(probe.NewError(e), "Unable to parse expire=`"+ctx.String("expire")+"`.") } for _, targetURL := range ctx.Args() { err := doShareDownloadURL(targetURL, isRecursive, expiry) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to share a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to share target `"+targetURL+"`.") } } } return nil }
[ "func", "mainShareDownload", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// Parse encryption keys per command.", "encKeyDB", ",", "err", ":=", "getEncKeys", "(", "ctx", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "// check input arguments.", "checkShareDownloadSyntax", "(", "ctx", ",", "encKeyDB", ")", "\n\n", "// Initialize share config folder.", "initShareConfig", "(", ")", "\n\n", "// Additional command speific theme customization.", "shareSetColor", "(", ")", "\n\n", "// Set command flags from context.", "isRecursive", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "expiry", ":=", "shareDefaultExpiry", "\n", "if", "ctx", ".", "String", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "var", "e", "error", "\n", "expiry", ",", "e", "=", "time", ".", "ParseDuration", "(", "ctx", ".", "String", "(", "\"", "\"", ")", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", "+", "ctx", ".", "String", "(", "\"", "\"", ")", "+", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "targetURL", ":=", "range", "ctx", ".", "Args", "(", ")", "{", "err", ":=", "doShareDownloadURL", "(", "targetURL", ",", "isRecursive", ",", "expiry", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "ToGoError", "(", ")", ".", "(", "type", ")", "{", "case", "APINotImplemented", ":", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "default", ":", "fatalIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// main for share download.
[ "main", "for", "share", "download", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-download-main.go#L195-L230
train
minio/mc
cmd/share-upload-main.go
checkShareUploadSyntax
func checkShareUploadSyntax(ctx *cli.Context) { args := ctx.Args() if !args.Present() { cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code. } // Set command flags from context. isRecursive := ctx.Bool("recursive") expireArg := ctx.String("expire") // Parse expiry. expiry := shareDefaultExpiry if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } // Validate expiry. if expiry.Seconds() < 1 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.") } if expiry.Seconds() > 604800 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") } for _, targetURL := range ctx.Args() { url := newClientURL(targetURL) if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive { fatalIf(errInvalidArgument().Trace(targetURL), "Use --recursive flag to generate curl command for prefixes.") } } }
go
func checkShareUploadSyntax(ctx *cli.Context) { args := ctx.Args() if !args.Present() { cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code. } // Set command flags from context. isRecursive := ctx.Bool("recursive") expireArg := ctx.String("expire") // Parse expiry. expiry := shareDefaultExpiry if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } // Validate expiry. if expiry.Seconds() < 1 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.") } if expiry.Seconds() > 604800 { fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") } for _, targetURL := range ctx.Args() { url := newClientURL(targetURL) if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive { fatalIf(errInvalidArgument().Trace(targetURL), "Use --recursive flag to generate curl command for prefixes.") } } }
[ "func", "checkShareUploadSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "if", "!", "args", ".", "Present", "(", ")", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code.", "\n", "}", "\n\n", "// Set command flags from context.", "isRecursive", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "expireArg", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n\n", "// Parse expiry.", "expiry", ":=", "shareDefaultExpiry", "\n", "if", "expireArg", "!=", "\"", "\"", "{", "var", "e", "error", "\n", "expiry", ",", "e", "=", "time", ".", "ParseDuration", "(", "expireArg", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", "+", "expireArg", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate expiry.", "if", "expiry", ".", "Seconds", "(", ")", "<", "1", "{", "fatalIf", "(", "errDummy", "(", ")", ".", "Trace", "(", "expiry", ".", "String", "(", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "expiry", ".", "Seconds", "(", ")", ">", "604800", "{", "fatalIf", "(", "errDummy", "(", ")", ".", "Trace", "(", "expiry", ".", "String", "(", ")", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "targetURL", ":=", "range", "ctx", ".", "Args", "(", ")", "{", "url", ":=", "newClientURL", "(", "targetURL", ")", "\n", "if", "strings", ".", "HasSuffix", "(", "targetURL", ",", "string", "(", "url", ".", "Separator", ")", ")", "&&", "!", "isRecursive", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// checkShareUploadSyntax - validate command-line args.
[ "checkShareUploadSyntax", "-", "validate", "command", "-", "line", "args", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-upload-main.go#L72-L107
train
minio/mc
cmd/share-upload-main.go
makeCurlCmd
func makeCurlCmd(key, postURL string, isRecursive bool, uploadInfo map[string]string) (string, *probe.Error) { postURL += " " curlCommand := "curl " + postURL for k, v := range uploadInfo { if k == "key" { key = v continue } curlCommand += fmt.Sprintf("-F %s=%s ", k, v) } // If key starts with is enabled prefix it with the output. if isRecursive { curlCommand += fmt.Sprintf("-F key=%s<NAME> ", key) // Object name. } else { curlCommand += fmt.Sprintf("-F key=%s ", key) // Object name. } curlCommand += "-F file=@<FILE>" // File to upload. return curlCommand, nil }
go
func makeCurlCmd(key, postURL string, isRecursive bool, uploadInfo map[string]string) (string, *probe.Error) { postURL += " " curlCommand := "curl " + postURL for k, v := range uploadInfo { if k == "key" { key = v continue } curlCommand += fmt.Sprintf("-F %s=%s ", k, v) } // If key starts with is enabled prefix it with the output. if isRecursive { curlCommand += fmt.Sprintf("-F key=%s<NAME> ", key) // Object name. } else { curlCommand += fmt.Sprintf("-F key=%s ", key) // Object name. } curlCommand += "-F file=@<FILE>" // File to upload. return curlCommand, nil }
[ "func", "makeCurlCmd", "(", "key", ",", "postURL", "string", ",", "isRecursive", "bool", ",", "uploadInfo", "map", "[", "string", "]", "string", ")", "(", "string", ",", "*", "probe", ".", "Error", ")", "{", "postURL", "+=", "\"", "\"", "\n", "curlCommand", ":=", "\"", "\"", "+", "postURL", "\n", "for", "k", ",", "v", ":=", "range", "uploadInfo", "{", "if", "k", "==", "\"", "\"", "{", "key", "=", "v", "\n", "continue", "\n", "}", "\n", "curlCommand", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "// If key starts with is enabled prefix it with the output.", "if", "isRecursive", "{", "curlCommand", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ")", "// Object name.", "\n", "}", "else", "{", "curlCommand", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ")", "// Object name.", "\n", "}", "\n", "curlCommand", "+=", "\"", "\"", "// File to upload.", "\n", "return", "curlCommand", ",", "nil", "\n", "}" ]
// makeCurlCmd constructs curl command-line.
[ "makeCurlCmd", "constructs", "curl", "command", "-", "line", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-upload-main.go#L110-L128
train
minio/mc
cmd/share-upload-main.go
saveSharedURL
func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, contentType string) *probe.Error { // Load previously saved upload-shares. shareDB := newShareDBV1() if err := shareDB.Load(getShareUploadsFile()); err != nil { return err.Trace(getShareUploadsFile()) } // Make new entries to uploadsDB. shareDB.Set(objectURL, shareURL, expiry, contentType) shareDB.Save(getShareUploadsFile()) return nil }
go
func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, contentType string) *probe.Error { // Load previously saved upload-shares. shareDB := newShareDBV1() if err := shareDB.Load(getShareUploadsFile()); err != nil { return err.Trace(getShareUploadsFile()) } // Make new entries to uploadsDB. shareDB.Set(objectURL, shareURL, expiry, contentType) shareDB.Save(getShareUploadsFile()) return nil }
[ "func", "saveSharedURL", "(", "objectURL", "string", ",", "shareURL", "string", ",", "expiry", "time", ".", "Duration", ",", "contentType", "string", ")", "*", "probe", ".", "Error", "{", "// Load previously saved upload-shares.", "shareDB", ":=", "newShareDBV1", "(", ")", "\n", "if", "err", ":=", "shareDB", ".", "Load", "(", "getShareUploadsFile", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "getShareUploadsFile", "(", ")", ")", "\n", "}", "\n\n", "// Make new entries to uploadsDB.", "shareDB", ".", "Set", "(", "objectURL", ",", "shareURL", ",", "expiry", ",", "contentType", ")", "\n", "shareDB", ".", "Save", "(", "getShareUploadsFile", "(", ")", ")", "\n\n", "return", "nil", "\n", "}" ]
// save shared URL to disk.
[ "save", "shared", "URL", "to", "disk", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-upload-main.go#L131-L143
train
minio/mc
cmd/share-upload-main.go
doShareUploadURL
func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error { clnt, err := newClient(objectURL) if err != nil { return err.Trace(objectURL) } // Generate pre-signed access info. shareURL, uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType) if err != nil { return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType) } // Get the new expanded url. objectURL = clnt.GetURL().String() // Generate curl command. curlCmd, err := makeCurlCmd(objectURL, shareURL, isRecursive, uploadInfo) if err != nil { return err.Trace(objectURL) } printMsg(shareMesssage{ ObjectURL: objectURL, ShareURL: curlCmd, TimeLeft: expiry, ContentType: contentType, }) // save shared URL to disk. return saveSharedURL(objectURL, curlCmd, expiry, contentType) }
go
func doShareUploadURL(objectURL string, isRecursive bool, expiry time.Duration, contentType string) *probe.Error { clnt, err := newClient(objectURL) if err != nil { return err.Trace(objectURL) } // Generate pre-signed access info. shareURL, uploadInfo, err := clnt.ShareUpload(isRecursive, expiry, contentType) if err != nil { return err.Trace(objectURL, "expiry="+expiry.String(), "contentType="+contentType) } // Get the new expanded url. objectURL = clnt.GetURL().String() // Generate curl command. curlCmd, err := makeCurlCmd(objectURL, shareURL, isRecursive, uploadInfo) if err != nil { return err.Trace(objectURL) } printMsg(shareMesssage{ ObjectURL: objectURL, ShareURL: curlCmd, TimeLeft: expiry, ContentType: contentType, }) // save shared URL to disk. return saveSharedURL(objectURL, curlCmd, expiry, contentType) }
[ "func", "doShareUploadURL", "(", "objectURL", "string", ",", "isRecursive", "bool", ",", "expiry", "time", ".", "Duration", ",", "contentType", "string", ")", "*", "probe", ".", "Error", "{", "clnt", ",", "err", ":=", "newClient", "(", "objectURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "objectURL", ")", "\n", "}", "\n\n", "// Generate pre-signed access info.", "shareURL", ",", "uploadInfo", ",", "err", ":=", "clnt", ".", "ShareUpload", "(", "isRecursive", ",", "expiry", ",", "contentType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "objectURL", ",", "\"", "\"", "+", "expiry", ".", "String", "(", ")", ",", "\"", "\"", "+", "contentType", ")", "\n", "}", "\n\n", "// Get the new expanded url.", "objectURL", "=", "clnt", ".", "GetURL", "(", ")", ".", "String", "(", ")", "\n\n", "// Generate curl command.", "curlCmd", ",", "err", ":=", "makeCurlCmd", "(", "objectURL", ",", "shareURL", ",", "isRecursive", ",", "uploadInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "objectURL", ")", "\n", "}", "\n\n", "printMsg", "(", "shareMesssage", "{", "ObjectURL", ":", "objectURL", ",", "ShareURL", ":", "curlCmd", ",", "TimeLeft", ":", "expiry", ",", "ContentType", ":", "contentType", ",", "}", ")", "\n\n", "// save shared URL to disk.", "return", "saveSharedURL", "(", "objectURL", ",", "curlCmd", ",", "expiry", ",", "contentType", ")", "\n", "}" ]
// doShareUploadURL uploads files to the target.
[ "doShareUploadURL", "uploads", "files", "to", "the", "target", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-upload-main.go#L146-L176
train
minio/mc
cmd/share-upload-main.go
mainShareUpload
func mainShareUpload(ctx *cli.Context) error { // check input arguments. checkShareUploadSyntax(ctx) // Initialize share config folder. initShareConfig() // Additional command speific theme customization. shareSetColor() // Set command flags from context. isRecursive := ctx.Bool("recursive") expireArg := ctx.String("expire") expiry := shareDefaultExpiry contentType := ctx.String("content-type") if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } for _, targetURL := range ctx.Args() { err := doShareUploadURL(targetURL, isRecursive, expiry, contentType) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to share a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload `"+targetURL+"`.") } } } return nil }
go
func mainShareUpload(ctx *cli.Context) error { // check input arguments. checkShareUploadSyntax(ctx) // Initialize share config folder. initShareConfig() // Additional command speific theme customization. shareSetColor() // Set command flags from context. isRecursive := ctx.Bool("recursive") expireArg := ctx.String("expire") expiry := shareDefaultExpiry contentType := ctx.String("content-type") if expireArg != "" { var e error expiry, e = time.ParseDuration(expireArg) fatalIf(probe.NewError(e), "Unable to parse expire=`"+expireArg+"`.") } for _, targetURL := range ctx.Args() { err := doShareUploadURL(targetURL, isRecursive, expiry, contentType) if err != nil { switch err.ToGoError().(type) { case APINotImplemented: fatalIf(err.Trace(), "Unable to share a non S3 url `"+targetURL+"`.") default: fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload `"+targetURL+"`.") } } } return nil }
[ "func", "mainShareUpload", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// check input arguments.", "checkShareUploadSyntax", "(", "ctx", ")", "\n\n", "// Initialize share config folder.", "initShareConfig", "(", ")", "\n\n", "// Additional command speific theme customization.", "shareSetColor", "(", ")", "\n\n", "// Set command flags from context.", "isRecursive", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "expireArg", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "expiry", ":=", "shareDefaultExpiry", "\n", "contentType", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "if", "expireArg", "!=", "\"", "\"", "{", "var", "e", "error", "\n", "expiry", ",", "e", "=", "time", ".", "ParseDuration", "(", "expireArg", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", "+", "expireArg", "+", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "targetURL", ":=", "range", "ctx", ".", "Args", "(", ")", "{", "err", ":=", "doShareUploadURL", "(", "targetURL", ",", "isRecursive", ",", "expiry", ",", "contentType", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", ".", "ToGoError", "(", ")", ".", "(", "type", ")", "{", "case", "APINotImplemented", ":", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "default", ":", "fatalIf", "(", "err", ".", "Trace", "(", "targetURL", ")", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// main for share upload command.
[ "main", "for", "share", "upload", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share-upload-main.go#L179-L213
train
minio/mc
cmd/event-add.go
checkEventAddSyntax
func checkEventAddSyntax(ctx *cli.Context) { if len(ctx.Args()) != 2 { cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code } }
go
func checkEventAddSyntax(ctx *cli.Context) { if len(ctx.Args()) != 2 { cli.ShowCommandHelpAndExit(ctx, "add", 1) // last argument is exit code } }
[ "func", "checkEventAddSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "!=", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkEventAddSyntax - validate all the passed arguments
[ "checkEventAddSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/event-add.go#L73-L77
train
minio/mc
cmd/event-add.go
JSON
func (u eventAddMessage) JSON() string { u.Status = "success" eventAddMessageJSONBytes, e := json.MarshalIndent(u, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(eventAddMessageJSONBytes) }
go
func (u eventAddMessage) JSON() string { u.Status = "success" eventAddMessageJSONBytes, e := json.MarshalIndent(u, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(eventAddMessageJSONBytes) }
[ "func", "(", "u", "eventAddMessage", ")", "JSON", "(", ")", "string", "{", "u", ".", "Status", "=", "\"", "\"", "\n", "eventAddMessageJSONBytes", ",", "e", ":=", "json", ".", "MarshalIndent", "(", "u", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n", "return", "string", "(", "eventAddMessageJSONBytes", ")", "\n", "}" ]
// JSON jsonified update message.
[ "JSON", "jsonified", "update", "message", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/event-add.go#L89-L94
train
minio/mc
cmd/admin-service-stop.go
checkAdminServiceStopSyntax
func checkAdminServiceStopSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code } }
go
func checkAdminServiceStopSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code } }
[ "func", "checkAdminServiceStopSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminServiceStopSyntax - validate all the passed arguments
[ "checkAdminServiceStopSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-service-stop.go#L70-L74
train
minio/mc
cmd/config-validate.go
validateConfigVersion
func validateConfigVersion(config *configV9) (bool, string) { if config.Version != globalMCConfigVersion { return false, fmt.Sprintf("Config version '%s' does not match mc config version '%s', please update your binary.\n", config.Version, globalMCConfigVersion) } return true, "" }
go
func validateConfigVersion(config *configV9) (bool, string) { if config.Version != globalMCConfigVersion { return false, fmt.Sprintf("Config version '%s' does not match mc config version '%s', please update your binary.\n", config.Version, globalMCConfigVersion) } return true, "" }
[ "func", "validateConfigVersion", "(", "config", "*", "configV9", ")", "(", "bool", ",", "string", ")", "{", "if", "config", ".", "Version", "!=", "globalMCConfigVersion", "{", "return", "false", ",", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "config", ".", "Version", ",", "globalMCConfigVersion", ")", "\n", "}", "\n", "return", "true", ",", "\"", "\"", "\n", "}" ]
// Check if version of the config is valid
[ "Check", "if", "version", "of", "the", "config", "is", "valid" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-validate.go#L25-L31
train
minio/mc
cmd/config-validate.go
validateConfigFile
func validateConfigFile(config *configV9) (bool, []string) { ok, err := validateConfigVersion(config) var validationSuccessful = true var errors []string if !ok { validationSuccessful = false errors = append(errors, err) } hosts := config.Hosts for _, hostConfig := range hosts { hostConfigHealthOk, hostErrors := validateConfigHost(hostConfig) if !hostConfigHealthOk { validationSuccessful = false errors = append(errors, hostErrors...) } } return validationSuccessful, errors }
go
func validateConfigFile(config *configV9) (bool, []string) { ok, err := validateConfigVersion(config) var validationSuccessful = true var errors []string if !ok { validationSuccessful = false errors = append(errors, err) } hosts := config.Hosts for _, hostConfig := range hosts { hostConfigHealthOk, hostErrors := validateConfigHost(hostConfig) if !hostConfigHealthOk { validationSuccessful = false errors = append(errors, hostErrors...) } } return validationSuccessful, errors }
[ "func", "validateConfigFile", "(", "config", "*", "configV9", ")", "(", "bool", ",", "[", "]", "string", ")", "{", "ok", ",", "err", ":=", "validateConfigVersion", "(", "config", ")", "\n", "var", "validationSuccessful", "=", "true", "\n", "var", "errors", "[", "]", "string", "\n", "if", "!", "ok", "{", "validationSuccessful", "=", "false", "\n", "errors", "=", "append", "(", "errors", ",", "err", ")", "\n", "}", "\n", "hosts", ":=", "config", ".", "Hosts", "\n", "for", "_", ",", "hostConfig", ":=", "range", "hosts", "{", "hostConfigHealthOk", ",", "hostErrors", ":=", "validateConfigHost", "(", "hostConfig", ")", "\n", "if", "!", "hostConfigHealthOk", "{", "validationSuccessful", "=", "false", "\n", "errors", "=", "append", "(", "errors", ",", "hostErrors", "...", ")", "\n", "}", "\n", "}", "\n", "return", "validationSuccessful", ",", "errors", "\n", "}" ]
// Verifies the config file of the MinIO Client
[ "Verifies", "the", "config", "file", "of", "the", "MinIO", "Client" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/config-validate.go#L34-L51
train
minio/mc
cmd/main.go
Main
func Main() { if len(os.Args) > 1 { switch os.Args[1] { case "mc", "-install", "-uninstall": mainComplete() return } } // Enable profiling supported modes are [cpu, mem, block]. // ``MC_PROFILER`` supported options are [cpu, mem, block]. switch os.Getenv("MC_PROFILER") { case "cpu": defer profile.Start(profile.CPUProfile, profile.ProfilePath(mustGetProfileDir())).Stop() case "mem": defer profile.Start(profile.MemProfile, profile.ProfilePath(mustGetProfileDir())).Stop() case "block": defer profile.Start(profile.BlockProfile, profile.ProfilePath(mustGetProfileDir())).Stop() } probe.Init() // Set project's root source path. probe.SetAppInfo("Release-Tag", ReleaseTag) probe.SetAppInfo("Commit", ShortCommitID) // Fetch terminal size, if not available, automatically // set globalQuiet to true. if w, e := pb.GetTerminalWidth(); e != nil { globalQuiet = true } else { globalTermWidth = w } app := registerApp() app.Before = registerBefore app.ExtraInfo = func() map[string]string { if globalDebug { return getSystemData() } return make(map[string]string) } app.RunAndExitOnError() }
go
func Main() { if len(os.Args) > 1 { switch os.Args[1] { case "mc", "-install", "-uninstall": mainComplete() return } } // Enable profiling supported modes are [cpu, mem, block]. // ``MC_PROFILER`` supported options are [cpu, mem, block]. switch os.Getenv("MC_PROFILER") { case "cpu": defer profile.Start(profile.CPUProfile, profile.ProfilePath(mustGetProfileDir())).Stop() case "mem": defer profile.Start(profile.MemProfile, profile.ProfilePath(mustGetProfileDir())).Stop() case "block": defer profile.Start(profile.BlockProfile, profile.ProfilePath(mustGetProfileDir())).Stop() } probe.Init() // Set project's root source path. probe.SetAppInfo("Release-Tag", ReleaseTag) probe.SetAppInfo("Commit", ShortCommitID) // Fetch terminal size, if not available, automatically // set globalQuiet to true. if w, e := pb.GetTerminalWidth(); e != nil { globalQuiet = true } else { globalTermWidth = w } app := registerApp() app.Before = registerBefore app.ExtraInfo = func() map[string]string { if globalDebug { return getSystemData() } return make(map[string]string) } app.RunAndExitOnError() }
[ "func", "Main", "(", ")", "{", "if", "len", "(", "os", ".", "Args", ")", ">", "1", "{", "switch", "os", ".", "Args", "[", "1", "]", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "mainComplete", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// Enable profiling supported modes are [cpu, mem, block].", "// ``MC_PROFILER`` supported options are [cpu, mem, block].", "switch", "os", ".", "Getenv", "(", "\"", "\"", ")", "{", "case", "\"", "\"", ":", "defer", "profile", ".", "Start", "(", "profile", ".", "CPUProfile", ",", "profile", ".", "ProfilePath", "(", "mustGetProfileDir", "(", ")", ")", ")", ".", "Stop", "(", ")", "\n", "case", "\"", "\"", ":", "defer", "profile", ".", "Start", "(", "profile", ".", "MemProfile", ",", "profile", ".", "ProfilePath", "(", "mustGetProfileDir", "(", ")", ")", ")", ".", "Stop", "(", ")", "\n", "case", "\"", "\"", ":", "defer", "profile", ".", "Start", "(", "profile", ".", "BlockProfile", ",", "profile", ".", "ProfilePath", "(", "mustGetProfileDir", "(", ")", ")", ")", ".", "Stop", "(", ")", "\n", "}", "\n\n", "probe", ".", "Init", "(", ")", "// Set project's root source path.", "\n", "probe", ".", "SetAppInfo", "(", "\"", "\"", ",", "ReleaseTag", ")", "\n", "probe", ".", "SetAppInfo", "(", "\"", "\"", ",", "ShortCommitID", ")", "\n\n", "// Fetch terminal size, if not available, automatically", "// set globalQuiet to true.", "if", "w", ",", "e", ":=", "pb", ".", "GetTerminalWidth", "(", ")", ";", "e", "!=", "nil", "{", "globalQuiet", "=", "true", "\n", "}", "else", "{", "globalTermWidth", "=", "w", "\n", "}", "\n\n", "app", ":=", "registerApp", "(", ")", "\n", "app", ".", "Before", "=", "registerBefore", "\n", "app", ".", "ExtraInfo", "=", "func", "(", ")", "map", "[", "string", "]", "string", "{", "if", "globalDebug", "{", "return", "getSystemData", "(", ")", "\n", "}", "\n", "return", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "app", ".", "RunAndExitOnError", "(", ")", "\n", "}" ]
// Main starts mc application
[ "Main", "starts", "mc", "application" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/main.go#L66-L107
train
minio/mc
cmd/main.go
commandNotFound
func commandNotFound(ctx *cli.Context, command string) { msg := fmt.Sprintf("`%s` is not a mc command. See `mc --help`.", command) closestCommands := findClosestCommands(command) if len(closestCommands) > 0 { msg += fmt.Sprintf("\n\nDid you mean one of these?\n") if len(closestCommands) == 1 { cmd := closestCommands[0] msg += fmt.Sprintf(" `%s`", cmd) } else { for _, cmd := range closestCommands { msg += fmt.Sprintf(" `%s`\n", cmd) } } } fatalIf(errDummy().Trace(), msg) }
go
func commandNotFound(ctx *cli.Context, command string) { msg := fmt.Sprintf("`%s` is not a mc command. See `mc --help`.", command) closestCommands := findClosestCommands(command) if len(closestCommands) > 0 { msg += fmt.Sprintf("\n\nDid you mean one of these?\n") if len(closestCommands) == 1 { cmd := closestCommands[0] msg += fmt.Sprintf(" `%s`", cmd) } else { for _, cmd := range closestCommands { msg += fmt.Sprintf(" `%s`\n", cmd) } } } fatalIf(errDummy().Trace(), msg) }
[ "func", "commandNotFound", "(", "ctx", "*", "cli", ".", "Context", ",", "command", "string", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "command", ")", "\n", "closestCommands", ":=", "findClosestCommands", "(", "command", ")", "\n", "if", "len", "(", "closestCommands", ")", ">", "0", "{", "msg", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ")", "\n", "if", "len", "(", "closestCommands", ")", "==", "1", "{", "cmd", ":=", "closestCommands", "[", "0", "]", "\n", "msg", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cmd", ")", "\n", "}", "else", "{", "for", "_", ",", "cmd", ":=", "range", "closestCommands", "{", "msg", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "cmd", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "fatalIf", "(", "errDummy", "(", ")", ".", "Trace", "(", ")", ",", "msg", ")", "\n", "}" ]
// Function invoked when invalid command is passed.
[ "Function", "invoked", "when", "invalid", "command", "is", "passed", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/main.go#L110-L125
train
minio/mc
cmd/main.go
checkConfig
func checkConfig() { // Refresh the config once. loadMcConfig = loadMcConfigFactory() // Ensures config file is sane. config, err := loadMcConfig() // Verify if the path is accesible before validating the config fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.") // Validate and print error messges ok, errMsgs := validateConfigFile(config) if !ok { var errorMsg bytes.Buffer for index, errMsg := range errMsgs { // Print atmost 10 errors if index > 10 { break } errorMsg.WriteString(errMsg + "\n") } console.Fatal(errorMsg.String()) } }
go
func checkConfig() { // Refresh the config once. loadMcConfig = loadMcConfigFactory() // Ensures config file is sane. config, err := loadMcConfig() // Verify if the path is accesible before validating the config fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.") // Validate and print error messges ok, errMsgs := validateConfigFile(config) if !ok { var errorMsg bytes.Buffer for index, errMsg := range errMsgs { // Print atmost 10 errors if index > 10 { break } errorMsg.WriteString(errMsg + "\n") } console.Fatal(errorMsg.String()) } }
[ "func", "checkConfig", "(", ")", "{", "// Refresh the config once.", "loadMcConfig", "=", "loadMcConfigFactory", "(", ")", "\n", "// Ensures config file is sane.", "config", ",", "err", ":=", "loadMcConfig", "(", ")", "\n", "// Verify if the path is accesible before validating the config", "fatalIf", "(", "err", ".", "Trace", "(", "mustGetMcConfigPath", "(", ")", ")", ",", "\"", "\"", ")", "\n\n", "// Validate and print error messges", "ok", ",", "errMsgs", ":=", "validateConfigFile", "(", "config", ")", "\n", "if", "!", "ok", "{", "var", "errorMsg", "bytes", ".", "Buffer", "\n", "for", "index", ",", "errMsg", ":=", "range", "errMsgs", "{", "// Print atmost 10 errors", "if", "index", ">", "10", "{", "break", "\n", "}", "\n", "errorMsg", ".", "WriteString", "(", "errMsg", "+", "\"", "\\n", "\"", ")", "\n", "}", "\n", "console", ".", "Fatal", "(", "errorMsg", ".", "String", "(", ")", ")", "\n", "}", "\n", "}" ]
// Check for sane config environment early on and gracefully report.
[ "Check", "for", "sane", "config", "environment", "early", "on", "and", "gracefully", "report", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/main.go#L128-L149
train
minio/mc
cmd/main.go
initMC
func initMC() { // Check if mc config exists. if !isMcConfigExists() { err := saveMcConfig(newMcConfig()) fatalIf(err.Trace(), "Unable to save new mc config.") if !globalQuiet && !globalJSON { console.Infoln("Configuration written to `" + mustGetMcConfigPath() + "`. Please update your access credentials.") } } // Install mc completion, ignore any error for now _ = completeinstall.Install("mc") // Check if mc session directory exists. if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session config directory.") } // Check if mc share directory exists. if !isShareDirExists() { initShareConfig() } // Check if certs dir exists if !isCertsDirExists() { fatalIf(createCertsDir().Trace(), "Unable to create `CAs` directory.") } // Check if CAs dir exists if !isCAsDirExists() { fatalIf(createCAsDir().Trace(), "Unable to create `CAs` directory.") } // Load all authority certificates present in CAs dir loadRootCAs() }
go
func initMC() { // Check if mc config exists. if !isMcConfigExists() { err := saveMcConfig(newMcConfig()) fatalIf(err.Trace(), "Unable to save new mc config.") if !globalQuiet && !globalJSON { console.Infoln("Configuration written to `" + mustGetMcConfigPath() + "`. Please update your access credentials.") } } // Install mc completion, ignore any error for now _ = completeinstall.Install("mc") // Check if mc session directory exists. if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session config directory.") } // Check if mc share directory exists. if !isShareDirExists() { initShareConfig() } // Check if certs dir exists if !isCertsDirExists() { fatalIf(createCertsDir().Trace(), "Unable to create `CAs` directory.") } // Check if CAs dir exists if !isCAsDirExists() { fatalIf(createCAsDir().Trace(), "Unable to create `CAs` directory.") } // Load all authority certificates present in CAs dir loadRootCAs() }
[ "func", "initMC", "(", ")", "{", "// Check if mc config exists.", "if", "!", "isMcConfigExists", "(", ")", "{", "err", ":=", "saveMcConfig", "(", "newMcConfig", "(", ")", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n\n", "if", "!", "globalQuiet", "&&", "!", "globalJSON", "{", "console", ".", "Infoln", "(", "\"", "\"", "+", "mustGetMcConfigPath", "(", ")", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// Install mc completion, ignore any error for now", "_", "=", "completeinstall", ".", "Install", "(", "\"", "\"", ")", "\n\n", "// Check if mc session directory exists.", "if", "!", "isSessionDirExists", "(", ")", "{", "fatalIf", "(", "createSessionDir", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Check if mc share directory exists.", "if", "!", "isShareDirExists", "(", ")", "{", "initShareConfig", "(", ")", "\n", "}", "\n\n", "// Check if certs dir exists", "if", "!", "isCertsDirExists", "(", ")", "{", "fatalIf", "(", "createCertsDir", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Check if CAs dir exists", "if", "!", "isCAsDirExists", "(", ")", "{", "fatalIf", "(", "createCAsDir", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Load all authority certificates present in CAs dir", "loadRootCAs", "(", ")", "\n\n", "}" ]
// initMC - initialize 'mc'.
[ "initMC", "-", "initialize", "mc", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/main.go#L188-L225
train
minio/mc
cmd/main.go
findClosestCommands
func findClosestCommands(command string) []string { var closestCommands []string for _, value := range commandsTree.PrefixMatch(command) { closestCommands = append(closestCommands, value.(string)) } sort.Strings(closestCommands) // Suggest other close commands - allow missed, wrongly added and even transposed characters for _, value := range commandsTree.Walk(commandsTree.Root()) { if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) { continue } // 2 is arbitrary and represents the max allowed number of typed errors if words.DamerauLevenshteinDistance(command, value.(string)) < 2 { closestCommands = append(closestCommands, value.(string)) } } return closestCommands }
go
func findClosestCommands(command string) []string { var closestCommands []string for _, value := range commandsTree.PrefixMatch(command) { closestCommands = append(closestCommands, value.(string)) } sort.Strings(closestCommands) // Suggest other close commands - allow missed, wrongly added and even transposed characters for _, value := range commandsTree.Walk(commandsTree.Root()) { if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) { continue } // 2 is arbitrary and represents the max allowed number of typed errors if words.DamerauLevenshteinDistance(command, value.(string)) < 2 { closestCommands = append(closestCommands, value.(string)) } } return closestCommands }
[ "func", "findClosestCommands", "(", "command", "string", ")", "[", "]", "string", "{", "var", "closestCommands", "[", "]", "string", "\n", "for", "_", ",", "value", ":=", "range", "commandsTree", ".", "PrefixMatch", "(", "command", ")", "{", "closestCommands", "=", "append", "(", "closestCommands", ",", "value", ".", "(", "string", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "closestCommands", ")", "\n", "// Suggest other close commands - allow missed, wrongly added and even transposed characters", "for", "_", ",", "value", ":=", "range", "commandsTree", ".", "Walk", "(", "commandsTree", ".", "Root", "(", ")", ")", "{", "if", "sort", ".", "SearchStrings", "(", "closestCommands", ",", "value", ".", "(", "string", ")", ")", "<", "len", "(", "closestCommands", ")", "{", "continue", "\n", "}", "\n", "// 2 is arbitrary and represents the max allowed number of typed errors", "if", "words", ".", "DamerauLevenshteinDistance", "(", "command", ",", "value", ".", "(", "string", ")", ")", "<", "2", "{", "closestCommands", "=", "append", "(", "closestCommands", ",", "value", ".", "(", "string", ")", ")", "\n", "}", "\n", "}", "\n", "return", "closestCommands", "\n", "}" ]
// findClosestCommands to match a given string with commands trie tree.
[ "findClosestCommands", "to", "match", "a", "given", "string", "with", "commands", "trie", "tree", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/main.go#L250-L267
train
minio/mc
cmd/pretty-table.go
newPrettyTable
func newPrettyTable(separator string, cols ...Field) PrettyTable { return PrettyTable{ cols: cols, separator: separator, } }
go
func newPrettyTable(separator string, cols ...Field) PrettyTable { return PrettyTable{ cols: cols, separator: separator, } }
[ "func", "newPrettyTable", "(", "separator", "string", ",", "cols", "...", "Field", ")", "PrettyTable", "{", "return", "PrettyTable", "{", "cols", ":", "cols", ",", "separator", ":", "separator", ",", "}", "\n", "}" ]
// newPrettyTable - creates a new pretty table
[ "newPrettyTable", "-", "creates", "a", "new", "pretty", "table" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pretty-table.go#L38-L43
train
minio/mc
cmd/pretty-table.go
buildRow
func (t PrettyTable) buildRow(contents ...string) (line string) { dots := "..." // totalColumns is the minimum of the number of fields config // and the number of contents elements. totalColumns := len(contents) if len(t.cols) < totalColumns { totalColumns = len(t.cols) } // Format fields and construct message for i := 0; i < totalColumns; i++ { // Default field format without pretty effect fieldContent := "" fieldFormat := "%s" if t.cols[i].maxLen >= 0 { // Override field format fieldFormat = fmt.Sprintf("%%-%d.%ds", t.cols[i].maxLen, t.cols[i].maxLen) // Cut field string and add '...' if length is greater than maxLen if len(contents[i]) > t.cols[i].maxLen { fieldContent = contents[i][:t.cols[i].maxLen-len(dots)] + dots } else { fieldContent = contents[i] } } else { fieldContent = contents[i] } // Add separator if this is not the last column if i < totalColumns-1 { fieldFormat += t.separator } // Add the field to the resulted message line += console.Colorize(t.cols[i].colorTheme, fmt.Sprintf(fieldFormat, fieldContent)) } return }
go
func (t PrettyTable) buildRow(contents ...string) (line string) { dots := "..." // totalColumns is the minimum of the number of fields config // and the number of contents elements. totalColumns := len(contents) if len(t.cols) < totalColumns { totalColumns = len(t.cols) } // Format fields and construct message for i := 0; i < totalColumns; i++ { // Default field format without pretty effect fieldContent := "" fieldFormat := "%s" if t.cols[i].maxLen >= 0 { // Override field format fieldFormat = fmt.Sprintf("%%-%d.%ds", t.cols[i].maxLen, t.cols[i].maxLen) // Cut field string and add '...' if length is greater than maxLen if len(contents[i]) > t.cols[i].maxLen { fieldContent = contents[i][:t.cols[i].maxLen-len(dots)] + dots } else { fieldContent = contents[i] } } else { fieldContent = contents[i] } // Add separator if this is not the last column if i < totalColumns-1 { fieldFormat += t.separator } // Add the field to the resulted message line += console.Colorize(t.cols[i].colorTheme, fmt.Sprintf(fieldFormat, fieldContent)) } return }
[ "func", "(", "t", "PrettyTable", ")", "buildRow", "(", "contents", "...", "string", ")", "(", "line", "string", ")", "{", "dots", ":=", "\"", "\"", "\n\n", "// totalColumns is the minimum of the number of fields config", "// and the number of contents elements.", "totalColumns", ":=", "len", "(", "contents", ")", "\n", "if", "len", "(", "t", ".", "cols", ")", "<", "totalColumns", "{", "totalColumns", "=", "len", "(", "t", ".", "cols", ")", "\n", "}", "\n\n", "// Format fields and construct message", "for", "i", ":=", "0", ";", "i", "<", "totalColumns", ";", "i", "++", "{", "// Default field format without pretty effect", "fieldContent", ":=", "\"", "\"", "\n", "fieldFormat", ":=", "\"", "\"", "\n", "if", "t", ".", "cols", "[", "i", "]", ".", "maxLen", ">=", "0", "{", "// Override field format", "fieldFormat", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "cols", "[", "i", "]", ".", "maxLen", ",", "t", ".", "cols", "[", "i", "]", ".", "maxLen", ")", "\n", "// Cut field string and add '...' if length is greater than maxLen", "if", "len", "(", "contents", "[", "i", "]", ")", ">", "t", ".", "cols", "[", "i", "]", ".", "maxLen", "{", "fieldContent", "=", "contents", "[", "i", "]", "[", ":", "t", ".", "cols", "[", "i", "]", ".", "maxLen", "-", "len", "(", "dots", ")", "]", "+", "dots", "\n", "}", "else", "{", "fieldContent", "=", "contents", "[", "i", "]", "\n", "}", "\n", "}", "else", "{", "fieldContent", "=", "contents", "[", "i", "]", "\n", "}", "\n\n", "// Add separator if this is not the last column", "if", "i", "<", "totalColumns", "-", "1", "{", "fieldFormat", "+=", "t", ".", "separator", "\n", "}", "\n\n", "// Add the field to the resulted message", "line", "+=", "console", ".", "Colorize", "(", "t", ".", "cols", "[", "i", "]", ".", "colorTheme", ",", "fmt", ".", "Sprintf", "(", "fieldFormat", ",", "fieldContent", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// buildRow - creates a string which represents a line table given // some fields contents.
[ "buildRow", "-", "creates", "a", "string", "which", "represents", "a", "line", "table", "given", "some", "fields", "contents", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pretty-table.go#L47-L84
train
minio/mc
cmd/session-migrate.go
migrateSessionV7ToV8
func migrateSessionV7ToV8() { for _, sid := range getSessionIDs() { sV7, err := loadSessionV7(sid) if err != nil { if os.IsNotExist(err.ToGoError()) { continue } fatalIf(err.Trace(sid), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.") } // Close underlying session data file. sV7.DataFP.Close() sessionVersion, e := strconv.Atoi(sV7.Header.Version) fatalIf(probe.NewError(e), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.") if sessionVersion > 7 { // 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. sV8Header := &sessionV8Header{} sV8Header.Version = globalSessionConfigVersion sV8Header.When = sV7.Header.When sV8Header.RootPath = sV7.Header.RootPath sV8Header.GlobalBoolFlags = sV7.Header.GlobalBoolFlags sV8Header.GlobalIntFlags = sV7.Header.GlobalIntFlags sV8Header.GlobalStringFlags = sV7.Header.GlobalStringFlags sV8Header.CommandType = sV7.Header.CommandType sV8Header.CommandArgs = sV7.Header.CommandArgs sV8Header.CommandBoolFlags = sV7.Header.CommandBoolFlags sV8Header.CommandIntFlags = sV7.Header.CommandIntFlags sV8Header.CommandStringFlags = sV7.Header.CommandStringFlags sV8Header.LastCopied = sV7.Header.LastCopied sV8Header.LastRemoved = sV7.Header.LastRemoved sV8Header.TotalBytes = sV7.Header.TotalBytes sV8Header.TotalObjects = int64(sV7.Header.TotalObjects) // Add insecure flag to the new V8 header sV8Header.GlobalBoolFlags["insecure"] = false qs, e := quick.NewConfig(sV8Header, nil) fatalIf(probe.NewError(e).Trace(sid), "Unable to initialize quick config for session '8' header.") e = qs.Save(sessionFile) fatalIf(probe.NewError(e).Trace(sid, sessionFile), "Unable to migrate session from '7' to '8'.") console.Println("Successfully migrated `" + sessionFile + "` from version `" + sV7.Header.Version + "` to " + "`" + sV8Header.Version + "`.") } }
go
func migrateSessionV7ToV8() { for _, sid := range getSessionIDs() { sV7, err := loadSessionV7(sid) if err != nil { if os.IsNotExist(err.ToGoError()) { continue } fatalIf(err.Trace(sid), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.") } // Close underlying session data file. sV7.DataFP.Close() sessionVersion, e := strconv.Atoi(sV7.Header.Version) fatalIf(probe.NewError(e), "Unable to load version `7`. Migration failed please report this issue at https://github.com/minio/mc/issues.") if sessionVersion > 7 { // 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. sV8Header := &sessionV8Header{} sV8Header.Version = globalSessionConfigVersion sV8Header.When = sV7.Header.When sV8Header.RootPath = sV7.Header.RootPath sV8Header.GlobalBoolFlags = sV7.Header.GlobalBoolFlags sV8Header.GlobalIntFlags = sV7.Header.GlobalIntFlags sV8Header.GlobalStringFlags = sV7.Header.GlobalStringFlags sV8Header.CommandType = sV7.Header.CommandType sV8Header.CommandArgs = sV7.Header.CommandArgs sV8Header.CommandBoolFlags = sV7.Header.CommandBoolFlags sV8Header.CommandIntFlags = sV7.Header.CommandIntFlags sV8Header.CommandStringFlags = sV7.Header.CommandStringFlags sV8Header.LastCopied = sV7.Header.LastCopied sV8Header.LastRemoved = sV7.Header.LastRemoved sV8Header.TotalBytes = sV7.Header.TotalBytes sV8Header.TotalObjects = int64(sV7.Header.TotalObjects) // Add insecure flag to the new V8 header sV8Header.GlobalBoolFlags["insecure"] = false qs, e := quick.NewConfig(sV8Header, nil) fatalIf(probe.NewError(e).Trace(sid), "Unable to initialize quick config for session '8' header.") e = qs.Save(sessionFile) fatalIf(probe.NewError(e).Trace(sid, sessionFile), "Unable to migrate session from '7' to '8'.") console.Println("Successfully migrated `" + sessionFile + "` from version `" + sV7.Header.Version + "` to " + "`" + sV8Header.Version + "`.") } }
[ "func", "migrateSessionV7ToV8", "(", ")", "{", "for", "_", ",", "sid", ":=", "range", "getSessionIDs", "(", ")", "{", "sV7", ",", "err", ":=", "loadSessionV7", "(", "sid", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ".", "ToGoError", "(", ")", ")", "{", "continue", "\n", "}", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Close underlying session data file.", "sV7", ".", "DataFP", ".", "Close", "(", ")", "\n\n", "sessionVersion", ",", "e", ":=", "strconv", ".", "Atoi", "(", "sV7", ".", "Header", ".", "Version", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n", "if", "sessionVersion", ">", "7", "{", "// It is new format.", "continue", "\n", "}", "\n\n", "sessionFile", ",", "err", ":=", "getSessionFile", "(", "sid", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", ")", "\n\n", "// Initialize v7 header and migrate to new config.", "sV8Header", ":=", "&", "sessionV8Header", "{", "}", "\n", "sV8Header", ".", "Version", "=", "globalSessionConfigVersion", "\n", "sV8Header", ".", "When", "=", "sV7", ".", "Header", ".", "When", "\n", "sV8Header", ".", "RootPath", "=", "sV7", ".", "Header", ".", "RootPath", "\n", "sV8Header", ".", "GlobalBoolFlags", "=", "sV7", ".", "Header", ".", "GlobalBoolFlags", "\n", "sV8Header", ".", "GlobalIntFlags", "=", "sV7", ".", "Header", ".", "GlobalIntFlags", "\n", "sV8Header", ".", "GlobalStringFlags", "=", "sV7", ".", "Header", ".", "GlobalStringFlags", "\n", "sV8Header", ".", "CommandType", "=", "sV7", ".", "Header", ".", "CommandType", "\n", "sV8Header", ".", "CommandArgs", "=", "sV7", ".", "Header", ".", "CommandArgs", "\n", "sV8Header", ".", "CommandBoolFlags", "=", "sV7", ".", "Header", ".", "CommandBoolFlags", "\n", "sV8Header", ".", "CommandIntFlags", "=", "sV7", ".", "Header", ".", "CommandIntFlags", "\n", "sV8Header", ".", "CommandStringFlags", "=", "sV7", ".", "Header", ".", "CommandStringFlags", "\n", "sV8Header", ".", "LastCopied", "=", "sV7", ".", "Header", ".", "LastCopied", "\n", "sV8Header", ".", "LastRemoved", "=", "sV7", ".", "Header", ".", "LastRemoved", "\n", "sV8Header", ".", "TotalBytes", "=", "sV7", ".", "Header", ".", "TotalBytes", "\n", "sV8Header", ".", "TotalObjects", "=", "int64", "(", "sV7", ".", "Header", ".", "TotalObjects", ")", "\n\n", "// Add insecure flag to the new V8 header", "sV8Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "=", "false", "\n\n", "qs", ",", "e", ":=", "quick", ".", "NewConfig", "(", "sV8Header", ",", "nil", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", ")", "\n\n", "e", "=", "qs", ".", "Save", "(", "sessionFile", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ",", "sessionFile", ")", ",", "\"", "\"", ")", "\n\n", "console", ".", "Println", "(", "\"", "\"", "+", "sessionFile", "+", "\"", "\"", "+", "sV7", ".", "Header", ".", "Version", "+", "\"", "\"", "+", "\"", "\"", "+", "sV8Header", ".", "Version", "+", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Migrates session header version '7' to '8'. The only // change was the adding of insecure global flag
[ "Migrates", "session", "header", "version", "7", "to", "8", ".", "The", "only", "change", "was", "the", "adding", "of", "insecure", "global", "flag" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-migrate.go#L30-L81
train
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", ".", "IsNotExist", "(", "err", ".", "ToGoError", "(", ")", ")", "{", "continue", "\n", "}", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "sessionVersion", ",", "e", ":=", "strconv", ".", "Atoi", "(", "sV6Header", ".", "Version", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n", "if", "sessionVersion", ">", "6", "{", "// It is new format.", "continue", "\n", "}", "\n\n", "sessionFile", ",", "err", ":=", "getSessionFile", "(", "sid", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", ")", "\n\n", "// Initialize v7 header and migrate to new config.", "sV7Header", ":=", "&", "sessionV7Header", "{", "}", "\n", "sV7Header", ".", "Version", "=", "\"", "\"", "\n", "sV7Header", ".", "When", "=", "sV6Header", ".", "When", "\n", "sV7Header", ".", "RootPath", "=", "sV6Header", ".", "RootPath", "\n", "sV7Header", ".", "GlobalBoolFlags", "=", "sV6Header", ".", "GlobalBoolFlags", "\n", "sV7Header", ".", "GlobalIntFlags", "=", "sV6Header", ".", "GlobalIntFlags", "\n", "sV7Header", ".", "GlobalStringFlags", "=", "sV6Header", ".", "GlobalStringFlags", "\n", "sV7Header", ".", "CommandType", "=", "sV6Header", ".", "CommandType", "\n", "sV7Header", ".", "CommandArgs", "=", "sV6Header", ".", "CommandArgs", "\n", "sV7Header", ".", "CommandBoolFlags", "=", "sV6Header", ".", "CommandBoolFlags", "\n", "sV7Header", ".", "CommandIntFlags", "=", "sV6Header", ".", "CommandIntFlags", "\n", "sV7Header", ".", "CommandStringFlags", "=", "sV6Header", ".", "CommandStringFlags", "\n", "sV7Header", ".", "LastCopied", "=", "sV6Header", ".", "LastCopied", "\n", "sV7Header", ".", "LastRemoved", "=", "\"", "\"", "\n", "sV7Header", ".", "TotalBytes", "=", "sV6Header", ".", "TotalBytes", "\n", "sV7Header", ".", "TotalObjects", "=", "sV6Header", ".", "TotalObjects", "\n\n", "qs", ",", "e", ":=", "quick", ".", "NewConfig", "(", "sV7Header", ",", "nil", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ")", ",", "\"", "\"", ")", "\n\n", "e", "=", "qs", ".", "Save", "(", "sessionFile", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ",", "sessionFile", ")", ",", "\"", "\"", ")", "\n\n", "console", ".", "Println", "(", "\"", "\"", "+", "sessionFile", "+", "\"", "\"", "+", "sV6Header", ".", "Version", "+", "\"", "\"", "+", "\"", "\"", "+", "sV7Header", ".", "Version", "+", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// 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", "{", "// Parse encryption keys per command.", "encKeyDB", ",", "err", ":=", "getEncKeys", "(", "ctx", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "// check 'rm' cli arguments.", "checkRmSyntax", "(", "ctx", ",", "encKeyDB", ")", "\n\n", "// rm specific flags.", "isIncomplete", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "isRecursive", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "isFake", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "isStdin", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n", "olderThan", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "newerThan", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "isForce", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n\n", "// Set color.", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ",", "color", ".", "Bold", ")", ")", "\n\n", "var", "rerr", "error", "\n", "var", "e", "error", "\n", "// Support multiple targets.", "for", "_", ",", "url", ":=", "range", "ctx", ".", "Args", "(", ")", "{", "if", "isRecursive", "{", "e", "=", "removeRecursive", "(", "url", ",", "isIncomplete", ",", "isFake", ",", "olderThan", ",", "newerThan", ",", "encKeyDB", ")", "\n", "}", "else", "{", "e", "=", "removeSingle", "(", "url", ",", "isIncomplete", ",", "isFake", ",", "isForce", ",", "olderThan", ",", "newerThan", ",", "encKeyDB", ")", "\n", "}", "\n\n", "if", "rerr", "==", "nil", "{", "rerr", "=", "e", "\n", "}", "\n", "}", "\n\n", "if", "!", "isStdin", "{", "return", "rerr", "\n", "}", "\n\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "os", ".", "Stdin", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "url", ":=", "scanner", ".", "Text", "(", ")", "\n", "if", "isRecursive", "{", "e", "=", "removeRecursive", "(", "url", ",", "isIncomplete", ",", "isFake", ",", "olderThan", ",", "newerThan", ",", "encKeyDB", ")", "\n", "}", "else", "{", "e", "=", "removeSingle", "(", "url", ",", "isIncomplete", ",", "isFake", ",", "isForce", ",", "olderThan", ",", "newerThan", ",", "encKeyDB", ")", "\n", "}", "\n\n", "if", "rerr", "==", "nil", "{", "rerr", "=", "e", "\n", "}", "\n", "}", "\n\n", "return", "rerr", "\n", "}" ]
// 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", ")", "{", "// Check source.", "if", "len", "(", "srcURLs", ")", "!=", "1", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "srcURL", ":=", "srcURLs", "[", "0", "]", "\n", "_", ",", "srcContent", ",", "err", ":=", "url2Stat", "(", "srcURL", ",", "false", ",", "keys", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "srcURL", ")", ",", "\"", "\"", "+", "srcURL", "+", "\"", "\"", ")", "\n\n", "if", "!", "srcContent", ".", "Type", ".", "IsRegular", "(", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", "+", "srcURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// 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", ")", "{", "// Check source.", "if", "len", "(", "srcURLs", ")", "!=", "1", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "srcURL", ":=", "srcURLs", "[", "0", "]", "\n", "_", ",", "srcContent", ",", "err", ":=", "url2Stat", "(", "srcURL", ",", "false", ",", "keys", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "srcURL", ")", ",", "\"", "\"", "+", "srcURL", "+", "\"", "\"", ")", "\n\n", "if", "!", "srcContent", ".", "Type", ".", "IsRegular", "(", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "srcURL", ")", ",", "\"", "\"", "+", "srcURL", "+", "\"", "\"", ")", "\n", "}", "\n\n", "// Check target.", "if", "_", ",", "tgtContent", ",", "err", ":=", "url2Stat", "(", "tgtURL", ",", "false", ",", "keys", ")", ";", "err", "==", "nil", "{", "if", "!", "tgtContent", ".", "Type", ".", "IsDir", "(", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "tgtURL", ")", ",", "\"", "\"", "+", "tgtURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// 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", ")", "{", "// Check source.", "if", "len", "(", "srcURLs", ")", "!=", "1", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Check target.", "if", "_", ",", "tgtContent", ",", "err", ":=", "url2Stat", "(", "tgtURL", ",", "false", ",", "keys", ")", ";", "err", "==", "nil", "{", "if", "!", "tgtContent", ".", "Type", ".", "IsDir", "(", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "tgtURL", ")", ",", "\"", "\"", "+", "tgtURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "srcURL", ":=", "range", "srcURLs", "{", "c", ",", "srcContent", ",", "err", ":=", "url2Stat", "(", "srcURL", ",", "false", ",", "keys", ")", "\n", "// incomplete uploads are not necessary for copy operation, no need to verify for them.", "isIncomplete", ":=", "false", "\n", "if", "err", "!=", "nil", "{", "if", "!", "isURLPrefixExists", "(", "srcURL", ",", "isIncomplete", ")", "{", "fatalIf", "(", "err", ".", "Trace", "(", "srcURL", ")", ",", "\"", "\"", "+", "srcURL", "+", "\"", "\"", ")", "\n", "}", "\n", "// No more check here, continue to the next source url", "continue", "\n", "}", "\n\n", "if", "srcContent", ".", "Type", ".", "IsDir", "(", ")", "{", "// Require --recursive flag if we are copying a directory", "if", "!", "isRecursive", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "srcURL", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Check if we are going to copy a directory into itself", "if", "isURLContains", "(", "srcURL", ",", "tgtURL", ",", "string", "(", "c", ".", "GetURL", "(", ")", ".", "Separator", ")", ")", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "}" ]
// 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", ")", "{", "// 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", ")", ",", "\"", "\"", "+", "tgtURL", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// 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", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n\n", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "if", "strings", ".", "TrimSpace", "(", "arg", ")", "==", "\"", "\"", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", "args", "...", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "// extract URLs.", "URLs", ":=", "ctx", ".", "Args", "(", ")", "\n", "isIncomplete", ":=", "false", "\n\n", "for", "_", ",", "url", ":=", "range", "URLs", "{", "_", ",", "_", ",", "err", ":=", "url2Stat", "(", "url", ",", "false", ",", "encKeyDB", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "isURLPrefixExists", "(", "url", ",", "isIncomplete", ")", "{", "fatalIf", "(", "err", ".", "Trace", "(", "url", ")", ",", "\"", "\"", "+", "url", "+", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// 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", "{", "// Additional command specific theme customization.", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "Bold", ",", "color", ".", "FgCyan", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgWhite", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgWhite", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgWhite", ")", ")", "\n\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgWhite", ")", ")", "\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgWhite", ")", ")", "\n\n", "// Parse encryption keys per command.", "encKeyDB", ",", "err", ":=", "getEncKeys", "(", "ctx", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "// check 'stat' cli arguments.", "checkStatSyntax", "(", "ctx", ",", "encKeyDB", ")", "\n\n", "// Set command flags from context.", "isRecursive", ":=", "ctx", ".", "Bool", "(", "\"", "\"", ")", "\n\n", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "// mimic operating system tool behavior.", "if", "!", "ctx", ".", "Args", "(", ")", ".", "Present", "(", ")", "{", "args", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n\n", "var", "cErr", "error", "\n", "for", "_", ",", "targetURL", ":=", "range", "args", "{", "stats", ",", "err", ":=", "statURL", "(", "targetURL", ",", "false", ",", "isRecursive", ",", "encKeyDB", ")", "\n", "if", "err", "!=", "nil", "{", "fatalIf", "(", "err", ",", "\"", "\"", "+", "targetURL", "+", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "stat", ":=", "range", "stats", "{", "st", ":=", "parseStat", "(", "stat", ")", "\n", "if", "!", "globalJSON", "{", "printStat", "(", "st", ")", "\n", "}", "else", "{", "console", ".", "Println", "(", "st", ".", "JSON", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "cErr", "\n\n", "}" ]
// 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", "{", "// Trim text to fit within the screen", "trimSize", ":=", "len", "(", "[", "]", "rune", "(", "text", ")", ")", "-", "width", "+", "3", "//\"...\"", "\n", "if", "trimSize", "<", "len", "(", "[", "]", "rune", "(", "text", ")", ")", "{", "text", "=", "\"", "\"", "+", "text", "[", "trimSize", ":", "]", "\n", "}", "\n", "}", "else", "{", "text", "+=", "strings", ".", "Repeat", "(", "\"", "\"", ",", "width", "-", "len", "(", "[", "]", "rune", "(", "text", ")", ")", ")", "\n", "}", "\n", "return", "text", "\n", "}" ]
// 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\n", "// Cursor animate channel.", "cursorCh", ":=", "cursorAnimate", "(", ")", "\n", "return", "func", "(", "source", "string", ")", "{", "scanPrefix", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "humanize", ".", "Comma", "(", "int64", "(", "fileCount", ")", ")", ",", "<-", "cursorCh", ")", "\n", "source", "=", "fixateScanBar", "(", "source", ",", "globalTermWidth", "-", "len", "(", "[", "]", "rune", "(", "scanPrefix", ")", ")", ")", "\n", "barText", ":=", "scanPrefix", "+", "source", "\n", "console", ".", "PrintC", "(", "\"", "\\r", "\"", "+", "barText", "+", "\"", "\\r", "\"", ")", "\n", "fileCount", "++", "\n", "}", "\n", "}" ]
// 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\n", "if", "e", ":=", "os", ".", "MkdirAll", "(", "sessionDir", ",", "0700", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", "}", "\n\n", "sessionDir", ":=", "filepath", ".", "Join", "(", "configDir", ",", "globalSessionDir", ")", "\n", "return", "sessionDir", ",", "nil", "\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", "(", ")", ",", "\"", "\"", ")", "\n\n", "if", "_", ",", "e", ":=", "os", ".", "Stat", "(", "sessionDir", ")", ";", "e", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// 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", "(", ")", "\n", "}", "\n\n", "sessionFile", ":=", "filepath", ".", "Join", "(", "sessionDir", ",", "sid", "+", "\"", "\"", ")", "\n", "return", "sessionFile", ",", "nil", "\n", "}" ]
// 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", ")", ",", "\"", "\"", "+", "sid", "+", "\"", "\"", ")", "\n\n", "if", "_", ",", "e", ":=", "os", ".", "Stat", "(", "sessionFile", ")", ";", "e", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "// Session exists.", "\n", "}" ]
// 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", ".", "Trace", "(", ")", "\n", "}", "\n\n", "sessionDataFile", ":=", "filepath", ".", "Join", "(", "sessionDir", ",", "sid", "+", "\"", "\"", ")", "\n", "return", "sessionDataFile", ",", "nil", "\n", "}" ]
// 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", "(", ")", ",", "\"", "\"", ")", "\n\n", "sessionList", ",", "e", ":=", "filepath", ".", "Glob", "(", "sessionDir", "+", "\"", "\"", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", "+", "sessionDir", "+", "\"", "\"", ")", "\n\n", "for", "_", ",", "path", ":=", "range", "sessionList", "{", "sids", "=", "append", "(", "sids", ",", "strings", ".", "TrimSuffix", "(", "filepath", ".", "Base", "(", "path", ")", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "sids", "\n", "}" ]
// 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\n", "// Checking version is always successful with go tip", "if", "strings", ".", "HasPrefix", "(", "runtimeVersion", ",", "\"", "\"", ")", "{", "return", "\n", "}", "\n\n", "// Parsing golang version", "curVersion", ",", "e", ":=", "version", ".", "NewVersion", "(", "runtimeVersion", "[", "2", ":", "]", ")", "\n", "if", "e", "!=", "nil", "{", "console", ".", "Fatalln", "(", "\"", "\"", ",", "e", ")", "\n", "}", "\n\n", "// Prepare version constraint.", "constraints", ",", "e", ":=", "version", ".", "NewConstraint", "(", "minGoVersion", ")", "\n", "if", "e", "!=", "nil", "{", "console", ".", "Fatalln", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check for minimum version.", "if", "!", "constraints", ".", "Check", "(", "curVersion", ")", "{", "console", ".", "Fatalln", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "minGoVersion", ")", ")", "\n", "}", "\n", "}" ]
// 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", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\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