repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
minio/mc | cmd/rb-main.go | deleteBucket | func deleteBucket(url string) *probe.Error {
targetAlias, targetURL, _ := mustExpandAlias(url)
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
if pErr != nil {
return pErr
}
var isIncomplete bool
isRemoveBucket := true
contentCh := make(chan *clientContent)
errorCh := clnt.Remove(isIncomplete, isRemoveBucket, contentCh)
for content := range clnt.List(true, false, DirLast) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
case PathInsufficientPermission:
errorIf(content.Err.Trace(url), "Failed to remove `"+url+"`.")
// Ignore Permission error.
continue
}
close(contentCh)
return content.Err
}
urlString := content.URL.Path
sent := false
for !sent {
select {
case contentCh <- content:
sent = true
case pErr := <-errorCh:
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
errorIf(pErr.Trace(urlString), "Failed to remove `"+urlString+"`.")
// Ignore Permission error.
continue
}
close(contentCh)
return pErr
}
}
// list internally mimics recursive directory listing of object prefixes for s3 similar to FS.
// The rmMessage needs to be printed only for actual buckets being deleted and not objects.
tgt := strings.TrimPrefix(urlString, string(filepath.Separator))
if !strings.Contains(tgt, string(filepath.Separator)) && tgt != targetAlias {
printMsg(removeBucketMessage{
Bucket: targetAlias + urlString, Status: "success",
})
}
}
// Remove the given url since the user will always want to remove it.
alias, _ := url2Alias(targetURL)
if alias != "" {
contentCh <- &clientContent{URL: *newClientURL(targetURL)}
}
// Finish removing and print all the remaining errors
close(contentCh)
for pErr := range errorCh {
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
// Ignore Permission error.
continue
}
return pErr
}
return nil
} | go | func deleteBucket(url string) *probe.Error {
targetAlias, targetURL, _ := mustExpandAlias(url)
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
if pErr != nil {
return pErr
}
var isIncomplete bool
isRemoveBucket := true
contentCh := make(chan *clientContent)
errorCh := clnt.Remove(isIncomplete, isRemoveBucket, contentCh)
for content := range clnt.List(true, false, DirLast) {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
case PathInsufficientPermission:
errorIf(content.Err.Trace(url), "Failed to remove `"+url+"`.")
// Ignore Permission error.
continue
}
close(contentCh)
return content.Err
}
urlString := content.URL.Path
sent := false
for !sent {
select {
case contentCh <- content:
sent = true
case pErr := <-errorCh:
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
errorIf(pErr.Trace(urlString), "Failed to remove `"+urlString+"`.")
// Ignore Permission error.
continue
}
close(contentCh)
return pErr
}
}
// list internally mimics recursive directory listing of object prefixes for s3 similar to FS.
// The rmMessage needs to be printed only for actual buckets being deleted and not objects.
tgt := strings.TrimPrefix(urlString, string(filepath.Separator))
if !strings.Contains(tgt, string(filepath.Separator)) && tgt != targetAlias {
printMsg(removeBucketMessage{
Bucket: targetAlias + urlString, Status: "success",
})
}
}
// Remove the given url since the user will always want to remove it.
alias, _ := url2Alias(targetURL)
if alias != "" {
contentCh <- &clientContent{URL: *newClientURL(targetURL)}
}
// Finish removing and print all the remaining errors
close(contentCh)
for pErr := range errorCh {
switch pErr.ToGoError().(type) {
case PathInsufficientPermission:
errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.")
// Ignore Permission error.
continue
}
return pErr
}
return nil
} | [
"func",
"deleteBucket",
"(",
"url",
"string",
")",
"*",
"probe",
".",
"Error",
"{",
"targetAlias",
",",
"targetURL",
",",
"_",
":=",
"mustExpandAlias",
"(",
"url",
")",
"\n",
"clnt",
",",
"pErr",
":=",
"newClientFromAlias",
"(",
"targetAlias",
",",
"target... | // deletes a bucket and all its contents | [
"deletes",
"a",
"bucket",
"and",
"all",
"its",
"contents"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/rb-main.go#L116-L184 | train |
minio/mc | cmd/rb-main.go | isNamespaceRemoval | func isNamespaceRemoval(url string) bool {
// clean path for aliases like s3/.
//Note: UNC path using / works properly in go 1.9.2 even though it breaks the UNC specification.
url = filepath.ToSlash(filepath.Clean(url))
// namespace removal applies only for non FS. So filter out if passed url represents a directory
if !isAliasURLDir(url, nil) {
_, path := url2Alias(url)
return (path == "")
}
return false
} | go | func isNamespaceRemoval(url string) bool {
// clean path for aliases like s3/.
//Note: UNC path using / works properly in go 1.9.2 even though it breaks the UNC specification.
url = filepath.ToSlash(filepath.Clean(url))
// namespace removal applies only for non FS. So filter out if passed url represents a directory
if !isAliasURLDir(url, nil) {
_, path := url2Alias(url)
return (path == "")
}
return false
} | [
"func",
"isNamespaceRemoval",
"(",
"url",
"string",
")",
"bool",
"{",
"url",
"=",
"filepath",
".",
"ToSlash",
"(",
"filepath",
".",
"Clean",
"(",
"url",
")",
")",
"\n",
"if",
"!",
"isAliasURLDir",
"(",
"url",
",",
"nil",
")",
"{",
"_",
",",
"path",
... | // isNamespaceRemoval returns true if alias
// is not qualified by bucket | [
"isNamespaceRemoval",
"returns",
"true",
"if",
"alias",
"is",
"not",
"qualified",
"by",
"bucket"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/rb-main.go#L188-L198 | train |
minio/mc | cmd/rb-main.go | mainRemoveBucket | func mainRemoveBucket(ctx *cli.Context) error {
// check 'rb' cli arguments.
checkRbSyntax(ctx)
isForce := ctx.Bool("force")
// Additional command specific theme customization.
console.SetColor("RemoveBucket", color.New(color.FgGreen, color.Bold))
var cErr error
for _, targetURL := range ctx.Args() {
// Instantiate client for URL.
clnt, err := newClient(targetURL)
if err != nil {
errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
continue
}
_, err = clnt.Stat(false, false, nil)
if err != nil {
switch err.ToGoError().(type) {
case BucketNameEmpty:
default:
errorIf(err.Trace(targetURL), "Unable to validate target `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
continue
}
}
isEmpty := true
for range clnt.List(true, false, DirNone) {
isEmpty = false
break
}
// For all recursive operations make sure to check for 'force' flag.
if !isForce && !isEmpty {
fatalIf(errDummy().Trace(), "`"+targetURL+"` is not empty. Retry this command with ‘--force’ flag if you want to remove `"+targetURL+"` and all its contents")
}
e := deleteBucket(targetURL)
fatalIf(e.Trace(targetURL), "Failed to remove `"+targetURL+"`.")
}
return cErr
} | go | func mainRemoveBucket(ctx *cli.Context) error {
// check 'rb' cli arguments.
checkRbSyntax(ctx)
isForce := ctx.Bool("force")
// Additional command specific theme customization.
console.SetColor("RemoveBucket", color.New(color.FgGreen, color.Bold))
var cErr error
for _, targetURL := range ctx.Args() {
// Instantiate client for URL.
clnt, err := newClient(targetURL)
if err != nil {
errorIf(err.Trace(targetURL), "Invalid target `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
continue
}
_, err = clnt.Stat(false, false, nil)
if err != nil {
switch err.ToGoError().(type) {
case BucketNameEmpty:
default:
errorIf(err.Trace(targetURL), "Unable to validate target `"+targetURL+"`.")
cErr = exitStatus(globalErrorExitStatus)
continue
}
}
isEmpty := true
for range clnt.List(true, false, DirNone) {
isEmpty = false
break
}
// For all recursive operations make sure to check for 'force' flag.
if !isForce && !isEmpty {
fatalIf(errDummy().Trace(), "`"+targetURL+"` is not empty. Retry this command with ‘--force’ flag if you want to remove `"+targetURL+"` and all its contents")
}
e := deleteBucket(targetURL)
fatalIf(e.Trace(targetURL), "Failed to remove `"+targetURL+"`.")
}
return cErr
} | [
"func",
"mainRemoveBucket",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"checkRbSyntax",
"(",
"ctx",
")",
"\n",
"isForce",
":=",
"ctx",
".",
"Bool",
"(",
"\"force\"",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"RemoveBucket\"",
",",
"co... | // mainRemoveBucket is entry point for rb command. | [
"mainRemoveBucket",
"is",
"entry",
"point",
"for",
"rb",
"command",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/rb-main.go#L201-L242 | train |
minio/mc | cmd/share.go | String | func (s shareMesssage) String() string {
msg := console.Colorize("URL", fmt.Sprintf("URL: %s\n", s.ObjectURL))
msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedDuration(s.TimeLeft)))
if s.ContentType != "" {
msg += console.Colorize("Content-type", fmt.Sprintf("Content-Type: %s\n", s.ContentType))
}
// Highlight <FILE> specifically. "share upload" sub-commands use this identifier.
shareURL := strings.Replace(s.ShareURL, "<FILE>", console.Colorize("File", "<FILE>"), 1)
// Highlight <KEY> specifically for recursive operation.
shareURL = strings.Replace(shareURL, "<NAME>", console.Colorize("File", "<NAME>"), 1)
msg += console.Colorize("Share", fmt.Sprintf("Share: %s\n", shareURL))
return msg
} | go | func (s shareMesssage) String() string {
msg := console.Colorize("URL", fmt.Sprintf("URL: %s\n", s.ObjectURL))
msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedDuration(s.TimeLeft)))
if s.ContentType != "" {
msg += console.Colorize("Content-type", fmt.Sprintf("Content-Type: %s\n", s.ContentType))
}
// Highlight <FILE> specifically. "share upload" sub-commands use this identifier.
shareURL := strings.Replace(s.ShareURL, "<FILE>", console.Colorize("File", "<FILE>"), 1)
// Highlight <KEY> specifically for recursive operation.
shareURL = strings.Replace(shareURL, "<NAME>", console.Colorize("File", "<NAME>"), 1)
msg += console.Colorize("Share", fmt.Sprintf("Share: %s\n", shareURL))
return msg
} | [
"func",
"(",
"s",
"shareMesssage",
")",
"String",
"(",
")",
"string",
"{",
"msg",
":=",
"console",
".",
"Colorize",
"(",
"\"URL\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"URL: %s\\n\"",
",",
"\\n",
")",
")",
"\n",
"s",
".",
"ObjectURL",
"\n",
"msg",
"+=... | // String - Themefied string message for console printing. | [
"String",
"-",
"Themefied",
"string",
"message",
"for",
"console",
"printing",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L62-L77 | train |
minio/mc | cmd/share.go | JSON | func (s shareMesssage) JSON() string {
s.Status = "success"
shareMessageBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Failed to marshal into JSON.")
// JSON encoding escapes ampersand into its unicode character
// which is not usable directly for share and fails with cloud
// storage. convert them back so that they are usable.
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1)
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003c"), []byte("<"), -1)
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003e"), []byte(">"), -1)
return string(shareMessageBytes)
} | go | func (s shareMesssage) JSON() string {
s.Status = "success"
shareMessageBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Failed to marshal into JSON.")
// JSON encoding escapes ampersand into its unicode character
// which is not usable directly for share and fails with cloud
// storage. convert them back so that they are usable.
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1)
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003c"), []byte("<"), -1)
shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003e"), []byte(">"), -1)
return string(shareMessageBytes)
} | [
"func",
"(",
"s",
"shareMesssage",
")",
"JSON",
"(",
")",
"string",
"{",
"s",
".",
"Status",
"=",
"\"success\"",
"\n",
"shareMessageBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"s",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
... | // JSON - JSONified message for scripting. | [
"JSON",
"-",
"JSONified",
"message",
"for",
"scripting",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L80-L93 | train |
minio/mc | cmd/share.go | shareSetColor | func shareSetColor() {
// Additional command speific theme customization.
console.SetColor("URL", color.New(color.Bold))
console.SetColor("Expire", color.New(color.FgCyan))
console.SetColor("Content-type", color.New(color.FgBlue))
console.SetColor("Share", color.New(color.FgGreen))
console.SetColor("File", color.New(color.FgRed, color.Bold))
} | go | func shareSetColor() {
// Additional command speific theme customization.
console.SetColor("URL", color.New(color.Bold))
console.SetColor("Expire", color.New(color.FgCyan))
console.SetColor("Content-type", color.New(color.FgBlue))
console.SetColor("Share", color.New(color.FgGreen))
console.SetColor("File", color.New(color.FgRed, color.Bold))
} | [
"func",
"shareSetColor",
"(",
")",
"{",
"console",
".",
"SetColor",
"(",
"\"URL\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"Bold",
")",
")",
"\n",
"console",
".",
"SetColor",
"(",
"\"Expire\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgCy... | // shareSetColor sets colors share sub-commands. | [
"shareSetColor",
"sets",
"colors",
"share",
"sub",
"-",
"commands",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L96-L103 | train |
minio/mc | cmd/share.go | getShareDir | func getShareDir() (string, *probe.Error) {
configDir, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
sharedURLsDataDir := filepath.Join(configDir, globalSharedURLsDataDir)
return sharedURLsDataDir, nil
} | go | func getShareDir() (string, *probe.Error) {
configDir, err := getMcConfigDir()
if err != nil {
return "", err.Trace()
}
sharedURLsDataDir := filepath.Join(configDir, globalSharedURLsDataDir)
return sharedURLsDataDir, nil
} | [
"func",
"getShareDir",
"(",
")",
"(",
"string",
",",
"*",
"probe",
".",
"Error",
")",
"{",
"configDir",
",",
"err",
":=",
"getMcConfigDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
".",
"Trace",
"(",
")",
"\n",
... | // Get share dir name. | [
"Get",
"share",
"dir",
"name",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L106-L114 | train |
minio/mc | cmd/share.go | isShareDirExists | func isShareDirExists() bool {
if _, e := os.Stat(mustGetShareDir()); e != nil {
return false
}
return true
} | go | func isShareDirExists() bool {
if _, e := os.Stat(mustGetShareDir()); e != nil {
return false
}
return true
} | [
"func",
"isShareDirExists",
"(",
")",
"bool",
"{",
"if",
"_",
",",
"e",
":=",
"os",
".",
"Stat",
"(",
"mustGetShareDir",
"(",
")",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Check if the share dir exists. | [
"Check",
"if",
"the",
"share",
"dir",
"exists",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L124-L129 | train |
minio/mc | cmd/share.go | createShareDir | func createShareDir() *probe.Error {
if e := os.MkdirAll(mustGetShareDir(), 0700); e != nil {
return probe.NewError(e)
}
return nil
} | go | func createShareDir() *probe.Error {
if e := os.MkdirAll(mustGetShareDir(), 0700); e != nil {
return probe.NewError(e)
}
return nil
} | [
"func",
"createShareDir",
"(",
")",
"*",
"probe",
".",
"Error",
"{",
"if",
"e",
":=",
"os",
".",
"MkdirAll",
"(",
"mustGetShareDir",
"(",
")",
",",
"0700",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"probe",
".",
"NewError",
"(",
"e",
")",
"\n",
... | // Create config share dir. | [
"Create",
"config",
"share",
"dir",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L132-L137 | train |
minio/mc | cmd/share.go | isShareUploadsExists | func isShareUploadsExists() bool {
if _, e := os.Stat(getShareUploadsFile()); e != nil {
return false
}
return true
} | go | func isShareUploadsExists() bool {
if _, e := os.Stat(getShareUploadsFile()); e != nil {
return false
}
return true
} | [
"func",
"isShareUploadsExists",
"(",
")",
"bool",
"{",
"if",
"_",
",",
"e",
":=",
"os",
".",
"Stat",
"(",
"getShareUploadsFile",
"(",
")",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Check if share uploads file exists?. | [
"Check",
"if",
"share",
"uploads",
"file",
"exists?",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L150-L155 | train |
minio/mc | cmd/share.go | isShareDownloadsExists | func isShareDownloadsExists() bool {
if _, e := os.Stat(getShareDownloadsFile()); e != nil {
return false
}
return true
} | go | func isShareDownloadsExists() bool {
if _, e := os.Stat(getShareDownloadsFile()); e != nil {
return false
}
return true
} | [
"func",
"isShareDownloadsExists",
"(",
")",
"bool",
"{",
"if",
"_",
",",
"e",
":=",
"os",
".",
"Stat",
"(",
"getShareDownloadsFile",
"(",
")",
")",
";",
"e",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Check if share downloads file exists?. | [
"Check",
"if",
"share",
"downloads",
"file",
"exists?",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L158-L163 | train |
minio/mc | cmd/share.go | initShareConfig | func initShareConfig() {
// Share directory.
if !isShareDirExists() {
fatalIf(createShareDir().Trace(mustGetShareDir()),
"Failed to create share `"+mustGetShareDir()+"` folder.")
if !globalQuiet && !globalJSON {
console.Infof("Successfully created `%s`.\n", mustGetShareDir())
}
}
// Uploads share file.
if !isShareUploadsExists() {
fatalIf(initShareUploadsFile().Trace(getShareUploadsFile()),
"Failed to initialize share uploads `"+getShareUploadsFile()+"` file.")
if !globalQuiet && !globalJSON {
console.Infof("Initialized share uploads `%s` file.\n", getShareUploadsFile())
}
}
// Downloads share file.
if !isShareDownloadsExists() {
fatalIf(initShareDownloadsFile().Trace(getShareDownloadsFile()),
"Failed to initialize share downloads `"+getShareDownloadsFile()+"` file.")
if !globalQuiet && !globalJSON {
console.Infof("Initialized share downloads `%s` file.\n", getShareDownloadsFile())
}
}
} | go | func initShareConfig() {
// Share directory.
if !isShareDirExists() {
fatalIf(createShareDir().Trace(mustGetShareDir()),
"Failed to create share `"+mustGetShareDir()+"` folder.")
if !globalQuiet && !globalJSON {
console.Infof("Successfully created `%s`.\n", mustGetShareDir())
}
}
// Uploads share file.
if !isShareUploadsExists() {
fatalIf(initShareUploadsFile().Trace(getShareUploadsFile()),
"Failed to initialize share uploads `"+getShareUploadsFile()+"` file.")
if !globalQuiet && !globalJSON {
console.Infof("Initialized share uploads `%s` file.\n", getShareUploadsFile())
}
}
// Downloads share file.
if !isShareDownloadsExists() {
fatalIf(initShareDownloadsFile().Trace(getShareDownloadsFile()),
"Failed to initialize share downloads `"+getShareDownloadsFile()+"` file.")
if !globalQuiet && !globalJSON {
console.Infof("Initialized share downloads `%s` file.\n", getShareDownloadsFile())
}
}
} | [
"func",
"initShareConfig",
"(",
")",
"{",
"if",
"!",
"isShareDirExists",
"(",
")",
"{",
"fatalIf",
"(",
"createShareDir",
"(",
")",
".",
"Trace",
"(",
"mustGetShareDir",
"(",
")",
")",
",",
"\"Failed to create share `\"",
"+",
"mustGetShareDir",
"(",
")",
"+... | // Initialize share directory, if not done already. | [
"Initialize",
"share",
"directory",
"if",
"not",
"done",
"already",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/share.go#L176-L203 | train |
minio/mc | pkg/console/themes.go | SetColor | func SetColor(tag string, cl *color.Color) {
privateMutex.Lock()
defer privateMutex.Unlock()
// add new theme
Theme[tag] = cl
} | go | func SetColor(tag string, cl *color.Color) {
privateMutex.Lock()
defer privateMutex.Unlock()
// add new theme
Theme[tag] = cl
} | [
"func",
"SetColor",
"(",
"tag",
"string",
",",
"cl",
"*",
"color",
".",
"Color",
")",
"{",
"privateMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"privateMutex",
".",
"Unlock",
"(",
")",
"\n",
"Theme",
"[",
"tag",
"]",
"=",
"cl",
"\n",
"}"
] | // SetColor sets a color for a particular tag. | [
"SetColor",
"sets",
"a",
"color",
"for",
"a",
"particular",
"tag",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/console/themes.go#L49-L54 | train |
minio/mc | cmd/watch-main.go | checkWatchSyntax | func checkWatchSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "watch", 1) // last argument is exit code
}
} | go | func checkWatchSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
cli.ShowCommandHelpAndExit(ctx, "watch", 1) // last argument is exit code
}
} | [
"func",
"checkWatchSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"1",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"watch\"",
",",
"1",
")",
"\n",
"}",
"\n",
... | // checkWatchSyntax - validate all the passed arguments | [
"checkWatchSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/watch-main.go#L90-L94 | train |
minio/mc | cmd/admin-config-get.go | checkAdminConfigGetSyntax | func checkAdminConfigGetSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "get", 1) // last argument is exit code
}
} | go | func checkAdminConfigGetSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "get", 1) // last argument is exit code
}
} | [
"func",
"checkAdminConfigGetSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"2",
"{",
"cli",
".",
"ShowCommandHel... | // checkAdminConfigGetSyntax - validate all the passed arguments | [
"checkAdminConfigGetSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-config-get.go#L71-L75 | train |
minio/mc | cmd/admin-credential.go | checkAdminCredsSyntax | func checkAdminCredsSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, credsCmdName, 1) // last argument is exit code
}
} | go | func checkAdminCredsSyntax(ctx *cli.Context) {
if len(ctx.Args()) != 3 {
cli.ShowCommandHelpAndExit(ctx, credsCmdName, 1) // last argument is exit code
}
} | [
"func",
"checkAdminCredsSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"!=",
"3",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"credsCmdName",
",",
"1",
")",
"\n",
"}",
... | // checkAdminCredsSyntax - validate all the passed arguments | [
"checkAdminCredsSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-credential.go#L52-L56 | train |
minio/mc | cmd/admin-service-restart.go | JSON | func (s serviceRestartCommand) JSON() string {
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serviceRestartJSONBytes)
} | go | func (s serviceRestartCommand) JSON() string {
serviceRestartJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(serviceRestartJSONBytes)
} | [
"func",
"(",
"s",
"serviceRestartCommand",
")",
"JSON",
"(",
")",
"string",
"{",
"serviceRestartJSONBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"s",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
"probe",
".",
"NewError",
"(",
"e",
... | // JSON jsonified service restart command message. | [
"JSON",
"jsonified",
"service",
"restart",
"command",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-service-restart.go#L64-L69 | train |
minio/mc | cmd/admin-service-restart.go | String | func (s serviceRestartMessage) String() string {
if s.Err == nil {
return console.Colorize("ServiceRestart", "Restarted `"+s.ServerURL+"` successfully.")
}
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
} | go | func (s serviceRestartMessage) String() string {
if s.Err == nil {
return console.Colorize("ServiceRestart", "Restarted `"+s.ServerURL+"` successfully.")
}
return console.Colorize("FailedServiceRestart", "Failed to restart `"+s.ServerURL+"`. error: "+s.Err.Error())
} | [
"func",
"(",
"s",
"serviceRestartMessage",
")",
"String",
"(",
")",
"string",
"{",
"if",
"s",
".",
"Err",
"==",
"nil",
"{",
"return",
"console",
".",
"Colorize",
"(",
"\"ServiceRestart\"",
",",
"\"Restarted `\"",
"+",
"s",
".",
"ServerURL",
"+",
"\"` succe... | // String colorized service restart message. | [
"String",
"colorized",
"service",
"restart",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-service-restart.go#L79-L84 | train |
minio/mc | cmd/admin-service-restart.go | checkAdminServiceRestartSyntax | func checkAdminServiceRestartSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "restart", 1) // last argument is exit code
}
} | go | func checkAdminServiceRestartSyntax(ctx *cli.Context) {
if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
cli.ShowCommandHelpAndExit(ctx, "restart", 1) // last argument is exit code
}
} | [
"func",
"checkAdminServiceRestartSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
"==",
"0",
"||",
"len",
"(",
"ctx",
".",
"Args",
"(",
")",
")",
">",
"2",
"{",
"cli",
".",
"ShowComma... | // checkAdminServiceRestartSyntax - validate all the passed arguments | [
"checkAdminServiceRestartSyntax",
"-",
"validate",
"all",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-service-restart.go#L95-L99 | train |
minio/mc | cmd/find-main.go | checkFindSyntax | func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
args := ctx.Args()
if !args.Present() {
args = []string{"./"} // No args just default to present directory.
} else if args.Get(0) == "." {
args[0] = "./" // If the arg is '.' treat it as './'.
}
for _, arg := range args {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
}
}
// Extract input URLs and validate.
for _, url := range args {
_, _, err := url2Stat(url, false, encKeyDB)
if err != nil && !isURLPrefixExists(url, false) {
// Bucket name empty is a valid error for 'find myminio' unless we are using watch, treat it as such.
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !ctx.Bool("watch") {
continue
}
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
} | go | func checkFindSyntax(ctx *cli.Context, encKeyDB map[string][]prefixSSEPair) {
args := ctx.Args()
if !args.Present() {
args = []string{"./"} // No args just default to present directory.
} else if args.Get(0) == "." {
args[0] = "./" // If the arg is '.' treat it as './'.
}
for _, arg := range args {
if strings.TrimSpace(arg) == "" {
fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
}
}
// Extract input URLs and validate.
for _, url := range args {
_, _, err := url2Stat(url, false, encKeyDB)
if err != nil && !isURLPrefixExists(url, false) {
// Bucket name empty is a valid error for 'find myminio' unless we are using watch, treat it as such.
if _, ok := err.ToGoError().(BucketNameEmpty); ok && !ctx.Bool("watch") {
continue
}
fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
}
}
} | [
"func",
"checkFindSyntax",
"(",
"ctx",
"*",
"cli",
".",
"Context",
",",
"encKeyDB",
"map",
"[",
"string",
"]",
"[",
"]",
"prefixSSEPair",
")",
"{",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"if",
"!",
"args",
".",
"Present",
"(",
")",
"{",
... | // checkFindSyntax - validate the passed arguments | [
"checkFindSyntax",
"-",
"validate",
"the",
"passed",
"arguments"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/find-main.go#L158-L183 | train |
minio/mc | cmd/find-main.go | mainFind | func mainFind(ctx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("Find", color.New(color.FgGreen, color.Bold))
console.SetColor("FindExecErr", color.New(color.FgRed, color.Italic, color.Bold))
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
checkFindSyntax(ctx, encKeyDB)
args := ctx.Args()
if !args.Present() {
args = []string{"./"} // Not args present default to present directory.
} else if args.Get(0) == "." {
args[0] = "./" // If the arg is '.' treat it as './'.
}
clnt, err := newClient(args[0])
fatalIf(err.Trace(args...), "Unable to initialize `"+args[0]+"`.")
var olderThan, newerThan string
if ctx.String("older-than") != "" {
olderThan = ctx.String("older-than")
}
if ctx.String("newer-than") != "" {
newerThan = ctx.String("newer-than")
}
// Use 'e' to indicate Go error, this is a convention followed in `mc`. For probe.Error we call it
// 'err' and regular Go error is called as 'e'.
var e error
var largerSize, smallerSize uint64
if ctx.String("larger") != "" {
largerSize, e = humanize.ParseBytes(ctx.String("larger"))
fatalIf(probe.NewError(e).Trace(ctx.String("larger")), "Unable to parse input bytes.")
}
if ctx.String("smaller") != "" {
smallerSize, e = humanize.ParseBytes(ctx.String("smaller"))
fatalIf(probe.NewError(e).Trace(ctx.String("smaller")), "Unable to parse input bytes.")
}
targetAlias, _, hostCfg, err := expandAlias(args[0])
fatalIf(err.Trace(args[0]), "Unable to expand alias.")
var targetFullURL string
if hostCfg != nil {
targetFullURL = hostCfg.URL
}
return doFind(&findContext{
Context: ctx,
maxDepth: ctx.Uint("maxdepth"),
execCmd: ctx.String("exec"),
printFmt: ctx.String("print"),
namePattern: ctx.String("name"),
pathPattern: ctx.String("path"),
regexPattern: ctx.String("regex"),
ignorePattern: ctx.String("ignore"),
olderThan: olderThan,
newerThan: newerThan,
largerSize: largerSize,
smallerSize: smallerSize,
watch: ctx.Bool("watch"),
targetAlias: targetAlias,
targetURL: args[0],
targetFullURL: targetFullURL,
clnt: clnt,
})
} | go | func mainFind(ctx *cli.Context) error {
// Additional command specific theme customization.
console.SetColor("Find", color.New(color.FgGreen, color.Bold))
console.SetColor("FindExecErr", color.New(color.FgRed, color.Italic, color.Bold))
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
checkFindSyntax(ctx, encKeyDB)
args := ctx.Args()
if !args.Present() {
args = []string{"./"} // Not args present default to present directory.
} else if args.Get(0) == "." {
args[0] = "./" // If the arg is '.' treat it as './'.
}
clnt, err := newClient(args[0])
fatalIf(err.Trace(args...), "Unable to initialize `"+args[0]+"`.")
var olderThan, newerThan string
if ctx.String("older-than") != "" {
olderThan = ctx.String("older-than")
}
if ctx.String("newer-than") != "" {
newerThan = ctx.String("newer-than")
}
// Use 'e' to indicate Go error, this is a convention followed in `mc`. For probe.Error we call it
// 'err' and regular Go error is called as 'e'.
var e error
var largerSize, smallerSize uint64
if ctx.String("larger") != "" {
largerSize, e = humanize.ParseBytes(ctx.String("larger"))
fatalIf(probe.NewError(e).Trace(ctx.String("larger")), "Unable to parse input bytes.")
}
if ctx.String("smaller") != "" {
smallerSize, e = humanize.ParseBytes(ctx.String("smaller"))
fatalIf(probe.NewError(e).Trace(ctx.String("smaller")), "Unable to parse input bytes.")
}
targetAlias, _, hostCfg, err := expandAlias(args[0])
fatalIf(err.Trace(args[0]), "Unable to expand alias.")
var targetFullURL string
if hostCfg != nil {
targetFullURL = hostCfg.URL
}
return doFind(&findContext{
Context: ctx,
maxDepth: ctx.Uint("maxdepth"),
execCmd: ctx.String("exec"),
printFmt: ctx.String("print"),
namePattern: ctx.String("name"),
pathPattern: ctx.String("path"),
regexPattern: ctx.String("regex"),
ignorePattern: ctx.String("ignore"),
olderThan: olderThan,
newerThan: newerThan,
largerSize: largerSize,
smallerSize: smallerSize,
watch: ctx.Bool("watch"),
targetAlias: targetAlias,
targetURL: args[0],
targetFullURL: targetFullURL,
clnt: clnt,
})
} | [
"func",
"mainFind",
"(",
"ctx",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"console",
".",
"SetColor",
"(",
"\"Find\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
",",
"color",
".",
"Bold",
")",
")",
"\n",
"console",
".",
"SetColor",... | // mainFind - handler for mc find commands | [
"mainFind",
"-",
"handler",
"for",
"mc",
"find",
"commands"
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/find-main.go#L211-L283 | train |
minio/mc | cmd/policy-main.go | JSON | func (s policyRules) JSON() string {
policyJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(policyJSONBytes)
} | go | func (s policyRules) JSON() string {
policyJSONBytes, e := json.MarshalIndent(s, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(policyJSONBytes)
} | [
"func",
"(",
"s",
"policyRules",
")",
"JSON",
"(",
")",
"string",
"{",
"policyJSONBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"s",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
"probe",
".",
"NewError",
"(",
"e",
")",
",",
"\... | // JSON jsonified policy message. | [
"JSON",
"jsonified",
"policy",
"message",
"."
] | f0f156aca82e451c80b05d5be8eb01a04fee29dd | https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/policy-main.go#L108-L112 | train |
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",
"if",
"argsLength",
">",
"2",
"{",
"cli",
".",
"ShowCommandHelpAndExit",
"(",
"ctx",
",",
"\"policy\... | // 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",
"=",
"\"none\"",
"\n",
"case",
"accessDownload",
":",
"policy",
"=",
"\"readonly\"",
"\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",
... | // 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",
".",
"Trac... | // 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",
"!=",
"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"... | // 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... | // 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",
")",
"{",
"targetURL",
":=",
"args",
".",
"First",
"(",
")",
"\n",
"policies",
",",
"err",
":=",
"doGetAccessRules",
"(",
"targetURL",
")",
"\n",
"if",
"err",
"!=",
... | // 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",
")",
")",
"... | // 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",
... | // 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",
"switch",
"ta... | // 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",
"... | // 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",
".",
"ShowCommandHelpAn... | // 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",
"=",
"\"success\"",
"\n",
"eventRemoveMessageJSONBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"u",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fata... | // 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",
... | // 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"... | // 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",
".",
"refr... | // 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",
".",
... | // 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",
".... | // 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",
"(",
"\"Mirror\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"`%s` -> `%s`\"",
",",
"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",
"=",
"\"success\"",
"\n",
"mirrorMessageBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"m",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
"(",
... | // 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",
"targetWithAlias",
":=",
"filepath",
".",
"Join",
"("... | // 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",
"{",
"return",
"sURLs",
".... | // 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",
")",
"{",
"mj",
".",
"status",
".",
"Start",
"(",
")",
"\n",
"defer",
"mj",
".",
"status",
".",
"Finish",
"(",
")",
"\n",
"for",
"sURLs",
":=",... | // 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",
"stopParallel",
":=",
"func... | // 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",
"if",
"mj",
".",
"isWatch",
"{",
"wg",
".",
"... | // 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",
... | // 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",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"checkMirrorSyntax",
"(",
"ctx"... | // 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",
"."... | // 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",
"(",
"\"MC_ENCRYPT\"",
")",
"\n",
"if",
... | // 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",
"{",
"_",
",",
"targetContent",
",",
"err",
":=",
"url2Stat",
"(",
"aliasURL",
",",
"false",
",",
"keys",
")",
"\n",
"if... | // 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",
... | 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",
"*",
"p... | // 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",
"... | // 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",
... | // 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",
".",... | // 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",
",",
... | // 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",
"[",
... | // 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",
":=",
... | // 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",
".",
... | // 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",... | // 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",
"{",
... | // 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",
".",
"ShowCommandHel... | // 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",
"console",
".",
"SetColor",
"(",
"\"PolicyMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
... | // 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",
... | // 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",
"{",
"checkAdminProfileStartSyntax",
"(",
"ctx",
")",
"\n",
"args",
":=",
"ctx",
".",
"Args",
"(",
")",
"\n",
"aliasedURL",
":=",
"args",
".",
"Get",
"(",
"0",
")",
... | // 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",
")",
... | // 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",
"==",
... | // 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",
"\"s3v2\"",
",",
"\"s3v4\"",
":",
"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"... | // 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",
",",
"\"remove\"",
",",
"1",
")",
"\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",
"console",
".",
"SetColor",
"(",
"\"UserMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
... | // 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",
",",
"\"list\"",
",",
"1",
")",
"\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",
"console",
".",
"SetColor",
"(",
"\"UserMessage\"",
",",
"color",
".",
"New",
"(",
"color",
".",
"FgGreen",
")",
")",... | // 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",
"(",
")"... | // 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",
"(",
"targetUR... | // 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",
"{",
"encKeyDB",
",",
"err",
":=",
"getEncKeys",
"(",
"ctx",
")",
"\n",
"fatalIf",
"(",
"err",
",",
"\"Unable to parse encryption keys.\"",
")",
"\n",
"checkShareDownloadSyntax",
... | // 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",
",",
"\"upload\"",... | // 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",... | // 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",
"{",
"shareDB",
":=",
"newShareDBV1",
"(",
")",
"\n",
"if",
"err",
":=",
... | // 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",
")",
"\... | // 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",
"{",
"checkShareUploadSyntax",
"(",
"ctx",
")",
"\n",
"initShareConfig",
"(",
")",
"\n",
"shareSetColor",
"(",
")",
"\n",
"isRecursive",
":=",
"ctx",
".",
"Bool",
"(",
"\"recu... | // 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",
",",
"\"add\"",
",",
"1",
")",
"\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",
"=",
"\"success\"",
"\n",
"eventAddMessageJSONBytes",
",",
"e",
":=",
"json",
".",
"MarshalIndent",
"(",
"u",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"fatalIf",
... | // 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",
".",
"ShowCommandH... | // 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",
"(",
"\"Config version '%s' does not ma... | // 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",... | // 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",
"\"mc\"",
",",
"\"-install\"",
",",
"\"-uninstall\"",
":",
"mainComplete",
"(",
")",
"\n",
"return",
... | // 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",
"(",
"\"`%s` is not a mc command. See `mc --help`.\"",
",",
"command",
")",
"\n",
"closestCommands",
":=",
"findClosestComman... | // 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",
"(",
")",
"{",
"loadMcConfig",
"=",
"loadMcConfigFactory",
"(",
")",
"\n",
"config",
",",
"err",
":=",
"loadMcConfig",
"(",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
"mustGetMcConfigPath",
"(",
")",
")",
",",
"\"Unable to ... | // 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",
"(",
")",
"{",
"if",
"!",
"isMcConfigExists",
"(",
")",
"{",
"err",
":=",
"saveMcConfig",
"(",
"newMcConfig",
"(",
")",
")",
"\n",
"fatalIf",
"(",
"err",
".",
"Trace",
"(",
")",
",",
"\"Unable to save new mc config.\"",
")",
"\n",
"if",... | // 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... | // 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",
"totalColumns",
":=",
"len",
"(",
"contents",
")",
"\n",
"if",
"len",
"(",
"t",
".",
"cols",
")",... | // 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",
"(",
... | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.