repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
minio/mc
pkg/colorjson/decode.go
addErrorContext
func (d *decodeState) addErrorContext(err error) error { if d.errorContext.Struct != "" || d.errorContext.Field != "" { switch err := err.(type) { case *UnmarshalTypeError: err.Struct = d.errorContext.Struct err.Field = d.errorContext.Field return err } } return err }
go
func (d *decodeState) addErrorContext(err error) error { if d.errorContext.Struct != "" || d.errorContext.Field != "" { switch err := err.(type) { case *UnmarshalTypeError: err.Struct = d.errorContext.Struct err.Field = d.errorContext.Field return err } } return err }
[ "func", "(", "d", "*", "decodeState", ")", "addErrorContext", "(", "err", "error", ")", "error", "{", "if", "d", ".", "errorContext", ".", "Struct", "!=", "\"", "\"", "||", "d", ".", "errorContext", ".", "Field", "!=", "\"", "\"", "{", "switch", "err", ":=", "err", ".", "(", "type", ")", "{", "case", "*", "UnmarshalTypeError", ":", "err", ".", "Struct", "=", "d", ".", "errorContext", ".", "Struct", "\n", "err", ".", "Field", "=", "d", ".", "errorContext", ".", "Field", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// addErrorContext returns a new error enhanced with information from d.errorContext
[ "addErrorContext", "returns", "a", "new", "error", "enhanced", "with", "information", "from", "d", ".", "errorContext" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/decode.go#L318-L328
train
minio/mc
pkg/colorjson/decode.go
skip
func (d *decodeState) skip() { s, data, i := &d.scan, d.data, d.off depth := len(s.parseState) for { op := s.step(s, data[i]) i++ if len(s.parseState) < depth { d.off = i d.opcode = op return } } }
go
func (d *decodeState) skip() { s, data, i := &d.scan, d.data, d.off depth := len(s.parseState) for { op := s.step(s, data[i]) i++ if len(s.parseState) < depth { d.off = i d.opcode = op return } } }
[ "func", "(", "d", "*", "decodeState", ")", "skip", "(", ")", "{", "s", ",", "data", ",", "i", ":=", "&", "d", ".", "scan", ",", "d", ".", "data", ",", "d", ".", "off", "\n", "depth", ":=", "len", "(", "s", ".", "parseState", ")", "\n", "for", "{", "op", ":=", "s", ".", "step", "(", "s", ",", "data", "[", "i", "]", ")", "\n", "i", "++", "\n", "if", "len", "(", "s", ".", "parseState", ")", "<", "depth", "{", "d", ".", "off", "=", "i", "\n", "d", ".", "opcode", "=", "op", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// skip scans to the end of what was started.
[ "skip", "scans", "to", "the", "end", "of", "what", "was", "started", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/decode.go#L331-L343
train
minio/mc
cmd/pipe-main.go
checkPipeSyntax
func checkPipeSyntax(ctx *cli.Context) { if len(ctx.Args()) > 1 { cli.ShowCommandHelpAndExit(ctx, "pipe", 1) // last argument is exit code. } }
go
func checkPipeSyntax(ctx *cli.Context) { if len(ctx.Args()) > 1 { cli.ShowCommandHelpAndExit(ctx, "pipe", 1) // last argument is exit code. } }
[ "func", "checkPipeSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "1", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code.", "\n", "}", "\n", "}" ]
// check pipe input arguments.
[ "check", "pipe", "input", "arguments", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pipe-main.go#L95-L99
train
minio/mc
cmd/pipe-main.go
mainPipe
func mainPipe(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // validate pipe input arguments. checkPipeSyntax(ctx) if len(ctx.Args()) == 0 { err = pipe("", nil) fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.") } else { // extract URLs. URLs := ctx.Args() err = pipe(URLs[0], encKeyDB) fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.") } // Done. return nil }
go
func mainPipe(ctx *cli.Context) error { // Parse encryption keys per command. encKeyDB, err := getEncKeys(ctx) fatalIf(err, "Unable to parse encryption keys.") // validate pipe input arguments. checkPipeSyntax(ctx) if len(ctx.Args()) == 0 { err = pipe("", nil) fatalIf(err.Trace("stdout"), "Unable to write to one or more targets.") } else { // extract URLs. URLs := ctx.Args() err = pipe(URLs[0], encKeyDB) fatalIf(err.Trace(URLs[0]), "Unable to write to one or more targets.") } // Done. return nil }
[ "func", "mainPipe", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// Parse encryption keys per command.", "encKeyDB", ",", "err", ":=", "getEncKeys", "(", "ctx", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "// validate pipe input arguments.", "checkPipeSyntax", "(", "ctx", ")", "\n\n", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "{", "err", "=", "pipe", "(", "\"", "\"", ",", "nil", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "}", "else", "{", "// extract URLs.", "URLs", ":=", "ctx", ".", "Args", "(", ")", "\n", "err", "=", "pipe", "(", "URLs", "[", "0", "]", ",", "encKeyDB", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "URLs", "[", "0", "]", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Done.", "return", "nil", "\n", "}" ]
// mainPipe is the main entry point for pipe command.
[ "mainPipe", "is", "the", "main", "entry", "point", "for", "pipe", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/pipe-main.go#L102-L122
train
minio/mc
cmd/certs.go
getCertsDir
func getCertsDir() (string, *probe.Error) { p, err := getMcConfigDir() if err != nil { return "", err.Trace() } return filepath.Join(p, globalMCCertsDir), nil }
go
func getCertsDir() (string, *probe.Error) { p, err := getMcConfigDir() if err != nil { return "", err.Trace() } return filepath.Join(p, globalMCCertsDir), nil }
[ "func", "getCertsDir", "(", ")", "(", "string", ",", "*", "probe", ".", "Error", ")", "{", "p", ",", "err", ":=", "getMcConfigDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", ".", "Trace", "(", ")", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "p", ",", "globalMCCertsDir", ")", ",", "nil", "\n", "}" ]
// getCertsDir - return the full path of certs dir
[ "getCertsDir", "-", "return", "the", "full", "path", "of", "certs", "dir" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L29-L35
train
minio/mc
cmd/certs.go
isCertsDirExists
func isCertsDirExists() bool { certsDir, err := getCertsDir() fatalIf(err.Trace(), "Unable to determine certs folder.") if _, e := os.Stat(certsDir); e != nil { return false } return true }
go
func isCertsDirExists() bool { certsDir, err := getCertsDir() fatalIf(err.Trace(), "Unable to determine certs folder.") if _, e := os.Stat(certsDir); e != nil { return false } return true }
[ "func", "isCertsDirExists", "(", ")", "bool", "{", "certsDir", ",", "err", ":=", "getCertsDir", "(", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "if", "_", ",", "e", ":=", "os", ".", "Stat", "(", "certsDir", ")", ";", "e", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isCertsDirExists - verify if certs directory exists.
[ "isCertsDirExists", "-", "verify", "if", "certs", "directory", "exists", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L38-L45
train
minio/mc
cmd/certs.go
createCertsDir
func createCertsDir() *probe.Error { p, err := getCertsDir() if err != nil { return err.Trace() } if e := os.MkdirAll(p, 0700); e != nil { return probe.NewError(e) } return nil }
go
func createCertsDir() *probe.Error { p, err := getCertsDir() if err != nil { return err.Trace() } if e := os.MkdirAll(p, 0700); e != nil { return probe.NewError(e) } return nil }
[ "func", "createCertsDir", "(", ")", "*", "probe", ".", "Error", "{", "p", ",", "err", ":=", "getCertsDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", ")", "\n", "}", "\n", "if", "e", ":=", "os", ".", "MkdirAll", "(", "p", ",", "0700", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// createCertsDir - create MinIO Client certs folder
[ "createCertsDir", "-", "create", "MinIO", "Client", "certs", "folder" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L48-L57
train
minio/mc
cmd/certs.go
getCAsDir
func getCAsDir() (string, *probe.Error) { p, err := getCertsDir() if err != nil { return "", err.Trace() } return filepath.Join(p, globalMCCAsDir), nil }
go
func getCAsDir() (string, *probe.Error) { p, err := getCertsDir() if err != nil { return "", err.Trace() } return filepath.Join(p, globalMCCAsDir), nil }
[ "func", "getCAsDir", "(", ")", "(", "string", ",", "*", "probe", ".", "Error", ")", "{", "p", ",", "err", ":=", "getCertsDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", ".", "Trace", "(", ")", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "p", ",", "globalMCCAsDir", ")", ",", "nil", "\n", "}" ]
// getCAsDir - return the full path of CAs dir
[ "getCAsDir", "-", "return", "the", "full", "path", "of", "CAs", "dir" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L60-L66
train
minio/mc
cmd/certs.go
isCAsDirExists
func isCAsDirExists() bool { CAsDir, err := getCAsDir() fatalIf(err.Trace(), "Unable to determine CAs folder.") if _, e := os.Stat(CAsDir); e != nil { return false } return true }
go
func isCAsDirExists() bool { CAsDir, err := getCAsDir() fatalIf(err.Trace(), "Unable to determine CAs folder.") if _, e := os.Stat(CAsDir); e != nil { return false } return true }
[ "func", "isCAsDirExists", "(", ")", "bool", "{", "CAsDir", ",", "err", ":=", "getCAsDir", "(", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "if", "_", ",", "e", ":=", "os", ".", "Stat", "(", "CAsDir", ")", ";", "e", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isCAsDirExists - verify if CAs directory exists.
[ "isCAsDirExists", "-", "verify", "if", "CAs", "directory", "exists", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L78-L85
train
minio/mc
cmd/certs.go
createCAsDir
func createCAsDir() *probe.Error { p, err := getCAsDir() if err != nil { return err.Trace() } if e := os.MkdirAll(p, 0700); e != nil { return probe.NewError(e) } return nil }
go
func createCAsDir() *probe.Error { p, err := getCAsDir() if err != nil { return err.Trace() } if e := os.MkdirAll(p, 0700); e != nil { return probe.NewError(e) } return nil }
[ "func", "createCAsDir", "(", ")", "*", "probe", ".", "Error", "{", "p", ",", "err", ":=", "getCAsDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", ")", "\n", "}", "\n", "if", "e", ":=", "os", ".", "MkdirAll", "(", "p", ",", "0700", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// createCAsDir - create MinIO Client CAs folder
[ "createCAsDir", "-", "create", "MinIO", "Client", "CAs", "folder" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L88-L97
train
minio/mc
cmd/certs.go
mustGetCAFiles
func mustGetCAFiles() (caCerts []string) { CAsDir := mustGetCAsDir() caFiles, _ := ioutil.ReadDir(CAsDir) for _, cert := range caFiles { caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name())) } return }
go
func mustGetCAFiles() (caCerts []string) { CAsDir := mustGetCAsDir() caFiles, _ := ioutil.ReadDir(CAsDir) for _, cert := range caFiles { caCerts = append(caCerts, filepath.Join(CAsDir, cert.Name())) } return }
[ "func", "mustGetCAFiles", "(", ")", "(", "caCerts", "[", "]", "string", ")", "{", "CAsDir", ":=", "mustGetCAsDir", "(", ")", "\n", "caFiles", ",", "_", ":=", "ioutil", ".", "ReadDir", "(", "CAsDir", ")", "\n", "for", "_", ",", "cert", ":=", "range", "caFiles", "{", "caCerts", "=", "append", "(", "caCerts", ",", "filepath", ".", "Join", "(", "CAsDir", ",", "cert", ".", "Name", "(", ")", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// mustGetCAFiles - get the list of the CA certificates stored in MinIO config dir
[ "mustGetCAFiles", "-", "get", "the", "list", "of", "the", "CA", "certificates", "stored", "in", "MinIO", "config", "dir" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L100-L107
train
minio/mc
cmd/certs.go
loadRootCAs
func loadRootCAs() { caFiles := mustGetCAFiles() if len(caFiles) == 0 { return } // Get system cert pool, and empty cert pool under Windows because it is not supported globalRootCAs = mustGetSystemCertPool() // Load custom root CAs for client requests for _, caFile := range caFiles { caCert, err := ioutil.ReadFile(caFile) if err != nil { fatalIf(probe.NewError(err), "Unable to load a CA file.") } globalRootCAs.AppendCertsFromPEM(caCert) } }
go
func loadRootCAs() { caFiles := mustGetCAFiles() if len(caFiles) == 0 { return } // Get system cert pool, and empty cert pool under Windows because it is not supported globalRootCAs = mustGetSystemCertPool() // Load custom root CAs for client requests for _, caFile := range caFiles { caCert, err := ioutil.ReadFile(caFile) if err != nil { fatalIf(probe.NewError(err), "Unable to load a CA file.") } globalRootCAs.AppendCertsFromPEM(caCert) } }
[ "func", "loadRootCAs", "(", ")", "{", "caFiles", ":=", "mustGetCAFiles", "(", ")", "\n", "if", "len", "(", "caFiles", ")", "==", "0", "{", "return", "\n", "}", "\n", "// Get system cert pool, and empty cert pool under Windows because it is not supported", "globalRootCAs", "=", "mustGetSystemCertPool", "(", ")", "\n", "// Load custom root CAs for client requests", "for", "_", ",", "caFile", ":=", "range", "caFiles", "{", "caCert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "caFile", ")", "\n", "if", "err", "!=", "nil", "{", "fatalIf", "(", "probe", ".", "NewError", "(", "err", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "globalRootCAs", ".", "AppendCertsFromPEM", "(", "caCert", ")", "\n", "}", "\n", "}" ]
// loadRootCAs fetches CA files provided in MinIO config and adds them to globalRootCAs // Currently under Windows, there is no way to load system + user CAs at the same time
[ "loadRootCAs", "fetches", "CA", "files", "provided", "in", "MinIO", "config", "and", "adds", "them", "to", "globalRootCAs", "Currently", "under", "Windows", "there", "is", "no", "way", "to", "load", "system", "+", "user", "CAs", "at", "the", "same", "time" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/certs.go#L120-L135
train
minio/mc
pkg/httptracer/httptracer.go
CancelRequest
func (t RoundTripTrace) CancelRequest(req *http.Request) { transport, ok := t.Transport.(*http.Transport) if ok { transport.CancelRequest(req) } }
go
func (t RoundTripTrace) CancelRequest(req *http.Request) { transport, ok := t.Transport.(*http.Transport) if ok { transport.CancelRequest(req) } }
[ "func", "(", "t", "RoundTripTrace", ")", "CancelRequest", "(", "req", "*", "http", ".", "Request", ")", "{", "transport", ",", "ok", ":=", "t", ".", "Transport", ".", "(", "*", "http", ".", "Transport", ")", "\n", "if", "ok", "{", "transport", ".", "CancelRequest", "(", "req", ")", "\n", "}", "\n", "}" ]
// CancelRequest implements functinality to cancel an underlying request.
[ "CancelRequest", "implements", "functinality", "to", "cancel", "an", "underlying", "request", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/httptracer/httptracer.go#L40-L45
train
minio/mc
pkg/httptracer/httptracer.go
RoundTrip
func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) { timeStamp := time.Now() if t.Transport == nil { return nil, errors.New("Invalid Argument") } res, err = t.Transport.RoundTrip(req) if err != nil { return res, err } if t.Trace != nil { err = t.Trace.Request(req) if err != nil { return nil, err } err = t.Trace.Response(res) if err != nil { return nil, err } console.Debugln("Response Time: ", time.Since(timeStamp).String()+"\n") } return res, err }
go
func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) { timeStamp := time.Now() if t.Transport == nil { return nil, errors.New("Invalid Argument") } res, err = t.Transport.RoundTrip(req) if err != nil { return res, err } if t.Trace != nil { err = t.Trace.Request(req) if err != nil { return nil, err } err = t.Trace.Response(res) if err != nil { return nil, err } console.Debugln("Response Time: ", time.Since(timeStamp).String()+"\n") } return res, err }
[ "func", "(", "t", "RoundTripTrace", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "timeStamp", ":=", "time", ".", "Now", "(", ")", "\n\n", "if", "t", ".", "Transport", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "res", ",", "err", "=", "t", ".", "Transport", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "if", "t", ".", "Trace", "!=", "nil", "{", "err", "=", "t", ".", "Trace", ".", "Request", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "t", ".", "Trace", ".", "Response", "(", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "console", ".", "Debugln", "(", "\"", "\"", ",", "time", ".", "Since", "(", "timeStamp", ")", ".", "String", "(", ")", "+", "\"", "\\n", "\"", ")", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// RoundTrip executes user provided request and response hooks for each HTTP call.
[ "RoundTrip", "executes", "user", "provided", "request", "and", "response", "hooks", "for", "each", "HTTP", "call", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/httptracer/httptracer.go#L48-L73
train
minio/mc
cmd/admin-user-add-policy.go
checkAdminUserPolicySyntax
func checkAdminUserPolicySyntax(ctx *cli.Context) { if len(ctx.Args()) != 3 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code } }
go
func checkAdminUserPolicySyntax(ctx *cli.Context) { if len(ctx.Args()) != 3 { cli.ShowCommandHelpAndExit(ctx, "policy", 1) // last argument is exit code } }
[ "func", "checkAdminUserPolicySyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "!=", "3", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminUserPolicySyntax - validate all the passed arguments
[ "checkAdminUserPolicySyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-add-policy.go#L51-L55
train
minio/mc
cmd/admin-user-add-policy.go
mainAdminUserPolicy
func mainAdminUserPolicy(ctx *cli.Context) error { checkAdminUserPolicySyntax(ctx) console.SetColor("UserMessage", color.New(color.FgGreen)) // Get the alias parameter from cli args := ctx.Args() aliasedURL := args.Get(0) // Create a new MinIO Admin Client client, err := newAdminClient(aliasedURL) fatalIf(err, "Cannot get a configured admin connection.") fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(2))).Trace(args...), "Cannot set user policy for user") printMsg(userMessage{ op: "policy", AccessKey: args.Get(1), PolicyName: args.Get(2), UserStatus: "enabled", }) return nil }
go
func mainAdminUserPolicy(ctx *cli.Context) error { checkAdminUserPolicySyntax(ctx) console.SetColor("UserMessage", color.New(color.FgGreen)) // Get the alias parameter from cli args := ctx.Args() aliasedURL := args.Get(0) // Create a new MinIO Admin Client client, err := newAdminClient(aliasedURL) fatalIf(err, "Cannot get a configured admin connection.") fatalIf(probe.NewError(client.SetUserPolicy(args.Get(1), args.Get(2))).Trace(args...), "Cannot set user policy for user") printMsg(userMessage{ op: "policy", AccessKey: args.Get(1), PolicyName: args.Get(2), UserStatus: "enabled", }) return nil }
[ "func", "mainAdminUserPolicy", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "checkAdminUserPolicySyntax", "(", "ctx", ")", "\n\n", "console", ".", "SetColor", "(", "\"", "\"", ",", "color", ".", "New", "(", "color", ".", "FgGreen", ")", ")", "\n\n", "// Get the alias parameter from cli", "args", ":=", "ctx", ".", "Args", "(", ")", "\n", "aliasedURL", ":=", "args", ".", "Get", "(", "0", ")", "\n\n", "// Create a new MinIO Admin Client", "client", ",", "err", ":=", "newAdminClient", "(", "aliasedURL", ")", "\n", "fatalIf", "(", "err", ",", "\"", "\"", ")", "\n\n", "fatalIf", "(", "probe", ".", "NewError", "(", "client", ".", "SetUserPolicy", "(", "args", ".", "Get", "(", "1", ")", ",", "args", ".", "Get", "(", "2", ")", ")", ")", ".", "Trace", "(", "args", "...", ")", ",", "\"", "\"", ")", "\n\n", "printMsg", "(", "userMessage", "{", "op", ":", "\"", "\"", ",", "AccessKey", ":", "args", ".", "Get", "(", "1", ")", ",", "PolicyName", ":", "args", ".", "Get", "(", "2", ")", ",", "UserStatus", ":", "\"", "\"", ",", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// mainAdminUserPolicy is the handle for "mc admin user policy" command.
[ "mainAdminUserPolicy", "is", "the", "handle", "for", "mc", "admin", "user", "policy", "command", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-user-add-policy.go#L58-L81
train
minio/mc
cmd/admin-service-status.go
checkAdminServiceStatusSyntax
func checkAdminServiceStatusSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code } }
go
func checkAdminServiceStatusSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 { cli.ShowCommandHelpAndExit(ctx, "status", 1) // last argument is exit code } }
[ "func", "checkAdminServiceStatusSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "2", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminServiceStatusSyntax - validate all the passed arguments
[ "checkAdminServiceStatusSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-service-status.go#L93-L97
train
minio/mc
cmd/session-v8.go
String
func (s sessionV8) String() string { message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID)) message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate))) message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " "))) return message }
go
func (s sessionV8) String() string { message := console.Colorize("SessionID", fmt.Sprintf("%s -> ", s.SessionID)) message = message + console.Colorize("SessionTime", fmt.Sprintf("[%s]", s.Header.When.Local().Format(printDate))) message = message + console.Colorize("Command", fmt.Sprintf(" %s %s", s.Header.CommandType, strings.Join(s.Header.CommandArgs, " "))) return message }
[ "func", "(", "s", "sessionV8", ")", "String", "(", ")", "string", "{", "message", ":=", "console", ".", "Colorize", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "SessionID", ")", ")", "\n", "message", "=", "message", "+", "console", ".", "Colorize", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "Header", ".", "When", ".", "Local", "(", ")", ".", "Format", "(", "printDate", ")", ")", ")", "\n", "message", "=", "message", "+", "console", ".", "Colorize", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "Header", ".", "CommandType", ",", "strings", ".", "Join", "(", "s", ".", "Header", ".", "CommandArgs", ",", "\"", "\"", ")", ")", ")", "\n", "return", "message", "\n", "}" ]
// String colorized session message.
[ "String", "colorized", "session", "message", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L86-L91
train
minio/mc
cmd/session-v8.go
JSON
func (s sessionV8) JSON() string { sessionMsg := sessionMessage{ SessionID: s.SessionID, Time: s.Header.When.Local(), CommandType: s.Header.CommandType, CommandArgs: s.Header.CommandArgs, } sessionMsg.Status = "success" sessionBytes, e := json.MarshalIndent(sessionMsg, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(sessionBytes) }
go
func (s sessionV8) JSON() string { sessionMsg := sessionMessage{ SessionID: s.SessionID, Time: s.Header.When.Local(), CommandType: s.Header.CommandType, CommandArgs: s.Header.CommandArgs, } sessionMsg.Status = "success" sessionBytes, e := json.MarshalIndent(sessionMsg, "", " ") fatalIf(probe.NewError(e), "Unable to marshal into JSON.") return string(sessionBytes) }
[ "func", "(", "s", "sessionV8", ")", "JSON", "(", ")", "string", "{", "sessionMsg", ":=", "sessionMessage", "{", "SessionID", ":", "s", ".", "SessionID", ",", "Time", ":", "s", ".", "Header", ".", "When", ".", "Local", "(", ")", ",", "CommandType", ":", "s", ".", "Header", ".", "CommandType", ",", "CommandArgs", ":", "s", ".", "Header", ".", "CommandArgs", ",", "}", "\n", "sessionMsg", ".", "Status", "=", "\"", "\"", "\n", "sessionBytes", ",", "e", ":=", "json", ".", "MarshalIndent", "(", "sessionMsg", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\"", ")", "\n\n", "return", "string", "(", "sessionBytes", ")", "\n", "}" ]
// JSON jsonified session message.
[ "JSON", "jsonified", "session", "message", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L94-L106
train
minio/mc
cmd/session-v8.go
loadSessionV8
func loadSessionV8(sid string) (*sessionV8, *probe.Error) { if !isSessionDirExists() { return nil, errInvalidArgument().Trace() } sessionFile, err := getSessionFile(sid) if err != nil { return nil, err.Trace(sid) } if _, e := os.Stat(sessionFile); e != nil { return nil, probe.NewError(e) } // Initialize new session. s := &sessionV8{ Header: &sessionV8Header{ Version: globalSessionConfigVersion, }, SessionID: sid, } // Initialize session config loader. qs, e := quick.NewConfig(s.Header, nil) if e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } if e = qs.Load(sessionFile); e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } // Validate if the version matches with expected current version. sV8Header := qs.Data().(*sessionV8Header) if sV8Header.Version != globalSessionConfigVersion { msg := fmt.Sprintf("Session header version %s does not match mc session version %s.\n", sV8Header.Version, globalSessionConfigVersion) return nil, probe.NewError(errors.New(msg)).Trace(sid, sV8Header.Version) } s.mutex = new(sync.Mutex) s.Header = sV8Header sessionDataFile, err := getSessionDataFile(s.SessionID) if err != nil { return nil, err.Trace(sid, s.Header.Version) } dataFile, e := os.Open(sessionDataFile) if e != nil { return nil, probe.NewError(e) } s.DataFP = &sessionDataFP{false, dataFile} return s, nil }
go
func loadSessionV8(sid string) (*sessionV8, *probe.Error) { if !isSessionDirExists() { return nil, errInvalidArgument().Trace() } sessionFile, err := getSessionFile(sid) if err != nil { return nil, err.Trace(sid) } if _, e := os.Stat(sessionFile); e != nil { return nil, probe.NewError(e) } // Initialize new session. s := &sessionV8{ Header: &sessionV8Header{ Version: globalSessionConfigVersion, }, SessionID: sid, } // Initialize session config loader. qs, e := quick.NewConfig(s.Header, nil) if e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } if e = qs.Load(sessionFile); e != nil { return nil, probe.NewError(e).Trace(sid, s.Header.Version) } // Validate if the version matches with expected current version. sV8Header := qs.Data().(*sessionV8Header) if sV8Header.Version != globalSessionConfigVersion { msg := fmt.Sprintf("Session header version %s does not match mc session version %s.\n", sV8Header.Version, globalSessionConfigVersion) return nil, probe.NewError(errors.New(msg)).Trace(sid, sV8Header.Version) } s.mutex = new(sync.Mutex) s.Header = sV8Header sessionDataFile, err := getSessionDataFile(s.SessionID) if err != nil { return nil, err.Trace(sid, s.Header.Version) } dataFile, e := os.Open(sessionDataFile) if e != nil { return nil, probe.NewError(e) } s.DataFP = &sessionDataFP{false, dataFile} return s, nil }
[ "func", "loadSessionV8", "(", "sid", "string", ")", "(", "*", "sessionV8", ",", "*", "probe", ".", "Error", ")", "{", "if", "!", "isSessionDirExists", "(", ")", "{", "return", "nil", ",", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", "\n", "}", "\n", "sessionFile", ",", "err", ":=", "getSessionFile", "(", "sid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "sid", ")", "\n", "}", "\n\n", "if", "_", ",", "e", ":=", "os", ".", "Stat", "(", "sessionFile", ")", ";", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "// Initialize new session.", "s", ":=", "&", "sessionV8", "{", "Header", ":", "&", "sessionV8Header", "{", "Version", ":", "globalSessionConfigVersion", ",", "}", ",", "SessionID", ":", "sid", ",", "}", "\n\n", "// Initialize session config loader.", "qs", ",", "e", ":=", "quick", ".", "NewConfig", "(", "s", ".", "Header", ",", "nil", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ",", "s", ".", "Header", ".", "Version", ")", "\n", "}", "\n\n", "if", "e", "=", "qs", ".", "Load", "(", "sessionFile", ")", ";", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sid", ",", "s", ".", "Header", ".", "Version", ")", "\n", "}", "\n\n", "// Validate if the version matches with expected current version.", "sV8Header", ":=", "qs", ".", "Data", "(", ")", ".", "(", "*", "sessionV8Header", ")", "\n", "if", "sV8Header", ".", "Version", "!=", "globalSessionConfigVersion", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "sV8Header", ".", "Version", ",", "globalSessionConfigVersion", ")", "\n", "return", "nil", ",", "probe", ".", "NewError", "(", "errors", ".", "New", "(", "msg", ")", ")", ".", "Trace", "(", "sid", ",", "sV8Header", ".", "Version", ")", "\n", "}", "\n\n", "s", ".", "mutex", "=", "new", "(", "sync", ".", "Mutex", ")", "\n", "s", ".", "Header", "=", "sV8Header", "\n\n", "sessionDataFile", ",", "err", ":=", "getSessionDataFile", "(", "s", ".", "SessionID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", ".", "Trace", "(", "sid", ",", "s", ".", "Header", ".", "Version", ")", "\n", "}", "\n\n", "dataFile", ",", "e", ":=", "os", ".", "Open", "(", "sessionDataFile", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "s", ".", "DataFP", "=", "&", "sessionDataFP", "{", "false", ",", "dataFile", "}", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// loadSessionV8 - reads session file if exists and re-initiates internal variables
[ "loadSessionV8", "-", "reads", "session", "file", "if", "exists", "and", "re", "-", "initiates", "internal", "variables" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L109-L163
train
minio/mc
cmd/session-v8.go
newSessionV8
func newSessionV8() *sessionV8 { s := &sessionV8{} s.Header = &sessionV8Header{} s.Header.Version = globalSessionConfigVersion // map of command and files copied. s.Header.GlobalBoolFlags = make(map[string]bool) s.Header.GlobalIntFlags = make(map[string]int) s.Header.GlobalStringFlags = make(map[string]string) s.Header.CommandArgs = nil s.Header.CommandBoolFlags = make(map[string]bool) s.Header.CommandIntFlags = make(map[string]int) s.Header.CommandStringFlags = make(map[string]string) s.Header.UserMetaData = make(map[string]string) s.Header.When = UTCNow() s.mutex = new(sync.Mutex) s.SessionID = newRandomID(8) sessionDataFile, err := getSessionDataFile(s.SessionID) fatalIf(err.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".") dataFile, e := os.Create(sessionDataFile) fatalIf(probe.NewError(e), "Unable to create session data file \""+sessionDataFile+"\".") s.DataFP = &sessionDataFP{false, dataFile} // Capture state of global flags. s.setGlobals() return s }
go
func newSessionV8() *sessionV8 { s := &sessionV8{} s.Header = &sessionV8Header{} s.Header.Version = globalSessionConfigVersion // map of command and files copied. s.Header.GlobalBoolFlags = make(map[string]bool) s.Header.GlobalIntFlags = make(map[string]int) s.Header.GlobalStringFlags = make(map[string]string) s.Header.CommandArgs = nil s.Header.CommandBoolFlags = make(map[string]bool) s.Header.CommandIntFlags = make(map[string]int) s.Header.CommandStringFlags = make(map[string]string) s.Header.UserMetaData = make(map[string]string) s.Header.When = UTCNow() s.mutex = new(sync.Mutex) s.SessionID = newRandomID(8) sessionDataFile, err := getSessionDataFile(s.SessionID) fatalIf(err.Trace(s.SessionID), "Unable to create session data file \""+sessionDataFile+"\".") dataFile, e := os.Create(sessionDataFile) fatalIf(probe.NewError(e), "Unable to create session data file \""+sessionDataFile+"\".") s.DataFP = &sessionDataFP{false, dataFile} // Capture state of global flags. s.setGlobals() return s }
[ "func", "newSessionV8", "(", ")", "*", "sessionV8", "{", "s", ":=", "&", "sessionV8", "{", "}", "\n", "s", ".", "Header", "=", "&", "sessionV8Header", "{", "}", "\n", "s", ".", "Header", ".", "Version", "=", "globalSessionConfigVersion", "\n", "// map of command and files copied.", "s", ".", "Header", ".", "GlobalBoolFlags", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "s", ".", "Header", ".", "GlobalIntFlags", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "s", ".", "Header", ".", "GlobalStringFlags", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "s", ".", "Header", ".", "CommandArgs", "=", "nil", "\n", "s", ".", "Header", ".", "CommandBoolFlags", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "s", ".", "Header", ".", "CommandIntFlags", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "s", ".", "Header", ".", "CommandStringFlags", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "s", ".", "Header", ".", "UserMetaData", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "s", ".", "Header", ".", "When", "=", "UTCNow", "(", ")", "\n", "s", ".", "mutex", "=", "new", "(", "sync", ".", "Mutex", ")", "\n", "s", ".", "SessionID", "=", "newRandomID", "(", "8", ")", "\n\n", "sessionDataFile", ",", "err", ":=", "getSessionDataFile", "(", "s", ".", "SessionID", ")", "\n", "fatalIf", "(", "err", ".", "Trace", "(", "s", ".", "SessionID", ")", ",", "\"", "\\\"", "\"", "+", "sessionDataFile", "+", "\"", "\\\"", "\"", ")", "\n\n", "dataFile", ",", "e", ":=", "os", ".", "Create", "(", "sessionDataFile", ")", "\n", "fatalIf", "(", "probe", ".", "NewError", "(", "e", ")", ",", "\"", "\\\"", "\"", "+", "sessionDataFile", "+", "\"", "\\\"", "\"", ")", "\n\n", "s", ".", "DataFP", "=", "&", "sessionDataFP", "{", "false", ",", "dataFile", "}", "\n\n", "// Capture state of global flags.", "s", ".", "setGlobals", "(", ")", "\n\n", "return", "s", "\n", "}" ]
// newSessionV8 provides a new session.
[ "newSessionV8", "provides", "a", "new", "session", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L166-L195
train
minio/mc
cmd/session-v8.go
HasData
func (s sessionV8) HasData() bool { return s.Header.LastCopied != "" || s.Header.LastRemoved != "" }
go
func (s sessionV8) HasData() bool { return s.Header.LastCopied != "" || s.Header.LastRemoved != "" }
[ "func", "(", "s", "sessionV8", ")", "HasData", "(", ")", "bool", "{", "return", "s", ".", "Header", ".", "LastCopied", "!=", "\"", "\"", "||", "s", ".", "Header", ".", "LastRemoved", "!=", "\"", "\"", "\n", "}" ]
// HasData provides true if this is a session resume, false otherwise.
[ "HasData", "provides", "true", "if", "this", "is", "a", "session", "resume", "false", "otherwise", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L198-L200
train
minio/mc
cmd/session-v8.go
NewDataReader
func (s *sessionV8) NewDataReader() io.Reader { // DataFP is always intitialized, either via new or load functions. s.DataFP.Seek(0, os.SEEK_SET) return io.Reader(s.DataFP) }
go
func (s *sessionV8) NewDataReader() io.Reader { // DataFP is always intitialized, either via new or load functions. s.DataFP.Seek(0, os.SEEK_SET) return io.Reader(s.DataFP) }
[ "func", "(", "s", "*", "sessionV8", ")", "NewDataReader", "(", ")", "io", ".", "Reader", "{", "// DataFP is always intitialized, either via new or load functions.", "s", ".", "DataFP", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "\n", "return", "io", ".", "Reader", "(", "s", ".", "DataFP", ")", "\n", "}" ]
// NewDataReader provides reader interface to session data file.
[ "NewDataReader", "provides", "reader", "interface", "to", "session", "data", "file", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L203-L207
train
minio/mc
cmd/session-v8.go
NewDataWriter
func (s *sessionV8) NewDataWriter() io.Writer { // DataFP is always intitialized, either via new or load functions. s.DataFP.Seek(0, os.SEEK_SET) // when moving to file position 0 we want to truncate the file as well, // otherwise we'll partly overwrite existing data s.DataFP.Truncate(0) return io.Writer(s.DataFP) }
go
func (s *sessionV8) NewDataWriter() io.Writer { // DataFP is always intitialized, either via new or load functions. s.DataFP.Seek(0, os.SEEK_SET) // when moving to file position 0 we want to truncate the file as well, // otherwise we'll partly overwrite existing data s.DataFP.Truncate(0) return io.Writer(s.DataFP) }
[ "func", "(", "s", "*", "sessionV8", ")", "NewDataWriter", "(", ")", "io", ".", "Writer", "{", "// DataFP is always intitialized, either via new or load functions.", "s", ".", "DataFP", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "\n", "// when moving to file position 0 we want to truncate the file as well,", "// otherwise we'll partly overwrite existing data", "s", ".", "DataFP", ".", "Truncate", "(", "0", ")", "\n", "return", "io", ".", "Writer", "(", "s", ".", "DataFP", ")", "\n", "}" ]
// NewDataReader provides writer interface to session data file.
[ "NewDataReader", "provides", "writer", "interface", "to", "session", "data", "file", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L210-L217
train
minio/mc
cmd/session-v8.go
Save
func (s *sessionV8) Save() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() if s.DataFP.dirty { if err := s.DataFP.Sync(); err != nil { return probe.NewError(err) } s.DataFP.dirty = false } qs, e := quick.NewConfig(s.Header, nil) if e != nil { return probe.NewError(e).Trace(s.SessionID) } sessionFile, err := getSessionFile(s.SessionID) if err != nil { return err.Trace(s.SessionID) } e = qs.Save(sessionFile) if e != nil { return probe.NewError(e).Trace(sessionFile) } return nil }
go
func (s *sessionV8) Save() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() if s.DataFP.dirty { if err := s.DataFP.Sync(); err != nil { return probe.NewError(err) } s.DataFP.dirty = false } qs, e := quick.NewConfig(s.Header, nil) if e != nil { return probe.NewError(e).Trace(s.SessionID) } sessionFile, err := getSessionFile(s.SessionID) if err != nil { return err.Trace(s.SessionID) } e = qs.Save(sessionFile) if e != nil { return probe.NewError(e).Trace(sessionFile) } return nil }
[ "func", "(", "s", "*", "sessionV8", ")", "Save", "(", ")", "*", "probe", ".", "Error", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "DataFP", ".", "dirty", "{", "if", "err", ":=", "s", ".", "DataFP", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "err", ")", "\n", "}", "\n", "s", ".", "DataFP", ".", "dirty", "=", "false", "\n", "}", "\n\n", "qs", ",", "e", ":=", "quick", ".", "NewConfig", "(", "s", ".", "Header", ",", "nil", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n\n", "sessionFile", ",", "err", ":=", "getSessionFile", "(", "s", ".", "SessionID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n", "e", "=", "qs", ".", "Save", "(", "sessionFile", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sessionFile", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Save this session.
[ "Save", "this", "session", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L220-L245
train
minio/mc
cmd/session-v8.go
setGlobals
func (s *sessionV8) setGlobals() { s.Header.GlobalBoolFlags["quiet"] = globalQuiet s.Header.GlobalBoolFlags["debug"] = globalDebug s.Header.GlobalBoolFlags["json"] = globalJSON s.Header.GlobalBoolFlags["noColor"] = globalNoColor s.Header.GlobalBoolFlags["insecure"] = globalInsecure }
go
func (s *sessionV8) setGlobals() { s.Header.GlobalBoolFlags["quiet"] = globalQuiet s.Header.GlobalBoolFlags["debug"] = globalDebug s.Header.GlobalBoolFlags["json"] = globalJSON s.Header.GlobalBoolFlags["noColor"] = globalNoColor s.Header.GlobalBoolFlags["insecure"] = globalInsecure }
[ "func", "(", "s", "*", "sessionV8", ")", "setGlobals", "(", ")", "{", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "=", "globalQuiet", "\n", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "=", "globalDebug", "\n", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "=", "globalJSON", "\n", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "=", "globalNoColor", "\n", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "=", "globalInsecure", "\n", "}" ]
// setGlobals captures the state of global variables into session header. // Used by newSession.
[ "setGlobals", "captures", "the", "state", "of", "global", "variables", "into", "session", "header", ".", "Used", "by", "newSession", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L249-L255
train
minio/mc
cmd/session-v8.go
restoreGlobals
func (s sessionV8) restoreGlobals() { quiet := s.Header.GlobalBoolFlags["quiet"] debug := s.Header.GlobalBoolFlags["debug"] json := s.Header.GlobalBoolFlags["json"] noColor := s.Header.GlobalBoolFlags["noColor"] insecure := s.Header.GlobalBoolFlags["insecure"] setGlobals(quiet, debug, json, noColor, insecure) }
go
func (s sessionV8) restoreGlobals() { quiet := s.Header.GlobalBoolFlags["quiet"] debug := s.Header.GlobalBoolFlags["debug"] json := s.Header.GlobalBoolFlags["json"] noColor := s.Header.GlobalBoolFlags["noColor"] insecure := s.Header.GlobalBoolFlags["insecure"] setGlobals(quiet, debug, json, noColor, insecure) }
[ "func", "(", "s", "sessionV8", ")", "restoreGlobals", "(", ")", "{", "quiet", ":=", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "\n", "debug", ":=", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "\n", "json", ":=", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "\n", "noColor", ":=", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "\n", "insecure", ":=", "s", ".", "Header", ".", "GlobalBoolFlags", "[", "\"", "\"", "]", "\n", "setGlobals", "(", "quiet", ",", "debug", ",", "json", ",", "noColor", ",", "insecure", ")", "\n", "}" ]
// RestoreGlobals restores the state of global variables. // Used by resumeSession.
[ "RestoreGlobals", "restores", "the", "state", "of", "global", "variables", ".", "Used", "by", "resumeSession", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L259-L266
train
minio/mc
cmd/session-v8.go
isModified
func (s *sessionV8) isModified(sessionFile string) (bool, *probe.Error) { qs, e := quick.NewConfig(s.Header, nil) if e != nil { return false, probe.NewError(e).Trace(s.SessionID) } var currentHeader = &sessionV8Header{} currentQS, e := quick.LoadConfig(sessionFile, nil, currentHeader) if e != nil { // If session does not exist for the first, return modified to // be true. if os.IsNotExist(e) { return true, nil } // For all other errors return. return false, probe.NewError(e).Trace(s.SessionID) } changedFields, e := qs.DeepDiff(currentQS) if e != nil { return false, probe.NewError(e).Trace(s.SessionID) } // Returns true if there are changed entries. return len(changedFields) > 0, nil }
go
func (s *sessionV8) isModified(sessionFile string) (bool, *probe.Error) { qs, e := quick.NewConfig(s.Header, nil) if e != nil { return false, probe.NewError(e).Trace(s.SessionID) } var currentHeader = &sessionV8Header{} currentQS, e := quick.LoadConfig(sessionFile, nil, currentHeader) if e != nil { // If session does not exist for the first, return modified to // be true. if os.IsNotExist(e) { return true, nil } // For all other errors return. return false, probe.NewError(e).Trace(s.SessionID) } changedFields, e := qs.DeepDiff(currentQS) if e != nil { return false, probe.NewError(e).Trace(s.SessionID) } // Returns true if there are changed entries. return len(changedFields) > 0, nil }
[ "func", "(", "s", "*", "sessionV8", ")", "isModified", "(", "sessionFile", "string", ")", "(", "bool", ",", "*", "probe", ".", "Error", ")", "{", "qs", ",", "e", ":=", "quick", ".", "NewConfig", "(", "s", ".", "Header", ",", "nil", ")", "\n", "if", "e", "!=", "nil", "{", "return", "false", ",", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n\n", "var", "currentHeader", "=", "&", "sessionV8Header", "{", "}", "\n", "currentQS", ",", "e", ":=", "quick", ".", "LoadConfig", "(", "sessionFile", ",", "nil", ",", "currentHeader", ")", "\n", "if", "e", "!=", "nil", "{", "// If session does not exist for the first, return modified to", "// be true.", "if", "os", ".", "IsNotExist", "(", "e", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n", "// For all other errors return.", "return", "false", ",", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n\n", "changedFields", ",", "e", ":=", "qs", ".", "DeepDiff", "(", "currentQS", ")", "\n", "if", "e", "!=", "nil", "{", "return", "false", ",", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n\n", "// Returns true if there are changed entries.", "return", "len", "(", "changedFields", ")", ">", "0", ",", "nil", "\n", "}" ]
// IsModified - returns if in memory session header has changed from // its on disk value.
[ "IsModified", "-", "returns", "if", "in", "memory", "session", "header", "has", "changed", "from", "its", "on", "disk", "value", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L270-L295
train
minio/mc
cmd/session-v8.go
save
func (s *sessionV8) save() *probe.Error { sessionFile, err := getSessionFile(s.SessionID) if err != nil { return err.Trace(s.SessionID) } // Verify if sessionFile is modified. modified, err := s.isModified(sessionFile) if err != nil { return err.Trace(s.SessionID) } // Header is modified, we save it. if modified { qs, e := quick.NewConfig(s.Header, nil) if e != nil { return probe.NewError(e).Trace(s.SessionID) } // Save an return. e = qs.Save(sessionFile) if e != nil { return probe.NewError(e).Trace(sessionFile) } } return nil }
go
func (s *sessionV8) save() *probe.Error { sessionFile, err := getSessionFile(s.SessionID) if err != nil { return err.Trace(s.SessionID) } // Verify if sessionFile is modified. modified, err := s.isModified(sessionFile) if err != nil { return err.Trace(s.SessionID) } // Header is modified, we save it. if modified { qs, e := quick.NewConfig(s.Header, nil) if e != nil { return probe.NewError(e).Trace(s.SessionID) } // Save an return. e = qs.Save(sessionFile) if e != nil { return probe.NewError(e).Trace(sessionFile) } } return nil }
[ "func", "(", "s", "*", "sessionV8", ")", "save", "(", ")", "*", "probe", ".", "Error", "{", "sessionFile", ",", "err", ":=", "getSessionFile", "(", "s", ".", "SessionID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n\n", "// Verify if sessionFile is modified.", "modified", ",", "err", ":=", "s", ".", "isModified", "(", "sessionFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n", "// Header is modified, we save it.", "if", "modified", "{", "qs", ",", "e", ":=", "quick", ".", "NewConfig", "(", "s", ".", "Header", ",", "nil", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n", "// Save an return.", "e", "=", "qs", ".", "Save", "(", "sessionFile", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", ".", "Trace", "(", "sessionFile", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// save - wrapper for quick.Save and saves only if sessionHeader is // modified.
[ "save", "-", "wrapper", "for", "quick", ".", "Save", "and", "saves", "only", "if", "sessionHeader", "is", "modified", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L299-L323
train
minio/mc
cmd/session-v8.go
Close
func (s *sessionV8) Close() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() if err := s.DataFP.Close(); err != nil { return probe.NewError(err) } // Attempt to save the header if modified. return s.save() }
go
func (s *sessionV8) Close() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() if err := s.DataFP.Close(); err != nil { return probe.NewError(err) } // Attempt to save the header if modified. return s.save() }
[ "func", "(", "s", "*", "sessionV8", ")", "Close", "(", ")", "*", "probe", ".", "Error", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "s", ".", "DataFP", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "err", ")", "\n", "}", "\n\n", "// Attempt to save the header if modified.", "return", "s", ".", "save", "(", ")", "\n", "}" ]
// Close ends this session and removes all associated session files.
[ "Close", "ends", "this", "session", "and", "removes", "all", "associated", "session", "files", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L326-L336
train
minio/mc
cmd/session-v8.go
Delete
func (s *sessionV8) Delete() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() if s.DataFP != nil { name := s.DataFP.Name() // close file pro-actively before deleting // ignore any error, it could be possibly that // the file is closed already s.DataFP.Close() // Remove the data file. if e := os.Remove(name); e != nil { return probe.NewError(e) } } // Fetch the session file. sessionFile, err := getSessionFile(s.SessionID) if err != nil { return err.Trace(s.SessionID) } // Remove session file if e := os.Remove(sessionFile); e != nil { return probe.NewError(e) } // Remove session backup file if any, ignore any error. os.Remove(sessionFile + ".old") return nil }
go
func (s *sessionV8) Delete() *probe.Error { s.mutex.Lock() defer s.mutex.Unlock() if s.DataFP != nil { name := s.DataFP.Name() // close file pro-actively before deleting // ignore any error, it could be possibly that // the file is closed already s.DataFP.Close() // Remove the data file. if e := os.Remove(name); e != nil { return probe.NewError(e) } } // Fetch the session file. sessionFile, err := getSessionFile(s.SessionID) if err != nil { return err.Trace(s.SessionID) } // Remove session file if e := os.Remove(sessionFile); e != nil { return probe.NewError(e) } // Remove session backup file if any, ignore any error. os.Remove(sessionFile + ".old") return nil }
[ "func", "(", "s", "*", "sessionV8", ")", "Delete", "(", ")", "*", "probe", ".", "Error", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "DataFP", "!=", "nil", "{", "name", ":=", "s", ".", "DataFP", ".", "Name", "(", ")", "\n", "// close file pro-actively before deleting", "// ignore any error, it could be possibly that", "// the file is closed already", "s", ".", "DataFP", ".", "Close", "(", ")", "\n\n", "// Remove the data file.", "if", "e", ":=", "os", ".", "Remove", "(", "name", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "}", "\n\n", "// Fetch the session file.", "sessionFile", ",", "err", ":=", "getSessionFile", "(", "s", ".", "SessionID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ".", "Trace", "(", "s", ".", "SessionID", ")", "\n", "}", "\n\n", "// Remove session file", "if", "e", ":=", "os", ".", "Remove", "(", "sessionFile", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "// Remove session backup file if any, ignore any error.", "os", ".", "Remove", "(", "sessionFile", "+", "\"", "\"", ")", "\n\n", "return", "nil", "\n", "}" ]
// Delete removes all the session files.
[ "Delete", "removes", "all", "the", "session", "files", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L339-L371
train
minio/mc
cmd/session-v8.go
isLastFactory
func isLastFactory(lastURL string) func(string) bool { last := true // closure return func(sourceURL string) bool { if sourceURL == "" { fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.") } if lastURL == "" { return false } if last { if lastURL == sourceURL { last = false // from next call onwards we say false. } return true } return false } }
go
func isLastFactory(lastURL string) func(string) bool { last := true // closure return func(sourceURL string) bool { if sourceURL == "" { fatalIf(errInvalidArgument().Trace(), "Empty source argument passed.") } if lastURL == "" { return false } if last { if lastURL == sourceURL { last = false // from next call onwards we say false. } return true } return false } }
[ "func", "isLastFactory", "(", "lastURL", "string", ")", "func", "(", "string", ")", "bool", "{", "last", ":=", "true", "// closure", "\n", "return", "func", "(", "sourceURL", "string", ")", "bool", "{", "if", "sourceURL", "==", "\"", "\"", "{", "fatalIf", "(", "errInvalidArgument", "(", ")", ".", "Trace", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "lastURL", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n\n", "if", "last", "{", "if", "lastURL", "==", "sourceURL", "{", "last", "=", "false", "// from next call onwards we say false.", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "}" ]
// Create a factory function to simplify checking if // object was last operated on.
[ "Create", "a", "factory", "function", "to", "simplify", "checking", "if", "object", "was", "last", "operated", "on", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/session-v8.go#L381-L399
train
minio/mc
cmd/client-s3.go
AddNotificationConfig
func (c *s3Client) AddNotificationConfig(arn string, events []string, prefix, suffix string) *probe.Error { bucket, _ := c.url2BucketAndObject() // Validate total fields in ARN. fields := strings.Split(arn, ":") if len(fields) != 6 { return errInvalidArgument() } // Get any enabled notification. mb, e := c.api.GetBucketNotification(bucket) if e != nil { return probe.NewError(e) } accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5]) nc := minio.NewNotificationConfig(accountArn) // Configure events for _, event := range events { switch event { case "put": nc.AddEvents(minio.ObjectCreatedAll) case "delete": nc.AddEvents(minio.ObjectRemovedAll) case "get": nc.AddEvents(minio.ObjectAccessedAll) default: return errInvalidArgument().Trace(events...) } } if prefix != "" { nc.AddFilterPrefix(prefix) } if suffix != "" { nc.AddFilterSuffix(suffix) } switch fields[2] { case "sns": if !mb.AddTopic(nc) { return errInvalidArgument().Trace("Overlapping Topic configs") } case "sqs": if !mb.AddQueue(nc) { return errInvalidArgument().Trace("Overlapping Queue configs") } case "lambda": if !mb.AddLambda(nc) { return errInvalidArgument().Trace("Overlapping lambda configs") } default: return errInvalidArgument().Trace(fields[2]) } // Set the new bucket configuration if err := c.api.SetBucketNotification(bucket, mb); err != nil { return probe.NewError(err) } return nil }
go
func (c *s3Client) AddNotificationConfig(arn string, events []string, prefix, suffix string) *probe.Error { bucket, _ := c.url2BucketAndObject() // Validate total fields in ARN. fields := strings.Split(arn, ":") if len(fields) != 6 { return errInvalidArgument() } // Get any enabled notification. mb, e := c.api.GetBucketNotification(bucket) if e != nil { return probe.NewError(e) } accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5]) nc := minio.NewNotificationConfig(accountArn) // Configure events for _, event := range events { switch event { case "put": nc.AddEvents(minio.ObjectCreatedAll) case "delete": nc.AddEvents(minio.ObjectRemovedAll) case "get": nc.AddEvents(minio.ObjectAccessedAll) default: return errInvalidArgument().Trace(events...) } } if prefix != "" { nc.AddFilterPrefix(prefix) } if suffix != "" { nc.AddFilterSuffix(suffix) } switch fields[2] { case "sns": if !mb.AddTopic(nc) { return errInvalidArgument().Trace("Overlapping Topic configs") } case "sqs": if !mb.AddQueue(nc) { return errInvalidArgument().Trace("Overlapping Queue configs") } case "lambda": if !mb.AddLambda(nc) { return errInvalidArgument().Trace("Overlapping lambda configs") } default: return errInvalidArgument().Trace(fields[2]) } // Set the new bucket configuration if err := c.api.SetBucketNotification(bucket, mb); err != nil { return probe.NewError(err) } return nil }
[ "func", "(", "c", "*", "s3Client", ")", "AddNotificationConfig", "(", "arn", "string", ",", "events", "[", "]", "string", ",", "prefix", ",", "suffix", "string", ")", "*", "probe", ".", "Error", "{", "bucket", ",", "_", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "// Validate total fields in ARN.", "fields", ":=", "strings", ".", "Split", "(", "arn", ",", "\"", "\"", ")", "\n", "if", "len", "(", "fields", ")", "!=", "6", "{", "return", "errInvalidArgument", "(", ")", "\n", "}", "\n\n", "// Get any enabled notification.", "mb", ",", "e", ":=", "c", ".", "api", ".", "GetBucketNotification", "(", "bucket", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "accountArn", ":=", "minio", ".", "NewArn", "(", "fields", "[", "1", "]", ",", "fields", "[", "2", "]", ",", "fields", "[", "3", "]", ",", "fields", "[", "4", "]", ",", "fields", "[", "5", "]", ")", "\n", "nc", ":=", "minio", ".", "NewNotificationConfig", "(", "accountArn", ")", "\n\n", "// Configure events", "for", "_", ",", "event", ":=", "range", "events", "{", "switch", "event", "{", "case", "\"", "\"", ":", "nc", ".", "AddEvents", "(", "minio", ".", "ObjectCreatedAll", ")", "\n", "case", "\"", "\"", ":", "nc", ".", "AddEvents", "(", "minio", ".", "ObjectRemovedAll", ")", "\n", "case", "\"", "\"", ":", "nc", ".", "AddEvents", "(", "minio", ".", "ObjectAccessedAll", ")", "\n", "default", ":", "return", "errInvalidArgument", "(", ")", ".", "Trace", "(", "events", "...", ")", "\n", "}", "\n", "}", "\n", "if", "prefix", "!=", "\"", "\"", "{", "nc", ".", "AddFilterPrefix", "(", "prefix", ")", "\n", "}", "\n", "if", "suffix", "!=", "\"", "\"", "{", "nc", ".", "AddFilterSuffix", "(", "suffix", ")", "\n", "}", "\n\n", "switch", "fields", "[", "2", "]", "{", "case", "\"", "\"", ":", "if", "!", "mb", ".", "AddTopic", "(", "nc", ")", "{", "return", "errInvalidArgument", "(", ")", ".", "Trace", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "!", "mb", ".", "AddQueue", "(", "nc", ")", "{", "return", "errInvalidArgument", "(", ")", ".", "Trace", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "if", "!", "mb", ".", "AddLambda", "(", "nc", ")", "{", "return", "errInvalidArgument", "(", ")", ".", "Trace", "(", "\"", "\"", ")", "\n", "}", "\n", "default", ":", "return", "errInvalidArgument", "(", ")", ".", "Trace", "(", "fields", "[", "2", "]", ")", "\n", "}", "\n\n", "// Set the new bucket configuration", "if", "err", ":=", "c", ".", "api", ".", "SetBucketNotification", "(", "bucket", ",", "mb", ")", ";", "err", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Add bucket notification
[ "Add", "bucket", "notification" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L243-L302
train
minio/mc
cmd/client-s3.go
RemoveNotificationConfig
func (c *s3Client) RemoveNotificationConfig(arn string) *probe.Error { bucket, _ := c.url2BucketAndObject() // Remove all notification configs if arn is empty if arn == "" { if err := c.api.RemoveAllBucketNotification(bucket); err != nil { return probe.NewError(err) } return nil } mb, e := c.api.GetBucketNotification(bucket) if e != nil { return probe.NewError(e) } fields := strings.Split(arn, ":") if len(fields) != 6 { return errInvalidArgument().Trace(fields...) } accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5]) switch fields[2] { case "sns": mb.RemoveTopicByArn(accountArn) case "sqs": mb.RemoveQueueByArn(accountArn) case "lambda": mb.RemoveLambdaByArn(accountArn) default: return errInvalidArgument().Trace(fields[2]) } // Set the new bucket configuration if e := c.api.SetBucketNotification(bucket, mb); e != nil { return probe.NewError(e) } return nil }
go
func (c *s3Client) RemoveNotificationConfig(arn string) *probe.Error { bucket, _ := c.url2BucketAndObject() // Remove all notification configs if arn is empty if arn == "" { if err := c.api.RemoveAllBucketNotification(bucket); err != nil { return probe.NewError(err) } return nil } mb, e := c.api.GetBucketNotification(bucket) if e != nil { return probe.NewError(e) } fields := strings.Split(arn, ":") if len(fields) != 6 { return errInvalidArgument().Trace(fields...) } accountArn := minio.NewArn(fields[1], fields[2], fields[3], fields[4], fields[5]) switch fields[2] { case "sns": mb.RemoveTopicByArn(accountArn) case "sqs": mb.RemoveQueueByArn(accountArn) case "lambda": mb.RemoveLambdaByArn(accountArn) default: return errInvalidArgument().Trace(fields[2]) } // Set the new bucket configuration if e := c.api.SetBucketNotification(bucket, mb); e != nil { return probe.NewError(e) } return nil }
[ "func", "(", "c", "*", "s3Client", ")", "RemoveNotificationConfig", "(", "arn", "string", ")", "*", "probe", ".", "Error", "{", "bucket", ",", "_", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "// Remove all notification configs if arn is empty", "if", "arn", "==", "\"", "\"", "{", "if", "err", ":=", "c", ".", "api", ".", "RemoveAllBucketNotification", "(", "bucket", ")", ";", "err", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "mb", ",", "e", ":=", "c", ".", "api", ".", "GetBucketNotification", "(", "bucket", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "fields", ":=", "strings", ".", "Split", "(", "arn", ",", "\"", "\"", ")", "\n", "if", "len", "(", "fields", ")", "!=", "6", "{", "return", "errInvalidArgument", "(", ")", ".", "Trace", "(", "fields", "...", ")", "\n", "}", "\n", "accountArn", ":=", "minio", ".", "NewArn", "(", "fields", "[", "1", "]", ",", "fields", "[", "2", "]", ",", "fields", "[", "3", "]", ",", "fields", "[", "4", "]", ",", "fields", "[", "5", "]", ")", "\n\n", "switch", "fields", "[", "2", "]", "{", "case", "\"", "\"", ":", "mb", ".", "RemoveTopicByArn", "(", "accountArn", ")", "\n", "case", "\"", "\"", ":", "mb", ".", "RemoveQueueByArn", "(", "accountArn", ")", "\n", "case", "\"", "\"", ":", "mb", ".", "RemoveLambdaByArn", "(", "accountArn", ")", "\n", "default", ":", "return", "errInvalidArgument", "(", ")", ".", "Trace", "(", "fields", "[", "2", "]", ")", "\n", "}", "\n\n", "// Set the new bucket configuration", "if", "e", ":=", "c", ".", "api", ".", "SetBucketNotification", "(", "bucket", ",", "mb", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Remove bucket notification
[ "Remove", "bucket", "notification" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L305-L342
train
minio/mc
cmd/client-s3.go
ListNotificationConfigs
func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *probe.Error) { var configs []notificationConfig bucket, _ := c.url2BucketAndObject() mb, e := c.api.GetBucketNotification(bucket) if e != nil { return nil, probe.NewError(e) } // Generate pretty event names from event types prettyEventNames := func(eventsTypes []minio.NotificationEventType) []string { var result []string for _, eventType := range eventsTypes { result = append(result, string(eventType)) } return result } getFilters := func(config minio.NotificationConfig) (prefix, suffix string) { if config.Filter == nil { return } for _, filter := range config.Filter.S3Key.FilterRules { if strings.ToLower(filter.Name) == "prefix" { prefix = filter.Value } if strings.ToLower(filter.Name) == "suffix" { suffix = filter.Value } } return prefix, suffix } for _, config := range mb.TopicConfigs { if arn != "" && config.Topic != arn { continue } prefix, suffix := getFilters(config.NotificationConfig) configs = append(configs, notificationConfig{ID: config.ID, Arn: config.Topic, Events: prettyEventNames(config.Events), Prefix: prefix, Suffix: suffix}) } for _, config := range mb.QueueConfigs { if arn != "" && config.Queue != arn { continue } prefix, suffix := getFilters(config.NotificationConfig) configs = append(configs, notificationConfig{ID: config.ID, Arn: config.Queue, Events: prettyEventNames(config.Events), Prefix: prefix, Suffix: suffix}) } for _, config := range mb.LambdaConfigs { if arn != "" && config.Lambda != arn { continue } prefix, suffix := getFilters(config.NotificationConfig) configs = append(configs, notificationConfig{ID: config.ID, Arn: config.Lambda, Events: prettyEventNames(config.Events), Prefix: prefix, Suffix: suffix}) } return configs, nil }
go
func (c *s3Client) ListNotificationConfigs(arn string) ([]notificationConfig, *probe.Error) { var configs []notificationConfig bucket, _ := c.url2BucketAndObject() mb, e := c.api.GetBucketNotification(bucket) if e != nil { return nil, probe.NewError(e) } // Generate pretty event names from event types prettyEventNames := func(eventsTypes []minio.NotificationEventType) []string { var result []string for _, eventType := range eventsTypes { result = append(result, string(eventType)) } return result } getFilters := func(config minio.NotificationConfig) (prefix, suffix string) { if config.Filter == nil { return } for _, filter := range config.Filter.S3Key.FilterRules { if strings.ToLower(filter.Name) == "prefix" { prefix = filter.Value } if strings.ToLower(filter.Name) == "suffix" { suffix = filter.Value } } return prefix, suffix } for _, config := range mb.TopicConfigs { if arn != "" && config.Topic != arn { continue } prefix, suffix := getFilters(config.NotificationConfig) configs = append(configs, notificationConfig{ID: config.ID, Arn: config.Topic, Events: prettyEventNames(config.Events), Prefix: prefix, Suffix: suffix}) } for _, config := range mb.QueueConfigs { if arn != "" && config.Queue != arn { continue } prefix, suffix := getFilters(config.NotificationConfig) configs = append(configs, notificationConfig{ID: config.ID, Arn: config.Queue, Events: prettyEventNames(config.Events), Prefix: prefix, Suffix: suffix}) } for _, config := range mb.LambdaConfigs { if arn != "" && config.Lambda != arn { continue } prefix, suffix := getFilters(config.NotificationConfig) configs = append(configs, notificationConfig{ID: config.ID, Arn: config.Lambda, Events: prettyEventNames(config.Events), Prefix: prefix, Suffix: suffix}) } return configs, nil }
[ "func", "(", "c", "*", "s3Client", ")", "ListNotificationConfigs", "(", "arn", "string", ")", "(", "[", "]", "notificationConfig", ",", "*", "probe", ".", "Error", ")", "{", "var", "configs", "[", "]", "notificationConfig", "\n", "bucket", ",", "_", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "mb", ",", "e", ":=", "c", ".", "api", ".", "GetBucketNotification", "(", "bucket", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "// Generate pretty event names from event types", "prettyEventNames", ":=", "func", "(", "eventsTypes", "[", "]", "minio", ".", "NotificationEventType", ")", "[", "]", "string", "{", "var", "result", "[", "]", "string", "\n", "for", "_", ",", "eventType", ":=", "range", "eventsTypes", "{", "result", "=", "append", "(", "result", ",", "string", "(", "eventType", ")", ")", "\n", "}", "\n", "return", "result", "\n", "}", "\n\n", "getFilters", ":=", "func", "(", "config", "minio", ".", "NotificationConfig", ")", "(", "prefix", ",", "suffix", "string", ")", "{", "if", "config", ".", "Filter", "==", "nil", "{", "return", "\n", "}", "\n", "for", "_", ",", "filter", ":=", "range", "config", ".", "Filter", ".", "S3Key", ".", "FilterRules", "{", "if", "strings", ".", "ToLower", "(", "filter", ".", "Name", ")", "==", "\"", "\"", "{", "prefix", "=", "filter", ".", "Value", "\n", "}", "\n", "if", "strings", ".", "ToLower", "(", "filter", ".", "Name", ")", "==", "\"", "\"", "{", "suffix", "=", "filter", ".", "Value", "\n", "}", "\n\n", "}", "\n", "return", "prefix", ",", "suffix", "\n", "}", "\n\n", "for", "_", ",", "config", ":=", "range", "mb", ".", "TopicConfigs", "{", "if", "arn", "!=", "\"", "\"", "&&", "config", ".", "Topic", "!=", "arn", "{", "continue", "\n", "}", "\n", "prefix", ",", "suffix", ":=", "getFilters", "(", "config", ".", "NotificationConfig", ")", "\n", "configs", "=", "append", "(", "configs", ",", "notificationConfig", "{", "ID", ":", "config", ".", "ID", ",", "Arn", ":", "config", ".", "Topic", ",", "Events", ":", "prettyEventNames", "(", "config", ".", "Events", ")", ",", "Prefix", ":", "prefix", ",", "Suffix", ":", "suffix", "}", ")", "\n", "}", "\n\n", "for", "_", ",", "config", ":=", "range", "mb", ".", "QueueConfigs", "{", "if", "arn", "!=", "\"", "\"", "&&", "config", ".", "Queue", "!=", "arn", "{", "continue", "\n", "}", "\n", "prefix", ",", "suffix", ":=", "getFilters", "(", "config", ".", "NotificationConfig", ")", "\n", "configs", "=", "append", "(", "configs", ",", "notificationConfig", "{", "ID", ":", "config", ".", "ID", ",", "Arn", ":", "config", ".", "Queue", ",", "Events", ":", "prettyEventNames", "(", "config", ".", "Events", ")", ",", "Prefix", ":", "prefix", ",", "Suffix", ":", "suffix", "}", ")", "\n", "}", "\n\n", "for", "_", ",", "config", ":=", "range", "mb", ".", "LambdaConfigs", "{", "if", "arn", "!=", "\"", "\"", "&&", "config", ".", "Lambda", "!=", "arn", "{", "continue", "\n", "}", "\n", "prefix", ",", "suffix", ":=", "getFilters", "(", "config", ".", "NotificationConfig", ")", "\n", "configs", "=", "append", "(", "configs", ",", "notificationConfig", "{", "ID", ":", "config", ".", "ID", ",", "Arn", ":", "config", ".", "Lambda", ",", "Events", ":", "prettyEventNames", "(", "config", ".", "Events", ")", ",", "Prefix", ":", "prefix", ",", "Suffix", ":", "suffix", "}", ")", "\n", "}", "\n\n", "return", "configs", ",", "nil", "\n", "}" ]
// List notification configs
[ "List", "notification", "configs" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L353-L423
train
minio/mc
cmd/client-s3.go
selectObjectOutputOpts
func selectObjectOutputOpts(selOpts SelectObjectOpts, i minio.SelectObjectInputSerialization) minio.SelectObjectOutputSerialization { var isOK bool var recDelim, fldDelim, quoteChar, quoteEscChar, qf string o := minio.SelectObjectOutputSerialization{} if _, ok := selOpts.OutputSerOpts["json"]; ok { recDelim, isOK = selOpts.OutputSerOpts["json"][recordDelimiterType] if !isOK { recDelim = "\n" } o.JSON = &minio.JSONOutputOptions{RecordDelimiter: recDelim} } if _, ok := selOpts.OutputSerOpts["csv"]; ok { o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter} if recDelim, isOK = selOpts.OutputSerOpts["csv"][recordDelimiterType]; isOK { o.CSV.RecordDelimiter = recDelim } if fldDelim, isOK = selOpts.OutputSerOpts["csv"][fieldDelimiterType]; isOK { o.CSV.FieldDelimiter = fldDelim } if quoteChar, isOK = selOpts.OutputSerOpts["csv"][quoteCharacterType]; isOK { o.CSV.QuoteCharacter = quoteChar } if quoteEscChar, isOK = selOpts.OutputSerOpts["csv"][quoteEscapeCharacterType]; isOK { o.CSV.QuoteEscapeCharacter = quoteEscChar } if qf, isOK = selOpts.OutputSerOpts["csv"][quoteFieldType]; isOK { o.CSV.QuoteFields = minio.CSVQuoteFields(qf) } } // default to CSV output if options left unspecified if o.CSV == nil && o.JSON == nil { if i.JSON != nil { o.JSON = &minio.JSONOutputOptions{RecordDelimiter: "\n"} } else { o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter} } } return o }
go
func selectObjectOutputOpts(selOpts SelectObjectOpts, i minio.SelectObjectInputSerialization) minio.SelectObjectOutputSerialization { var isOK bool var recDelim, fldDelim, quoteChar, quoteEscChar, qf string o := minio.SelectObjectOutputSerialization{} if _, ok := selOpts.OutputSerOpts["json"]; ok { recDelim, isOK = selOpts.OutputSerOpts["json"][recordDelimiterType] if !isOK { recDelim = "\n" } o.JSON = &minio.JSONOutputOptions{RecordDelimiter: recDelim} } if _, ok := selOpts.OutputSerOpts["csv"]; ok { o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter} if recDelim, isOK = selOpts.OutputSerOpts["csv"][recordDelimiterType]; isOK { o.CSV.RecordDelimiter = recDelim } if fldDelim, isOK = selOpts.OutputSerOpts["csv"][fieldDelimiterType]; isOK { o.CSV.FieldDelimiter = fldDelim } if quoteChar, isOK = selOpts.OutputSerOpts["csv"][quoteCharacterType]; isOK { o.CSV.QuoteCharacter = quoteChar } if quoteEscChar, isOK = selOpts.OutputSerOpts["csv"][quoteEscapeCharacterType]; isOK { o.CSV.QuoteEscapeCharacter = quoteEscChar } if qf, isOK = selOpts.OutputSerOpts["csv"][quoteFieldType]; isOK { o.CSV.QuoteFields = minio.CSVQuoteFields(qf) } } // default to CSV output if options left unspecified if o.CSV == nil && o.JSON == nil { if i.JSON != nil { o.JSON = &minio.JSONOutputOptions{RecordDelimiter: "\n"} } else { o.CSV = &minio.CSVOutputOptions{RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter} } } return o }
[ "func", "selectObjectOutputOpts", "(", "selOpts", "SelectObjectOpts", ",", "i", "minio", ".", "SelectObjectInputSerialization", ")", "minio", ".", "SelectObjectOutputSerialization", "{", "var", "isOK", "bool", "\n", "var", "recDelim", ",", "fldDelim", ",", "quoteChar", ",", "quoteEscChar", ",", "qf", "string", "\n\n", "o", ":=", "minio", ".", "SelectObjectOutputSerialization", "{", "}", "\n", "if", "_", ",", "ok", ":=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", ";", "ok", "{", "recDelim", ",", "isOK", "=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", "[", "recordDelimiterType", "]", "\n", "if", "!", "isOK", "{", "recDelim", "=", "\"", "\\n", "\"", "\n", "}", "\n", "o", ".", "JSON", "=", "&", "minio", ".", "JSONOutputOptions", "{", "RecordDelimiter", ":", "recDelim", "}", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", ";", "ok", "{", "o", ".", "CSV", "=", "&", "minio", ".", "CSVOutputOptions", "{", "RecordDelimiter", ":", "defaultRecordDelimiter", ",", "FieldDelimiter", ":", "defaultFieldDelimiter", "}", "\n", "if", "recDelim", ",", "isOK", "=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", "[", "recordDelimiterType", "]", ";", "isOK", "{", "o", ".", "CSV", ".", "RecordDelimiter", "=", "recDelim", "\n", "}", "\n\n", "if", "fldDelim", ",", "isOK", "=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", "[", "fieldDelimiterType", "]", ";", "isOK", "{", "o", ".", "CSV", ".", "FieldDelimiter", "=", "fldDelim", "\n", "}", "\n", "if", "quoteChar", ",", "isOK", "=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", "[", "quoteCharacterType", "]", ";", "isOK", "{", "o", ".", "CSV", ".", "QuoteCharacter", "=", "quoteChar", "\n", "}", "\n\n", "if", "quoteEscChar", ",", "isOK", "=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", "[", "quoteEscapeCharacterType", "]", ";", "isOK", "{", "o", ".", "CSV", ".", "QuoteEscapeCharacter", "=", "quoteEscChar", "\n", "}", "\n", "if", "qf", ",", "isOK", "=", "selOpts", ".", "OutputSerOpts", "[", "\"", "\"", "]", "[", "quoteFieldType", "]", ";", "isOK", "{", "o", ".", "CSV", ".", "QuoteFields", "=", "minio", ".", "CSVQuoteFields", "(", "qf", ")", "\n", "}", "\n", "}", "\n", "// default to CSV output if options left unspecified", "if", "o", ".", "CSV", "==", "nil", "&&", "o", ".", "JSON", "==", "nil", "{", "if", "i", ".", "JSON", "!=", "nil", "{", "o", ".", "JSON", "=", "&", "minio", ".", "JSONOutputOptions", "{", "RecordDelimiter", ":", "\"", "\\n", "\"", "}", "\n", "}", "else", "{", "o", ".", "CSV", "=", "&", "minio", ".", "CSVOutputOptions", "{", "RecordDelimiter", ":", "defaultRecordDelimiter", ",", "FieldDelimiter", ":", "defaultFieldDelimiter", "}", "\n", "}", "\n", "}", "\n", "return", "o", "\n", "}" ]
// set the SelectObjectOutputSerialization struct using options passed in by client. If unspecified, // default S3 API specified defaults
[ "set", "the", "SelectObjectOutputSerialization", "struct", "using", "options", "passed", "in", "by", "client", ".", "If", "unspecified", "default", "S3", "API", "specified", "defaults" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L435-L476
train
minio/mc
cmd/client-s3.go
selectObjectInputOpts
func selectObjectInputOpts(selOpts SelectObjectOpts, object string) minio.SelectObjectInputSerialization { var isOK bool var recDelim, fldDelim, quoteChar, quoteEscChar, fileHeader, commentChar, typ string i := minio.SelectObjectInputSerialization{} if _, ok := selOpts.InputSerOpts["parquet"]; ok { i.Parquet = &minio.ParquetInputOptions{} } if _, ok := selOpts.InputSerOpts["json"]; ok { i.JSON = &minio.JSONInputOptions{} if typ, _ = selOpts.InputSerOpts["json"][typeJSONType]; typ != "" { i.JSON.Type = minio.JSONType(typ) } } if _, ok := selOpts.InputSerOpts["csv"]; ok { i.CSV = &minio.CSVInputOptions{RecordDelimiter: defaultRecordDelimiter} if recDelim, isOK = selOpts.InputSerOpts["csv"][recordDelimiterType]; isOK { i.CSV.RecordDelimiter = recDelim } if fldDelim, isOK = selOpts.InputSerOpts["csv"][fieldDelimiterType]; isOK { i.CSV.FieldDelimiter = fldDelim } if quoteChar, isOK = selOpts.InputSerOpts["csv"][quoteCharacterType]; isOK { i.CSV.QuoteCharacter = quoteChar } if quoteEscChar, isOK = selOpts.InputSerOpts["csv"][quoteEscapeCharacterType]; isOK { i.CSV.QuoteEscapeCharacter = quoteEscChar } fileHeader, _ = selOpts.InputSerOpts["csv"][fileHeaderType] i.CSV.FileHeaderInfo = minio.CSVFileHeaderInfo(fileHeader) if commentChar, isOK = selOpts.InputSerOpts["csv"][commentCharType]; isOK { i.CSV.Comments = commentChar } // needs to be added to minio-go // if qrd, isOK = selOpts.InputSerOpts["csv"][quotedRecordDelimiterType];isOK { // i.CSV.QuotedRecordDelimiter = qrd // } } if i.CSV == nil && i.JSON == nil && i.Parquet == nil { ext := filepath.Ext(trimCompressionFileExts(object)) if strings.Contains(ext, "csv") { i.CSV = &minio.CSVInputOptions{ RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter, FileHeaderInfo: minio.CSVFileHeaderInfoUse, } } if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") { i.Parquet = &minio.ParquetInputOptions{} } if strings.Contains(ext, "json") { i.JSON = &minio.JSONInputOptions{Type: minio.JSONLinesType} } } i.CompressionType = selectCompressionType(selOpts, object) return i }
go
func selectObjectInputOpts(selOpts SelectObjectOpts, object string) minio.SelectObjectInputSerialization { var isOK bool var recDelim, fldDelim, quoteChar, quoteEscChar, fileHeader, commentChar, typ string i := minio.SelectObjectInputSerialization{} if _, ok := selOpts.InputSerOpts["parquet"]; ok { i.Parquet = &minio.ParquetInputOptions{} } if _, ok := selOpts.InputSerOpts["json"]; ok { i.JSON = &minio.JSONInputOptions{} if typ, _ = selOpts.InputSerOpts["json"][typeJSONType]; typ != "" { i.JSON.Type = minio.JSONType(typ) } } if _, ok := selOpts.InputSerOpts["csv"]; ok { i.CSV = &minio.CSVInputOptions{RecordDelimiter: defaultRecordDelimiter} if recDelim, isOK = selOpts.InputSerOpts["csv"][recordDelimiterType]; isOK { i.CSV.RecordDelimiter = recDelim } if fldDelim, isOK = selOpts.InputSerOpts["csv"][fieldDelimiterType]; isOK { i.CSV.FieldDelimiter = fldDelim } if quoteChar, isOK = selOpts.InputSerOpts["csv"][quoteCharacterType]; isOK { i.CSV.QuoteCharacter = quoteChar } if quoteEscChar, isOK = selOpts.InputSerOpts["csv"][quoteEscapeCharacterType]; isOK { i.CSV.QuoteEscapeCharacter = quoteEscChar } fileHeader, _ = selOpts.InputSerOpts["csv"][fileHeaderType] i.CSV.FileHeaderInfo = minio.CSVFileHeaderInfo(fileHeader) if commentChar, isOK = selOpts.InputSerOpts["csv"][commentCharType]; isOK { i.CSV.Comments = commentChar } // needs to be added to minio-go // if qrd, isOK = selOpts.InputSerOpts["csv"][quotedRecordDelimiterType];isOK { // i.CSV.QuotedRecordDelimiter = qrd // } } if i.CSV == nil && i.JSON == nil && i.Parquet == nil { ext := filepath.Ext(trimCompressionFileExts(object)) if strings.Contains(ext, "csv") { i.CSV = &minio.CSVInputOptions{ RecordDelimiter: defaultRecordDelimiter, FieldDelimiter: defaultFieldDelimiter, FileHeaderInfo: minio.CSVFileHeaderInfoUse, } } if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") { i.Parquet = &minio.ParquetInputOptions{} } if strings.Contains(ext, "json") { i.JSON = &minio.JSONInputOptions{Type: minio.JSONLinesType} } } i.CompressionType = selectCompressionType(selOpts, object) return i }
[ "func", "selectObjectInputOpts", "(", "selOpts", "SelectObjectOpts", ",", "object", "string", ")", "minio", ".", "SelectObjectInputSerialization", "{", "var", "isOK", "bool", "\n", "var", "recDelim", ",", "fldDelim", ",", "quoteChar", ",", "quoteEscChar", ",", "fileHeader", ",", "commentChar", ",", "typ", "string", "\n\n", "i", ":=", "minio", ".", "SelectObjectInputSerialization", "{", "}", "\n", "if", "_", ",", "ok", ":=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", ";", "ok", "{", "i", ".", "Parquet", "=", "&", "minio", ".", "ParquetInputOptions", "{", "}", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", ";", "ok", "{", "i", ".", "JSON", "=", "&", "minio", ".", "JSONInputOptions", "{", "}", "\n", "if", "typ", ",", "_", "=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", "[", "typeJSONType", "]", ";", "typ", "!=", "\"", "\"", "{", "i", ".", "JSON", ".", "Type", "=", "minio", ".", "JSONType", "(", "typ", ")", "\n", "}", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", ";", "ok", "{", "i", ".", "CSV", "=", "&", "minio", ".", "CSVInputOptions", "{", "RecordDelimiter", ":", "defaultRecordDelimiter", "}", "\n", "if", "recDelim", ",", "isOK", "=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", "[", "recordDelimiterType", "]", ";", "isOK", "{", "i", ".", "CSV", ".", "RecordDelimiter", "=", "recDelim", "\n", "}", "\n", "if", "fldDelim", ",", "isOK", "=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", "[", "fieldDelimiterType", "]", ";", "isOK", "{", "i", ".", "CSV", ".", "FieldDelimiter", "=", "fldDelim", "\n", "}", "\n", "if", "quoteChar", ",", "isOK", "=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", "[", "quoteCharacterType", "]", ";", "isOK", "{", "i", ".", "CSV", ".", "QuoteCharacter", "=", "quoteChar", "\n", "}", "\n\n", "if", "quoteEscChar", ",", "isOK", "=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", "[", "quoteEscapeCharacterType", "]", ";", "isOK", "{", "i", ".", "CSV", ".", "QuoteEscapeCharacter", "=", "quoteEscChar", "\n", "}", "\n", "fileHeader", ",", "_", "=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", "[", "fileHeaderType", "]", "\n", "i", ".", "CSV", ".", "FileHeaderInfo", "=", "minio", ".", "CSVFileHeaderInfo", "(", "fileHeader", ")", "\n", "if", "commentChar", ",", "isOK", "=", "selOpts", ".", "InputSerOpts", "[", "\"", "\"", "]", "[", "commentCharType", "]", ";", "isOK", "{", "i", ".", "CSV", ".", "Comments", "=", "commentChar", "\n", "}", "\n", "// needs to be added to minio-go", "// if qrd, isOK = selOpts.InputSerOpts[\"csv\"][quotedRecordDelimiterType];isOK {", "// \t\t\ti.CSV.QuotedRecordDelimiter = qrd", "// }", "}", "\n", "if", "i", ".", "CSV", "==", "nil", "&&", "i", ".", "JSON", "==", "nil", "&&", "i", ".", "Parquet", "==", "nil", "{", "ext", ":=", "filepath", ".", "Ext", "(", "trimCompressionFileExts", "(", "object", ")", ")", "\n", "if", "strings", ".", "Contains", "(", "ext", ",", "\"", "\"", ")", "{", "i", ".", "CSV", "=", "&", "minio", ".", "CSVInputOptions", "{", "RecordDelimiter", ":", "defaultRecordDelimiter", ",", "FieldDelimiter", ":", "defaultFieldDelimiter", ",", "FileHeaderInfo", ":", "minio", ".", "CSVFileHeaderInfoUse", ",", "}", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "ext", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "object", ",", "\"", "\"", ")", "{", "i", ".", "Parquet", "=", "&", "minio", ".", "ParquetInputOptions", "{", "}", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "ext", ",", "\"", "\"", ")", "{", "i", ".", "JSON", "=", "&", "minio", ".", "JSONInputOptions", "{", "Type", ":", "minio", ".", "JSONLinesType", "}", "\n", "}", "\n", "}", "\n", "i", ".", "CompressionType", "=", "selectCompressionType", "(", "selOpts", ",", "object", ")", "\n", "return", "i", "\n", "}" ]
// set the SelectObjectInputSerialization struct using options passed in by client. If unspecified, // default S3 API specified defaults
[ "set", "the", "SelectObjectInputSerialization", "struct", "using", "options", "passed", "in", "by", "client", ".", "If", "unspecified", "default", "S3", "API", "specified", "defaults" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L484-L541
train
minio/mc
cmd/client-s3.go
selectCompressionType
func selectCompressionType(selOpts SelectObjectOpts, object string) minio.SelectCompressionType { ext := filepath.Ext(object) contentType := mimedb.TypeByExtension(ext) if selOpts.CompressionType != "" { return selOpts.CompressionType } if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") { return minio.SelectCompressionNONE } if contentType != "" { if strings.Contains(contentType, "gzip") { return minio.SelectCompressionGZIP } else if strings.Contains(contentType, "bzip") { return minio.SelectCompressionBZIP } } return minio.SelectCompressionNONE }
go
func selectCompressionType(selOpts SelectObjectOpts, object string) minio.SelectCompressionType { ext := filepath.Ext(object) contentType := mimedb.TypeByExtension(ext) if selOpts.CompressionType != "" { return selOpts.CompressionType } if strings.Contains(ext, "parquet") || strings.Contains(object, ".parquet") { return minio.SelectCompressionNONE } if contentType != "" { if strings.Contains(contentType, "gzip") { return minio.SelectCompressionGZIP } else if strings.Contains(contentType, "bzip") { return minio.SelectCompressionBZIP } } return minio.SelectCompressionNONE }
[ "func", "selectCompressionType", "(", "selOpts", "SelectObjectOpts", ",", "object", "string", ")", "minio", ".", "SelectCompressionType", "{", "ext", ":=", "filepath", ".", "Ext", "(", "object", ")", "\n", "contentType", ":=", "mimedb", ".", "TypeByExtension", "(", "ext", ")", "\n\n", "if", "selOpts", ".", "CompressionType", "!=", "\"", "\"", "{", "return", "selOpts", ".", "CompressionType", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "ext", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "object", ",", "\"", "\"", ")", "{", "return", "minio", ".", "SelectCompressionNONE", "\n", "}", "\n", "if", "contentType", "!=", "\"", "\"", "{", "if", "strings", ".", "Contains", "(", "contentType", ",", "\"", "\"", ")", "{", "return", "minio", ".", "SelectCompressionGZIP", "\n", "}", "else", "if", "strings", ".", "Contains", "(", "contentType", ",", "\"", "\"", ")", "{", "return", "minio", ".", "SelectCompressionBZIP", "\n", "}", "\n", "}", "\n", "return", "minio", ".", "SelectCompressionNONE", "\n", "}" ]
// get client specified compression type or default compression type from file extension
[ "get", "client", "specified", "compression", "type", "or", "default", "compression", "type", "from", "file", "extension" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L544-L562
train
minio/mc
cmd/client-s3.go
Get
func (c *s3Client) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { bucket, object := c.url2BucketAndObject() opts := minio.GetObjectOptions{} opts.ServerSideEncryption = sse reader, e := c.api.GetObject(bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "NoSuchBucket" { return nil, probe.NewError(BucketDoesNotExist{ Bucket: bucket, }) } if errResponse.Code == "InvalidBucketName" { return nil, probe.NewError(BucketInvalid{ Bucket: bucket, }) } if errResponse.Code == "NoSuchKey" { return nil, probe.NewError(ObjectMissing{}) } return nil, probe.NewError(e) } return reader, nil }
go
func (c *s3Client) Get(sse encrypt.ServerSide) (io.ReadCloser, *probe.Error) { bucket, object := c.url2BucketAndObject() opts := minio.GetObjectOptions{} opts.ServerSideEncryption = sse reader, e := c.api.GetObject(bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "NoSuchBucket" { return nil, probe.NewError(BucketDoesNotExist{ Bucket: bucket, }) } if errResponse.Code == "InvalidBucketName" { return nil, probe.NewError(BucketInvalid{ Bucket: bucket, }) } if errResponse.Code == "NoSuchKey" { return nil, probe.NewError(ObjectMissing{}) } return nil, probe.NewError(e) } return reader, nil }
[ "func", "(", "c", "*", "s3Client", ")", "Get", "(", "sse", "encrypt", ".", "ServerSide", ")", "(", "io", ".", "ReadCloser", ",", "*", "probe", ".", "Error", ")", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "opts", ":=", "minio", ".", "GetObjectOptions", "{", "}", "\n", "opts", ".", "ServerSideEncryption", "=", "sse", "\n", "reader", ",", "e", ":=", "c", ".", "api", ".", "GetObject", "(", "bucket", ",", "object", ",", "opts", ")", "\n", "if", "e", "!=", "nil", "{", "errResponse", ":=", "minio", ".", "ToErrorResponse", "(", "e", ")", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "BucketDoesNotExist", "{", "Bucket", ":", "bucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "BucketInvalid", "{", "Bucket", ":", "bucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "ObjectMissing", "{", "}", ")", "\n", "}", "\n", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "reader", ",", "nil", "\n", "}" ]
// Get - get object with metadata.
[ "Get", "-", "get", "object", "with", "metadata", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L707-L730
train
minio/mc
cmd/client-s3.go
Copy
func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error { dstBucket, dstObject := c.url2BucketAndObject() if dstBucket == "" { return probe.NewError(BucketNameEmpty{}) } tokens := splitStr(source, string(c.targetURL.Separator), 3) // Source object src := minio.NewSourceInfo(tokens[1], tokens[2], srcSSE) // Destination object dst, e := minio.NewDestinationInfo(dstBucket, dstObject, tgtSSE, metadata) if e != nil { return probe.NewError(e) } if e = c.api.ComposeObjectWithProgress(dst, []minio.SourceInfo{src}, progress); e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "AccessDenied" { return probe.NewError(PathInsufficientPermission{ Path: c.targetURL.String(), }) } if errResponse.Code == "NoSuchBucket" { return probe.NewError(BucketDoesNotExist{ Bucket: dstBucket, }) } if errResponse.Code == "InvalidBucketName" { return probe.NewError(BucketInvalid{ Bucket: dstBucket, }) } if errResponse.Code == "NoSuchKey" { return probe.NewError(ObjectMissing{}) } return probe.NewError(e) } return nil }
go
func (c *s3Client) Copy(source string, size int64, progress io.Reader, srcSSE, tgtSSE encrypt.ServerSide, metadata map[string]string) *probe.Error { dstBucket, dstObject := c.url2BucketAndObject() if dstBucket == "" { return probe.NewError(BucketNameEmpty{}) } tokens := splitStr(source, string(c.targetURL.Separator), 3) // Source object src := minio.NewSourceInfo(tokens[1], tokens[2], srcSSE) // Destination object dst, e := minio.NewDestinationInfo(dstBucket, dstObject, tgtSSE, metadata) if e != nil { return probe.NewError(e) } if e = c.api.ComposeObjectWithProgress(dst, []minio.SourceInfo{src}, progress); e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "AccessDenied" { return probe.NewError(PathInsufficientPermission{ Path: c.targetURL.String(), }) } if errResponse.Code == "NoSuchBucket" { return probe.NewError(BucketDoesNotExist{ Bucket: dstBucket, }) } if errResponse.Code == "InvalidBucketName" { return probe.NewError(BucketInvalid{ Bucket: dstBucket, }) } if errResponse.Code == "NoSuchKey" { return probe.NewError(ObjectMissing{}) } return probe.NewError(e) } return nil }
[ "func", "(", "c", "*", "s3Client", ")", "Copy", "(", "source", "string", ",", "size", "int64", ",", "progress", "io", ".", "Reader", ",", "srcSSE", ",", "tgtSSE", "encrypt", ".", "ServerSide", ",", "metadata", "map", "[", "string", "]", "string", ")", "*", "probe", ".", "Error", "{", "dstBucket", ",", "dstObject", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "if", "dstBucket", "==", "\"", "\"", "{", "return", "probe", ".", "NewError", "(", "BucketNameEmpty", "{", "}", ")", "\n", "}", "\n\n", "tokens", ":=", "splitStr", "(", "source", ",", "string", "(", "c", ".", "targetURL", ".", "Separator", ")", ",", "3", ")", "\n\n", "// Source object", "src", ":=", "minio", ".", "NewSourceInfo", "(", "tokens", "[", "1", "]", ",", "tokens", "[", "2", "]", ",", "srcSSE", ")", "\n\n", "// Destination object", "dst", ",", "e", ":=", "minio", ".", "NewDestinationInfo", "(", "dstBucket", ",", "dstObject", ",", "tgtSSE", ",", "metadata", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n\n", "if", "e", "=", "c", ".", "api", ".", "ComposeObjectWithProgress", "(", "dst", ",", "[", "]", "minio", ".", "SourceInfo", "{", "src", "}", ",", "progress", ")", ";", "e", "!=", "nil", "{", "errResponse", ":=", "minio", ".", "ToErrorResponse", "(", "e", ")", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "probe", ".", "NewError", "(", "PathInsufficientPermission", "{", "Path", ":", "c", ".", "targetURL", ".", "String", "(", ")", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "probe", ".", "NewError", "(", "BucketDoesNotExist", "{", "Bucket", ":", "dstBucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "probe", ".", "NewError", "(", "BucketInvalid", "{", "Bucket", ":", "dstBucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "probe", ".", "NewError", "(", "ObjectMissing", "{", "}", ")", "\n", "}", "\n", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Copy - copy object, uses server side copy API. Also uses an abstracted API // such that large file sizes will be copied in multipart manner on server // side.
[ "Copy", "-", "copy", "object", "uses", "server", "side", "copy", "API", ".", "Also", "uses", "an", "abstracted", "API", "such", "that", "large", "file", "sizes", "will", "be", "copied", "in", "multipart", "manner", "on", "server", "side", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L735-L775
train
minio/mc
cmd/client-s3.go
Put
func (c *s3Client) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) { bucket, object := c.url2BucketAndObject() contentType, ok := metadata["Content-Type"] if ok { delete(metadata, "Content-Type") } else { // Set content-type if not specified. contentType = "application/octet-stream" } cacheControl, ok := metadata["Cache-Control"] if ok { delete(metadata, "Cache-Control") } contentEncoding, ok := metadata["Content-Encoding"] if ok { delete(metadata, "Content-Encoding") } contentDisposition, ok := metadata["Content-Disposition"] if ok { delete(metadata, "Content-Disposition") } contentLanguage, ok := metadata["Content-Language"] if ok { delete(metadata, "Content-Language") } storageClass, ok := metadata["X-Amz-Storage-Class"] if ok { delete(metadata, "X-Amz-Storage-Class") } if bucket == "" { return 0, probe.NewError(BucketNameEmpty{}) } opts := minio.PutObjectOptions{ UserMetadata: metadata, Progress: progress, NumThreads: defaultMultipartThreadsNum, ContentType: contentType, CacheControl: cacheControl, ContentDisposition: contentDisposition, ContentEncoding: contentEncoding, ContentLanguage: contentLanguage, StorageClass: strings.ToUpper(storageClass), ServerSideEncryption: sse, } n, e := c.api.PutObjectWithContext(ctx, bucket, object, reader, size, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "UnexpectedEOF" || e == io.EOF { return n, probe.NewError(UnexpectedEOF{ TotalSize: size, TotalWritten: n, }) } if errResponse.Code == "AccessDenied" { return n, probe.NewError(PathInsufficientPermission{ Path: c.targetURL.String(), }) } if errResponse.Code == "MethodNotAllowed" { return n, probe.NewError(ObjectAlreadyExists{ Object: object, }) } if errResponse.Code == "XMinioObjectExistsAsDirectory" { return n, probe.NewError(ObjectAlreadyExistsAsDirectory{ Object: object, }) } if errResponse.Code == "NoSuchBucket" { return n, probe.NewError(BucketDoesNotExist{ Bucket: bucket, }) } if errResponse.Code == "InvalidBucketName" { return n, probe.NewError(BucketInvalid{ Bucket: bucket, }) } if errResponse.Code == "NoSuchKey" { return n, probe.NewError(ObjectMissing{}) } return n, probe.NewError(e) } return n, nil }
go
func (c *s3Client) Put(ctx context.Context, reader io.Reader, size int64, metadata map[string]string, progress io.Reader, sse encrypt.ServerSide) (int64, *probe.Error) { bucket, object := c.url2BucketAndObject() contentType, ok := metadata["Content-Type"] if ok { delete(metadata, "Content-Type") } else { // Set content-type if not specified. contentType = "application/octet-stream" } cacheControl, ok := metadata["Cache-Control"] if ok { delete(metadata, "Cache-Control") } contentEncoding, ok := metadata["Content-Encoding"] if ok { delete(metadata, "Content-Encoding") } contentDisposition, ok := metadata["Content-Disposition"] if ok { delete(metadata, "Content-Disposition") } contentLanguage, ok := metadata["Content-Language"] if ok { delete(metadata, "Content-Language") } storageClass, ok := metadata["X-Amz-Storage-Class"] if ok { delete(metadata, "X-Amz-Storage-Class") } if bucket == "" { return 0, probe.NewError(BucketNameEmpty{}) } opts := minio.PutObjectOptions{ UserMetadata: metadata, Progress: progress, NumThreads: defaultMultipartThreadsNum, ContentType: contentType, CacheControl: cacheControl, ContentDisposition: contentDisposition, ContentEncoding: contentEncoding, ContentLanguage: contentLanguage, StorageClass: strings.ToUpper(storageClass), ServerSideEncryption: sse, } n, e := c.api.PutObjectWithContext(ctx, bucket, object, reader, size, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "UnexpectedEOF" || e == io.EOF { return n, probe.NewError(UnexpectedEOF{ TotalSize: size, TotalWritten: n, }) } if errResponse.Code == "AccessDenied" { return n, probe.NewError(PathInsufficientPermission{ Path: c.targetURL.String(), }) } if errResponse.Code == "MethodNotAllowed" { return n, probe.NewError(ObjectAlreadyExists{ Object: object, }) } if errResponse.Code == "XMinioObjectExistsAsDirectory" { return n, probe.NewError(ObjectAlreadyExistsAsDirectory{ Object: object, }) } if errResponse.Code == "NoSuchBucket" { return n, probe.NewError(BucketDoesNotExist{ Bucket: bucket, }) } if errResponse.Code == "InvalidBucketName" { return n, probe.NewError(BucketInvalid{ Bucket: bucket, }) } if errResponse.Code == "NoSuchKey" { return n, probe.NewError(ObjectMissing{}) } return n, probe.NewError(e) } return n, nil }
[ "func", "(", "c", "*", "s3Client", ")", "Put", "(", "ctx", "context", ".", "Context", ",", "reader", "io", ".", "Reader", ",", "size", "int64", ",", "metadata", "map", "[", "string", "]", "string", ",", "progress", "io", ".", "Reader", ",", "sse", "encrypt", ".", "ServerSide", ")", "(", "int64", ",", "*", "probe", ".", "Error", ")", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "contentType", ",", "ok", ":=", "metadata", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "}", "else", "{", "// Set content-type if not specified.", "contentType", "=", "\"", "\"", "\n", "}", "\n\n", "cacheControl", ",", "ok", ":=", "metadata", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "}", "\n\n", "contentEncoding", ",", "ok", ":=", "metadata", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "}", "\n\n", "contentDisposition", ",", "ok", ":=", "metadata", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "}", "\n\n", "contentLanguage", ",", "ok", ":=", "metadata", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "}", "\n\n", "storageClass", ",", "ok", ":=", "metadata", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "delete", "(", "metadata", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "bucket", "==", "\"", "\"", "{", "return", "0", ",", "probe", ".", "NewError", "(", "BucketNameEmpty", "{", "}", ")", "\n", "}", "\n", "opts", ":=", "minio", ".", "PutObjectOptions", "{", "UserMetadata", ":", "metadata", ",", "Progress", ":", "progress", ",", "NumThreads", ":", "defaultMultipartThreadsNum", ",", "ContentType", ":", "contentType", ",", "CacheControl", ":", "cacheControl", ",", "ContentDisposition", ":", "contentDisposition", ",", "ContentEncoding", ":", "contentEncoding", ",", "ContentLanguage", ":", "contentLanguage", ",", "StorageClass", ":", "strings", ".", "ToUpper", "(", "storageClass", ")", ",", "ServerSideEncryption", ":", "sse", ",", "}", "\n", "n", ",", "e", ":=", "c", ".", "api", ".", "PutObjectWithContext", "(", "ctx", ",", "bucket", ",", "object", ",", "reader", ",", "size", ",", "opts", ")", "\n", "if", "e", "!=", "nil", "{", "errResponse", ":=", "minio", ".", "ToErrorResponse", "(", "e", ")", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "||", "e", "==", "io", ".", "EOF", "{", "return", "n", ",", "probe", ".", "NewError", "(", "UnexpectedEOF", "{", "TotalSize", ":", "size", ",", "TotalWritten", ":", "n", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "n", ",", "probe", ".", "NewError", "(", "PathInsufficientPermission", "{", "Path", ":", "c", ".", "targetURL", ".", "String", "(", ")", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "n", ",", "probe", ".", "NewError", "(", "ObjectAlreadyExists", "{", "Object", ":", "object", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "n", ",", "probe", ".", "NewError", "(", "ObjectAlreadyExistsAsDirectory", "{", "Object", ":", "object", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "n", ",", "probe", ".", "NewError", "(", "BucketDoesNotExist", "{", "Bucket", ":", "bucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "n", ",", "probe", ".", "NewError", "(", "BucketInvalid", "{", "Bucket", ":", "bucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "n", ",", "probe", ".", "NewError", "(", "ObjectMissing", "{", "}", ")", "\n", "}", "\n", "return", "n", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "n", ",", "nil", "\n", "}" ]
// Put - upload an object with custom metadata.
[ "Put", "-", "upload", "an", "object", "with", "custom", "metadata", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L778-L867
train
minio/mc
cmd/client-s3.go
removeIncompleteObjects
func (c *s3Client) removeIncompleteObjects(bucket string, objectsCh <-chan string) <-chan minio.RemoveObjectError { removeObjectErrorCh := make(chan minio.RemoveObjectError) // Goroutine reads from objectsCh and sends error to removeObjectErrorCh if any. go func() { defer close(removeObjectErrorCh) for object := range objectsCh { if err := c.api.RemoveIncompleteUpload(bucket, object); err != nil { removeObjectErrorCh <- minio.RemoveObjectError{ObjectName: object, Err: err} } } }() return removeObjectErrorCh }
go
func (c *s3Client) removeIncompleteObjects(bucket string, objectsCh <-chan string) <-chan minio.RemoveObjectError { removeObjectErrorCh := make(chan minio.RemoveObjectError) // Goroutine reads from objectsCh and sends error to removeObjectErrorCh if any. go func() { defer close(removeObjectErrorCh) for object := range objectsCh { if err := c.api.RemoveIncompleteUpload(bucket, object); err != nil { removeObjectErrorCh <- minio.RemoveObjectError{ObjectName: object, Err: err} } } }() return removeObjectErrorCh }
[ "func", "(", "c", "*", "s3Client", ")", "removeIncompleteObjects", "(", "bucket", "string", ",", "objectsCh", "<-", "chan", "string", ")", "<-", "chan", "minio", ".", "RemoveObjectError", "{", "removeObjectErrorCh", ":=", "make", "(", "chan", "minio", ".", "RemoveObjectError", ")", "\n\n", "// Goroutine reads from objectsCh and sends error to removeObjectErrorCh if any.", "go", "func", "(", ")", "{", "defer", "close", "(", "removeObjectErrorCh", ")", "\n\n", "for", "object", ":=", "range", "objectsCh", "{", "if", "err", ":=", "c", ".", "api", ".", "RemoveIncompleteUpload", "(", "bucket", ",", "object", ")", ";", "err", "!=", "nil", "{", "removeObjectErrorCh", "<-", "minio", ".", "RemoveObjectError", "{", "ObjectName", ":", "object", ",", "Err", ":", "err", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "removeObjectErrorCh", "\n", "}" ]
// Remove incomplete uploads.
[ "Remove", "incomplete", "uploads", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L870-L885
train
minio/mc
cmd/client-s3.go
MakeBucket
func (c *s3Client) MakeBucket(region string, ignoreExisting bool) *probe.Error { bucket, object := c.url2BucketAndObject() if bucket == "" { return probe.NewError(BucketNameEmpty{}) } if object != "" { if strings.HasSuffix(object, "/") { retry: if _, e := c.api.PutObject(bucket, object, bytes.NewReader([]byte("")), 0, minio.PutObjectOptions{}); e != nil { switch minio.ToErrorResponse(e).Code { case "NoSuchBucket": e = c.api.MakeBucket(bucket, region) if e != nil { return probe.NewError(e) } goto retry } return probe.NewError(e) } return nil } return probe.NewError(BucketNameTopLevel{}) } e := c.api.MakeBucket(bucket, region) if e != nil { // Ignore bucket already existing error when ignoreExisting flag is enabled if ignoreExisting { switch minio.ToErrorResponse(e).Code { case "BucketAlreadyOwnedByYou": fallthrough case "BucketAlreadyExists": return nil } } return probe.NewError(e) } return nil }
go
func (c *s3Client) MakeBucket(region string, ignoreExisting bool) *probe.Error { bucket, object := c.url2BucketAndObject() if bucket == "" { return probe.NewError(BucketNameEmpty{}) } if object != "" { if strings.HasSuffix(object, "/") { retry: if _, e := c.api.PutObject(bucket, object, bytes.NewReader([]byte("")), 0, minio.PutObjectOptions{}); e != nil { switch minio.ToErrorResponse(e).Code { case "NoSuchBucket": e = c.api.MakeBucket(bucket, region) if e != nil { return probe.NewError(e) } goto retry } return probe.NewError(e) } return nil } return probe.NewError(BucketNameTopLevel{}) } e := c.api.MakeBucket(bucket, region) if e != nil { // Ignore bucket already existing error when ignoreExisting flag is enabled if ignoreExisting { switch minio.ToErrorResponse(e).Code { case "BucketAlreadyOwnedByYou": fallthrough case "BucketAlreadyExists": return nil } } return probe.NewError(e) } return nil }
[ "func", "(", "c", "*", "s3Client", ")", "MakeBucket", "(", "region", "string", ",", "ignoreExisting", "bool", ")", "*", "probe", ".", "Error", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "if", "bucket", "==", "\"", "\"", "{", "return", "probe", ".", "NewError", "(", "BucketNameEmpty", "{", "}", ")", "\n", "}", "\n", "if", "object", "!=", "\"", "\"", "{", "if", "strings", ".", "HasSuffix", "(", "object", ",", "\"", "\"", ")", "{", "retry", ":", "if", "_", ",", "e", ":=", "c", ".", "api", ".", "PutObject", "(", "bucket", ",", "object", ",", "bytes", ".", "NewReader", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "0", ",", "minio", ".", "PutObjectOptions", "{", "}", ")", ";", "e", "!=", "nil", "{", "switch", "minio", ".", "ToErrorResponse", "(", "e", ")", ".", "Code", "{", "case", "\"", "\"", ":", "e", "=", "c", ".", "api", ".", "MakeBucket", "(", "bucket", ",", "region", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "goto", "retry", "\n", "}", "\n", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "probe", ".", "NewError", "(", "BucketNameTopLevel", "{", "}", ")", "\n", "}", "\n\n", "e", ":=", "c", ".", "api", ".", "MakeBucket", "(", "bucket", ",", "region", ")", "\n", "if", "e", "!=", "nil", "{", "// Ignore bucket already existing error when ignoreExisting flag is enabled", "if", "ignoreExisting", "{", "switch", "minio", ".", "ToErrorResponse", "(", "e", ")", ".", "Code", "{", "case", "\"", "\"", ":", "fallthrough", "\n", "case", "\"", "\"", ":", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MakeBucket - make a new bucket.
[ "MakeBucket", "-", "make", "a", "new", "bucket", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L984-L1022
train
minio/mc
cmd/client-s3.go
GetAccessRules
func (c *s3Client) GetAccessRules() (map[string]string, *probe.Error) { bucket, object := c.url2BucketAndObject() if bucket == "" { return map[string]string{}, probe.NewError(BucketNameEmpty{}) } policies := map[string]string{} policyStr, e := c.api.GetBucketPolicy(bucket) if e != nil { return nil, probe.NewError(e) } if policyStr == "" { return policies, nil } var p policy.BucketAccessPolicy if e = json.Unmarshal([]byte(policyStr), &p); e != nil { return nil, probe.NewError(e) } policyRules := policy.GetPolicies(p.Statements, bucket, object) // Hide policy data structure at this level for k, v := range policyRules { policies[k] = string(v) } return policies, nil }
go
func (c *s3Client) GetAccessRules() (map[string]string, *probe.Error) { bucket, object := c.url2BucketAndObject() if bucket == "" { return map[string]string{}, probe.NewError(BucketNameEmpty{}) } policies := map[string]string{} policyStr, e := c.api.GetBucketPolicy(bucket) if e != nil { return nil, probe.NewError(e) } if policyStr == "" { return policies, nil } var p policy.BucketAccessPolicy if e = json.Unmarshal([]byte(policyStr), &p); e != nil { return nil, probe.NewError(e) } policyRules := policy.GetPolicies(p.Statements, bucket, object) // Hide policy data structure at this level for k, v := range policyRules { policies[k] = string(v) } return policies, nil }
[ "func", "(", "c", "*", "s3Client", ")", "GetAccessRules", "(", ")", "(", "map", "[", "string", "]", "string", ",", "*", "probe", ".", "Error", ")", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "if", "bucket", "==", "\"", "\"", "{", "return", "map", "[", "string", "]", "string", "{", "}", ",", "probe", ".", "NewError", "(", "BucketNameEmpty", "{", "}", ")", "\n", "}", "\n", "policies", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "policyStr", ",", "e", ":=", "c", ".", "api", ".", "GetBucketPolicy", "(", "bucket", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "if", "policyStr", "==", "\"", "\"", "{", "return", "policies", ",", "nil", "\n", "}", "\n", "var", "p", "policy", ".", "BucketAccessPolicy", "\n", "if", "e", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "policyStr", ")", ",", "&", "p", ")", ";", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "policyRules", ":=", "policy", ".", "GetPolicies", "(", "p", ".", "Statements", ",", "bucket", ",", "object", ")", "\n", "// Hide policy data structure at this level", "for", "k", ",", "v", ":=", "range", "policyRules", "{", "policies", "[", "k", "]", "=", "string", "(", "v", ")", "\n", "}", "\n", "return", "policies", ",", "nil", "\n", "}" ]
// GetAccessRules - get configured policies from the server
[ "GetAccessRules", "-", "get", "configured", "policies", "from", "the", "server" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1025-L1048
train
minio/mc
cmd/client-s3.go
GetAccess
func (c *s3Client) GetAccess() (string, string, *probe.Error) { bucket, object := c.url2BucketAndObject() if bucket == "" { return "", "", probe.NewError(BucketNameEmpty{}) } policyStr, e := c.api.GetBucketPolicy(bucket) if e != nil { return "", "", probe.NewError(e) } if policyStr == "" { return string(policy.BucketPolicyNone), policyStr, nil } var p policy.BucketAccessPolicy if e = json.Unmarshal([]byte(policyStr), &p); e != nil { return "", "", probe.NewError(e) } pType := string(policy.GetPolicy(p.Statements, bucket, object)) if pType == string(policy.BucketPolicyNone) && policyStr != "" { pType = "custom" } return pType, policyStr, nil }
go
func (c *s3Client) GetAccess() (string, string, *probe.Error) { bucket, object := c.url2BucketAndObject() if bucket == "" { return "", "", probe.NewError(BucketNameEmpty{}) } policyStr, e := c.api.GetBucketPolicy(bucket) if e != nil { return "", "", probe.NewError(e) } if policyStr == "" { return string(policy.BucketPolicyNone), policyStr, nil } var p policy.BucketAccessPolicy if e = json.Unmarshal([]byte(policyStr), &p); e != nil { return "", "", probe.NewError(e) } pType := string(policy.GetPolicy(p.Statements, bucket, object)) if pType == string(policy.BucketPolicyNone) && policyStr != "" { pType = "custom" } return pType, policyStr, nil }
[ "func", "(", "c", "*", "s3Client", ")", "GetAccess", "(", ")", "(", "string", ",", "string", ",", "*", "probe", ".", "Error", ")", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "if", "bucket", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "probe", ".", "NewError", "(", "BucketNameEmpty", "{", "}", ")", "\n", "}", "\n", "policyStr", ",", "e", ":=", "c", ".", "api", ".", "GetBucketPolicy", "(", "bucket", ")", "\n", "if", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "if", "policyStr", "==", "\"", "\"", "{", "return", "string", "(", "policy", ".", "BucketPolicyNone", ")", ",", "policyStr", ",", "nil", "\n", "}", "\n", "var", "p", "policy", ".", "BucketAccessPolicy", "\n", "if", "e", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "policyStr", ")", ",", "&", "p", ")", ";", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "pType", ":=", "string", "(", "policy", ".", "GetPolicy", "(", "p", ".", "Statements", ",", "bucket", ",", "object", ")", ")", "\n", "if", "pType", "==", "string", "(", "policy", ".", "BucketPolicyNone", ")", "&&", "policyStr", "!=", "\"", "\"", "{", "pType", "=", "\"", "\"", "\n", "}", "\n", "return", "pType", ",", "policyStr", ",", "nil", "\n", "}" ]
// GetAccess get access policy permissions.
[ "GetAccess", "get", "access", "policy", "permissions", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1051-L1072
train
minio/mc
cmd/client-s3.go
SetAccess
func (c *s3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error { bucket, object := c.url2BucketAndObject() if bucket == "" { return probe.NewError(BucketNameEmpty{}) } if isJSON { if e := c.api.SetBucketPolicy(bucket, bucketPolicy); e != nil { return probe.NewError(e) } return nil } policyStr, e := c.api.GetBucketPolicy(bucket) if e != nil { return probe.NewError(e) } var p = policy.BucketAccessPolicy{Version: "2012-10-17"} if policyStr != "" { if e = json.Unmarshal([]byte(policyStr), &p); e != nil { return probe.NewError(e) } } p.Statements = policy.SetPolicy(p.Statements, policy.BucketPolicy(bucketPolicy), bucket, object) if len(p.Statements) == 0 { if e = c.api.SetBucketPolicy(bucket, ""); e != nil { return probe.NewError(e) } return nil } policyB, e := json.Marshal(p) if e != nil { return probe.NewError(e) } if e = c.api.SetBucketPolicy(bucket, string(policyB)); e != nil { return probe.NewError(e) } return nil }
go
func (c *s3Client) SetAccess(bucketPolicy string, isJSON bool) *probe.Error { bucket, object := c.url2BucketAndObject() if bucket == "" { return probe.NewError(BucketNameEmpty{}) } if isJSON { if e := c.api.SetBucketPolicy(bucket, bucketPolicy); e != nil { return probe.NewError(e) } return nil } policyStr, e := c.api.GetBucketPolicy(bucket) if e != nil { return probe.NewError(e) } var p = policy.BucketAccessPolicy{Version: "2012-10-17"} if policyStr != "" { if e = json.Unmarshal([]byte(policyStr), &p); e != nil { return probe.NewError(e) } } p.Statements = policy.SetPolicy(p.Statements, policy.BucketPolicy(bucketPolicy), bucket, object) if len(p.Statements) == 0 { if e = c.api.SetBucketPolicy(bucket, ""); e != nil { return probe.NewError(e) } return nil } policyB, e := json.Marshal(p) if e != nil { return probe.NewError(e) } if e = c.api.SetBucketPolicy(bucket, string(policyB)); e != nil { return probe.NewError(e) } return nil }
[ "func", "(", "c", "*", "s3Client", ")", "SetAccess", "(", "bucketPolicy", "string", ",", "isJSON", "bool", ")", "*", "probe", ".", "Error", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "if", "bucket", "==", "\"", "\"", "{", "return", "probe", ".", "NewError", "(", "BucketNameEmpty", "{", "}", ")", "\n", "}", "\n", "if", "isJSON", "{", "if", "e", ":=", "c", ".", "api", ".", "SetBucketPolicy", "(", "bucket", ",", "bucketPolicy", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "policyStr", ",", "e", ":=", "c", ".", "api", ".", "GetBucketPolicy", "(", "bucket", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "var", "p", "=", "policy", ".", "BucketAccessPolicy", "{", "Version", ":", "\"", "\"", "}", "\n", "if", "policyStr", "!=", "\"", "\"", "{", "if", "e", "=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "policyStr", ")", ",", "&", "p", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "}", "\n", "p", ".", "Statements", "=", "policy", ".", "SetPolicy", "(", "p", ".", "Statements", ",", "policy", ".", "BucketPolicy", "(", "bucketPolicy", ")", ",", "bucket", ",", "object", ")", "\n", "if", "len", "(", "p", ".", "Statements", ")", "==", "0", "{", "if", "e", "=", "c", ".", "api", ".", "SetBucketPolicy", "(", "bucket", ",", "\"", "\"", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "policyB", ",", "e", ":=", "json", ".", "Marshal", "(", "p", ")", "\n", "if", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "if", "e", "=", "c", ".", "api", ".", "SetBucketPolicy", "(", "bucket", ",", "string", "(", "policyB", ")", ")", ";", "e", "!=", "nil", "{", "return", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetAccess set access policy permissions.
[ "SetAccess", "set", "access", "policy", "permissions", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1075-L1111
train
minio/mc
cmd/client-s3.go
listObjectWrapper
func (c *s3Client) listObjectWrapper(bucket, object string, isRecursive bool, doneCh chan struct{}) <-chan minio.ObjectInfo { if isAmazon(c.targetURL.Host) || isAmazonAccelerated(c.targetURL.Host) { return c.api.ListObjectsV2(bucket, object, isRecursive, doneCh) } return c.api.ListObjects(bucket, object, isRecursive, doneCh) }
go
func (c *s3Client) listObjectWrapper(bucket, object string, isRecursive bool, doneCh chan struct{}) <-chan minio.ObjectInfo { if isAmazon(c.targetURL.Host) || isAmazonAccelerated(c.targetURL.Host) { return c.api.ListObjectsV2(bucket, object, isRecursive, doneCh) } return c.api.ListObjects(bucket, object, isRecursive, doneCh) }
[ "func", "(", "c", "*", "s3Client", ")", "listObjectWrapper", "(", "bucket", ",", "object", "string", ",", "isRecursive", "bool", ",", "doneCh", "chan", "struct", "{", "}", ")", "<-", "chan", "minio", ".", "ObjectInfo", "{", "if", "isAmazon", "(", "c", ".", "targetURL", ".", "Host", ")", "||", "isAmazonAccelerated", "(", "c", ".", "targetURL", ".", "Host", ")", "{", "return", "c", ".", "api", ".", "ListObjectsV2", "(", "bucket", ",", "object", ",", "isRecursive", ",", "doneCh", ")", "\n", "}", "\n", "return", "c", ".", "api", ".", "ListObjects", "(", "bucket", ",", "object", ",", "isRecursive", ",", "doneCh", ")", "\n", "}" ]
// listObjectWrapper - select ObjectList version depending on the target hostname
[ "listObjectWrapper", "-", "select", "ObjectList", "version", "depending", "on", "the", "target", "hostname" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1114-L1119
train
minio/mc
cmd/client-s3.go
getObjectStat
func (c *s3Client) getObjectStat(bucket, object string, opts minio.StatObjectOptions) (*clientContent, *probe.Error) { objectMetadata := &clientContent{} objectStat, e := c.api.StatObject(bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "AccessDenied" { return nil, probe.NewError(PathInsufficientPermission{Path: c.targetURL.String()}) } if errResponse.Code == "NoSuchBucket" { return nil, probe.NewError(BucketDoesNotExist{ Bucket: bucket, }) } if errResponse.Code == "InvalidBucketName" { return nil, probe.NewError(BucketInvalid{ Bucket: bucket, }) } if errResponse.Code == "NoSuchKey" { return nil, probe.NewError(ObjectMissing{}) } return nil, probe.NewError(e) } objectMetadata.URL = *c.targetURL objectMetadata.Time = objectStat.LastModified objectMetadata.Size = objectStat.Size objectMetadata.ETag = objectStat.ETag objectMetadata.Expires = objectStat.Expires objectMetadata.Type = os.FileMode(0664) objectMetadata.Metadata = map[string]string{} objectMetadata.EncryptionHeaders = map[string]string{} objectMetadata.Metadata["Content-Type"] = objectStat.ContentType for k, v := range objectStat.Metadata { isCSEHeader := false for _, header := range cseHeaders { if (strings.Compare(strings.ToLower(header), strings.ToLower(k)) == 0) || strings.HasPrefix(strings.ToLower(serverEncryptionKeyPrefix), strings.ToLower(k)) { if len(v) > 0 { objectMetadata.EncryptionHeaders[k] = v[0] } isCSEHeader = true break } } if !isCSEHeader { if len(v) > 0 { objectMetadata.Metadata[k] = v[0] } } } objectMetadata.ETag = objectStat.ETag return objectMetadata, nil }
go
func (c *s3Client) getObjectStat(bucket, object string, opts minio.StatObjectOptions) (*clientContent, *probe.Error) { objectMetadata := &clientContent{} objectStat, e := c.api.StatObject(bucket, object, opts) if e != nil { errResponse := minio.ToErrorResponse(e) if errResponse.Code == "AccessDenied" { return nil, probe.NewError(PathInsufficientPermission{Path: c.targetURL.String()}) } if errResponse.Code == "NoSuchBucket" { return nil, probe.NewError(BucketDoesNotExist{ Bucket: bucket, }) } if errResponse.Code == "InvalidBucketName" { return nil, probe.NewError(BucketInvalid{ Bucket: bucket, }) } if errResponse.Code == "NoSuchKey" { return nil, probe.NewError(ObjectMissing{}) } return nil, probe.NewError(e) } objectMetadata.URL = *c.targetURL objectMetadata.Time = objectStat.LastModified objectMetadata.Size = objectStat.Size objectMetadata.ETag = objectStat.ETag objectMetadata.Expires = objectStat.Expires objectMetadata.Type = os.FileMode(0664) objectMetadata.Metadata = map[string]string{} objectMetadata.EncryptionHeaders = map[string]string{} objectMetadata.Metadata["Content-Type"] = objectStat.ContentType for k, v := range objectStat.Metadata { isCSEHeader := false for _, header := range cseHeaders { if (strings.Compare(strings.ToLower(header), strings.ToLower(k)) == 0) || strings.HasPrefix(strings.ToLower(serverEncryptionKeyPrefix), strings.ToLower(k)) { if len(v) > 0 { objectMetadata.EncryptionHeaders[k] = v[0] } isCSEHeader = true break } } if !isCSEHeader { if len(v) > 0 { objectMetadata.Metadata[k] = v[0] } } } objectMetadata.ETag = objectStat.ETag return objectMetadata, nil }
[ "func", "(", "c", "*", "s3Client", ")", "getObjectStat", "(", "bucket", ",", "object", "string", ",", "opts", "minio", ".", "StatObjectOptions", ")", "(", "*", "clientContent", ",", "*", "probe", ".", "Error", ")", "{", "objectMetadata", ":=", "&", "clientContent", "{", "}", "\n", "objectStat", ",", "e", ":=", "c", ".", "api", ".", "StatObject", "(", "bucket", ",", "object", ",", "opts", ")", "\n", "if", "e", "!=", "nil", "{", "errResponse", ":=", "minio", ".", "ToErrorResponse", "(", "e", ")", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "PathInsufficientPermission", "{", "Path", ":", "c", ".", "targetURL", ".", "String", "(", ")", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "BucketDoesNotExist", "{", "Bucket", ":", "bucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "BucketInvalid", "{", "Bucket", ":", "bucket", ",", "}", ")", "\n", "}", "\n", "if", "errResponse", ".", "Code", "==", "\"", "\"", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "ObjectMissing", "{", "}", ")", "\n", "}", "\n", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "objectMetadata", ".", "URL", "=", "*", "c", ".", "targetURL", "\n", "objectMetadata", ".", "Time", "=", "objectStat", ".", "LastModified", "\n", "objectMetadata", ".", "Size", "=", "objectStat", ".", "Size", "\n", "objectMetadata", ".", "ETag", "=", "objectStat", ".", "ETag", "\n", "objectMetadata", ".", "Expires", "=", "objectStat", ".", "Expires", "\n", "objectMetadata", ".", "Type", "=", "os", ".", "FileMode", "(", "0664", ")", "\n", "objectMetadata", ".", "Metadata", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "objectMetadata", ".", "EncryptionHeaders", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "objectMetadata", ".", "Metadata", "[", "\"", "\"", "]", "=", "objectStat", ".", "ContentType", "\n", "for", "k", ",", "v", ":=", "range", "objectStat", ".", "Metadata", "{", "isCSEHeader", ":=", "false", "\n", "for", "_", ",", "header", ":=", "range", "cseHeaders", "{", "if", "(", "strings", ".", "Compare", "(", "strings", ".", "ToLower", "(", "header", ")", ",", "strings", ".", "ToLower", "(", "k", ")", ")", "==", "0", ")", "||", "strings", ".", "HasPrefix", "(", "strings", ".", "ToLower", "(", "serverEncryptionKeyPrefix", ")", ",", "strings", ".", "ToLower", "(", "k", ")", ")", "{", "if", "len", "(", "v", ")", ">", "0", "{", "objectMetadata", ".", "EncryptionHeaders", "[", "k", "]", "=", "v", "[", "0", "]", "\n", "}", "\n", "isCSEHeader", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "isCSEHeader", "{", "if", "len", "(", "v", ")", ">", "0", "{", "objectMetadata", ".", "Metadata", "[", "k", "]", "=", "v", "[", "0", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "objectMetadata", ".", "ETag", "=", "objectStat", ".", "ETag", "\n", "return", "objectMetadata", ",", "nil", "\n", "}" ]
// getObjectStat returns the metadata of an object from a HEAD call.
[ "getObjectStat", "returns", "the", "metadata", "of", "an", "object", "from", "a", "HEAD", "call", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1229-L1281
train
minio/mc
cmd/client-s3.go
url2BucketAndObject
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { path := c.targetURL.Path // Convert any virtual host styled requests. // // For the time being this check is introduced for S3, // If you have custom virtual styled hosts please. // List them below. if c.virtualStyle { var bucket string hostIndex := strings.Index(c.targetURL.Host, "s3") if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate") } if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis") } if hostIndex > 0 { bucket = c.targetURL.Host[:hostIndex-1] path = string(c.targetURL.Separator) + bucket + c.targetURL.Path } } tokens := splitStr(path, string(c.targetURL.Separator), 3) return tokens[1], tokens[2] }
go
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) { path := c.targetURL.Path // Convert any virtual host styled requests. // // For the time being this check is introduced for S3, // If you have custom virtual styled hosts please. // List them below. if c.virtualStyle { var bucket string hostIndex := strings.Index(c.targetURL.Host, "s3") if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate") } if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis") } if hostIndex > 0 { bucket = c.targetURL.Host[:hostIndex-1] path = string(c.targetURL.Separator) + bucket + c.targetURL.Path } } tokens := splitStr(path, string(c.targetURL.Separator), 3) return tokens[1], tokens[2] }
[ "func", "(", "c", "*", "s3Client", ")", "url2BucketAndObject", "(", ")", "(", "bucketName", ",", "objectName", "string", ")", "{", "path", ":=", "c", ".", "targetURL", ".", "Path", "\n", "// Convert any virtual host styled requests.", "//", "// For the time being this check is introduced for S3,", "// If you have custom virtual styled hosts please.", "// List them below.", "if", "c", ".", "virtualStyle", "{", "var", "bucket", "string", "\n", "hostIndex", ":=", "strings", ".", "Index", "(", "c", ".", "targetURL", ".", "Host", ",", "\"", "\"", ")", "\n", "if", "hostIndex", "==", "-", "1", "{", "hostIndex", "=", "strings", ".", "Index", "(", "c", ".", "targetURL", ".", "Host", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "hostIndex", "==", "-", "1", "{", "hostIndex", "=", "strings", ".", "Index", "(", "c", ".", "targetURL", ".", "Host", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "hostIndex", ">", "0", "{", "bucket", "=", "c", ".", "targetURL", ".", "Host", "[", ":", "hostIndex", "-", "1", "]", "\n", "path", "=", "string", "(", "c", ".", "targetURL", ".", "Separator", ")", "+", "bucket", "+", "c", ".", "targetURL", ".", "Path", "\n", "}", "\n", "}", "\n", "tokens", ":=", "splitStr", "(", "path", ",", "string", "(", "c", ".", "targetURL", ".", "Separator", ")", ",", "3", ")", "\n", "return", "tokens", "[", "1", "]", ",", "tokens", "[", "2", "]", "\n", "}" ]
// url2BucketAndObject gives bucketName and objectName from URL path.
[ "url2BucketAndObject", "gives", "bucketName", "and", "objectName", "from", "URL", "path", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1317-L1340
train
minio/mc
cmd/client-s3.go
splitPath
func (c *s3Client) splitPath(path string) (bucketName, objectName string) { path = strings.TrimPrefix(path, string(c.targetURL.Separator)) // Handle path if its virtual style. if c.virtualStyle { hostIndex := strings.Index(c.targetURL.Host, "s3") if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate") } if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis") } if hostIndex > 0 { bucketName = c.targetURL.Host[:hostIndex-1] objectName = path return bucketName, objectName } } tokens := splitStr(path, string(c.targetURL.Separator), 2) return tokens[0], tokens[1] }
go
func (c *s3Client) splitPath(path string) (bucketName, objectName string) { path = strings.TrimPrefix(path, string(c.targetURL.Separator)) // Handle path if its virtual style. if c.virtualStyle { hostIndex := strings.Index(c.targetURL.Host, "s3") if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "s3-accelerate") } if hostIndex == -1 { hostIndex = strings.Index(c.targetURL.Host, "storage.googleapis") } if hostIndex > 0 { bucketName = c.targetURL.Host[:hostIndex-1] objectName = path return bucketName, objectName } } tokens := splitStr(path, string(c.targetURL.Separator), 2) return tokens[0], tokens[1] }
[ "func", "(", "c", "*", "s3Client", ")", "splitPath", "(", "path", "string", ")", "(", "bucketName", ",", "objectName", "string", ")", "{", "path", "=", "strings", ".", "TrimPrefix", "(", "path", ",", "string", "(", "c", ".", "targetURL", ".", "Separator", ")", ")", "\n\n", "// Handle path if its virtual style.", "if", "c", ".", "virtualStyle", "{", "hostIndex", ":=", "strings", ".", "Index", "(", "c", ".", "targetURL", ".", "Host", ",", "\"", "\"", ")", "\n", "if", "hostIndex", "==", "-", "1", "{", "hostIndex", "=", "strings", ".", "Index", "(", "c", ".", "targetURL", ".", "Host", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "hostIndex", "==", "-", "1", "{", "hostIndex", "=", "strings", ".", "Index", "(", "c", ".", "targetURL", ".", "Host", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "hostIndex", ">", "0", "{", "bucketName", "=", "c", ".", "targetURL", ".", "Host", "[", ":", "hostIndex", "-", "1", "]", "\n", "objectName", "=", "path", "\n", "return", "bucketName", ",", "objectName", "\n", "}", "\n", "}", "\n\n", "tokens", ":=", "splitStr", "(", "path", ",", "string", "(", "c", ".", "targetURL", ".", "Separator", ")", ",", "2", ")", "\n", "return", "tokens", "[", "0", "]", ",", "tokens", "[", "1", "]", "\n", "}" ]
// splitPath split path into bucket and object.
[ "splitPath", "split", "path", "into", "bucket", "and", "object", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1343-L1364
train
minio/mc
cmd/client-s3.go
objectMultipartInfo2ClientContent
func (c *s3Client) objectMultipartInfo2ClientContent(bucket string, entry minio.ObjectMultipartInfo) clientContent { content := clientContent{} url := *c.targetURL // Join bucket and incoming object key. url.Path = c.joinPath(bucket, entry.Key) content.URL = url content.Size = entry.Size content.Time = entry.Initiated if strings.HasSuffix(entry.Key, "/") { content.Type = os.ModeDir } else { content.Type = os.ModeTemporary } return content }
go
func (c *s3Client) objectMultipartInfo2ClientContent(bucket string, entry minio.ObjectMultipartInfo) clientContent { content := clientContent{} url := *c.targetURL // Join bucket and incoming object key. url.Path = c.joinPath(bucket, entry.Key) content.URL = url content.Size = entry.Size content.Time = entry.Initiated if strings.HasSuffix(entry.Key, "/") { content.Type = os.ModeDir } else { content.Type = os.ModeTemporary } return content }
[ "func", "(", "c", "*", "s3Client", ")", "objectMultipartInfo2ClientContent", "(", "bucket", "string", ",", "entry", "minio", ".", "ObjectMultipartInfo", ")", "clientContent", "{", "content", ":=", "clientContent", "{", "}", "\n", "url", ":=", "*", "c", ".", "targetURL", "\n", "// Join bucket and incoming object key.", "url", ".", "Path", "=", "c", ".", "joinPath", "(", "bucket", ",", "entry", ".", "Key", ")", "\n", "content", ".", "URL", "=", "url", "\n", "content", ".", "Size", "=", "entry", ".", "Size", "\n", "content", ".", "Time", "=", "entry", ".", "Initiated", "\n\n", "if", "strings", ".", "HasSuffix", "(", "entry", ".", "Key", ",", "\"", "\"", ")", "{", "content", ".", "Type", "=", "os", ".", "ModeDir", "\n", "}", "else", "{", "content", ".", "Type", "=", "os", ".", "ModeTemporary", "\n", "}", "\n\n", "return", "content", "\n", "}" ]
// Convert objectMultipartInfo to clientContent
[ "Convert", "objectMultipartInfo", "to", "clientContent" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1525-L1542
train
minio/mc
cmd/client-s3.go
joinPath
func (c *s3Client) joinPath(bucket string, objects ...string) string { p := string(c.targetURL.Separator) + bucket for _, o := range objects { p += string(c.targetURL.Separator) + o } return p }
go
func (c *s3Client) joinPath(bucket string, objects ...string) string { p := string(c.targetURL.Separator) + bucket for _, o := range objects { p += string(c.targetURL.Separator) + o } return p }
[ "func", "(", "c", "*", "s3Client", ")", "joinPath", "(", "bucket", "string", ",", "objects", "...", "string", ")", "string", "{", "p", ":=", "string", "(", "c", ".", "targetURL", ".", "Separator", ")", "+", "bucket", "\n", "for", "_", ",", "o", ":=", "range", "objects", "{", "p", "+=", "string", "(", "c", ".", "targetURL", ".", "Separator", ")", "+", "o", "\n", "}", "\n", "return", "p", "\n", "}" ]
// Returns new path by joining path segments with URL path separator.
[ "Returns", "new", "path", "by", "joining", "path", "segments", "with", "URL", "path", "separator", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1643-L1649
train
minio/mc
cmd/client-s3.go
objectInfo2ClientContent
func (c *s3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInfo) clientContent { content := clientContent{} url := *c.targetURL // Join bucket and incoming object key. url.Path = c.joinPath(bucket, entry.Key) content.URL = url content.Size = entry.Size content.ETag = entry.ETag content.Time = entry.LastModified if strings.HasSuffix(entry.Key, "/") && entry.Size == 0 && entry.LastModified.IsZero() { content.Type = os.ModeDir } else { content.Type = os.FileMode(0664) } return content }
go
func (c *s3Client) objectInfo2ClientContent(bucket string, entry minio.ObjectInfo) clientContent { content := clientContent{} url := *c.targetURL // Join bucket and incoming object key. url.Path = c.joinPath(bucket, entry.Key) content.URL = url content.Size = entry.Size content.ETag = entry.ETag content.Time = entry.LastModified if strings.HasSuffix(entry.Key, "/") && entry.Size == 0 && entry.LastModified.IsZero() { content.Type = os.ModeDir } else { content.Type = os.FileMode(0664) } return content }
[ "func", "(", "c", "*", "s3Client", ")", "objectInfo2ClientContent", "(", "bucket", "string", ",", "entry", "minio", ".", "ObjectInfo", ")", "clientContent", "{", "content", ":=", "clientContent", "{", "}", "\n", "url", ":=", "*", "c", ".", "targetURL", "\n", "// Join bucket and incoming object key.", "url", ".", "Path", "=", "c", ".", "joinPath", "(", "bucket", ",", "entry", ".", "Key", ")", "\n", "content", ".", "URL", "=", "url", "\n", "content", ".", "Size", "=", "entry", ".", "Size", "\n", "content", ".", "ETag", "=", "entry", ".", "ETag", "\n", "content", ".", "Time", "=", "entry", ".", "LastModified", "\n\n", "if", "strings", ".", "HasSuffix", "(", "entry", ".", "Key", ",", "\"", "\"", ")", "&&", "entry", ".", "Size", "==", "0", "&&", "entry", ".", "LastModified", ".", "IsZero", "(", ")", "{", "content", ".", "Type", "=", "os", ".", "ModeDir", "\n", "}", "else", "{", "content", ".", "Type", "=", "os", ".", "FileMode", "(", "0664", ")", "\n", "}", "\n\n", "return", "content", "\n", "}" ]
// Convert objectInfo to clientContent
[ "Convert", "objectInfo", "to", "clientContent" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1652-L1670
train
minio/mc
cmd/client-s3.go
bucketStat
func (c *s3Client) bucketStat(bucket string) (*clientContent, *probe.Error) { exists, e := c.api.BucketExists(bucket) if e != nil { return nil, probe.NewError(e) } if !exists { return nil, probe.NewError(BucketDoesNotExist{Bucket: bucket}) } return &clientContent{URL: *c.targetURL, Time: time.Unix(0, 0), Type: os.ModeDir}, nil }
go
func (c *s3Client) bucketStat(bucket string) (*clientContent, *probe.Error) { exists, e := c.api.BucketExists(bucket) if e != nil { return nil, probe.NewError(e) } if !exists { return nil, probe.NewError(BucketDoesNotExist{Bucket: bucket}) } return &clientContent{URL: *c.targetURL, Time: time.Unix(0, 0), Type: os.ModeDir}, nil }
[ "func", "(", "c", "*", "s3Client", ")", "bucketStat", "(", "bucket", "string", ")", "(", "*", "clientContent", ",", "*", "probe", ".", "Error", ")", "{", "exists", ",", "e", ":=", "c", ".", "api", ".", "BucketExists", "(", "bucket", ")", "\n", "if", "e", "!=", "nil", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "if", "!", "exists", "{", "return", "nil", ",", "probe", ".", "NewError", "(", "BucketDoesNotExist", "{", "Bucket", ":", "bucket", "}", ")", "\n", "}", "\n", "return", "&", "clientContent", "{", "URL", ":", "*", "c", ".", "targetURL", ",", "Time", ":", "time", ".", "Unix", "(", "0", ",", "0", ")", ",", "Type", ":", "os", ".", "ModeDir", "}", ",", "nil", "\n", "}" ]
// Returns bucket stat info of current bucket.
[ "Returns", "bucket", "stat", "info", "of", "current", "bucket", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1673-L1682
train
minio/mc
cmd/client-s3.go
ShareDownload
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) { bucket, object := c.url2BucketAndObject() // No additional request parameters are set for the time being. reqParams := make(url.Values) presignedURL, e := c.api.PresignedGetObject(bucket, object, expires, reqParams) if e != nil { return "", probe.NewError(e) } return presignedURL.String(), nil }
go
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) { bucket, object := c.url2BucketAndObject() // No additional request parameters are set for the time being. reqParams := make(url.Values) presignedURL, e := c.api.PresignedGetObject(bucket, object, expires, reqParams) if e != nil { return "", probe.NewError(e) } return presignedURL.String(), nil }
[ "func", "(", "c", "*", "s3Client", ")", "ShareDownload", "(", "expires", "time", ".", "Duration", ")", "(", "string", ",", "*", "probe", ".", "Error", ")", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "// No additional request parameters are set for the time being.", "reqParams", ":=", "make", "(", "url", ".", "Values", ")", "\n", "presignedURL", ",", "e", ":=", "c", ".", "api", ".", "PresignedGetObject", "(", "bucket", ",", "object", ",", "expires", ",", "reqParams", ")", "\n", "if", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "presignedURL", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// ShareDownload - get a usable presigned object url to share.
[ "ShareDownload", "-", "get", "a", "usable", "presigned", "object", "url", "to", "share", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1926-L1935
train
minio/mc
cmd/client-s3.go
ShareUpload
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) { bucket, object := c.url2BucketAndObject() p := minio.NewPostPolicy() if e := p.SetExpires(UTCNow().Add(expires)); e != nil { return "", nil, probe.NewError(e) } if strings.TrimSpace(contentType) != "" || contentType != "" { // No need to verify for error here, since we have stripped out spaces. p.SetContentType(contentType) } if e := p.SetBucket(bucket); e != nil { return "", nil, probe.NewError(e) } if isRecursive { if e := p.SetKeyStartsWith(object); e != nil { return "", nil, probe.NewError(e) } } else { if e := p.SetKey(object); e != nil { return "", nil, probe.NewError(e) } } u, m, e := c.api.PresignedPostPolicy(p) if e != nil { return "", nil, probe.NewError(e) } return u.String(), m, nil }
go
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (string, map[string]string, *probe.Error) { bucket, object := c.url2BucketAndObject() p := minio.NewPostPolicy() if e := p.SetExpires(UTCNow().Add(expires)); e != nil { return "", nil, probe.NewError(e) } if strings.TrimSpace(contentType) != "" || contentType != "" { // No need to verify for error here, since we have stripped out spaces. p.SetContentType(contentType) } if e := p.SetBucket(bucket); e != nil { return "", nil, probe.NewError(e) } if isRecursive { if e := p.SetKeyStartsWith(object); e != nil { return "", nil, probe.NewError(e) } } else { if e := p.SetKey(object); e != nil { return "", nil, probe.NewError(e) } } u, m, e := c.api.PresignedPostPolicy(p) if e != nil { return "", nil, probe.NewError(e) } return u.String(), m, nil }
[ "func", "(", "c", "*", "s3Client", ")", "ShareUpload", "(", "isRecursive", "bool", ",", "expires", "time", ".", "Duration", ",", "contentType", "string", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "*", "probe", ".", "Error", ")", "{", "bucket", ",", "object", ":=", "c", ".", "url2BucketAndObject", "(", ")", "\n", "p", ":=", "minio", ".", "NewPostPolicy", "(", ")", "\n", "if", "e", ":=", "p", ".", "SetExpires", "(", "UTCNow", "(", ")", ".", "Add", "(", "expires", ")", ")", ";", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "if", "strings", ".", "TrimSpace", "(", "contentType", ")", "!=", "\"", "\"", "||", "contentType", "!=", "\"", "\"", "{", "// No need to verify for error here, since we have stripped out spaces.", "p", ".", "SetContentType", "(", "contentType", ")", "\n", "}", "\n", "if", "e", ":=", "p", ".", "SetBucket", "(", "bucket", ")", ";", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "if", "isRecursive", "{", "if", "e", ":=", "p", ".", "SetKeyStartsWith", "(", "object", ")", ";", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "}", "else", "{", "if", "e", ":=", "p", ".", "SetKey", "(", "object", ")", ";", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "}", "\n", "u", ",", "m", ",", "e", ":=", "c", ".", "api", ".", "PresignedPostPolicy", "(", "p", ")", "\n", "if", "e", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "probe", ".", "NewError", "(", "e", ")", "\n", "}", "\n", "return", "u", ".", "String", "(", ")", ",", "m", ",", "nil", "\n", "}" ]
// ShareUpload - get data for presigned post http form upload.
[ "ShareUpload", "-", "get", "data", "for", "presigned", "post", "http", "form", "upload", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/client-s3.go#L1938-L1965
train
minio/mc
cmd/admin-top-locks.go
String
func (u lockMessage) String() string { timeFieldMaxLen := 20 resourceFieldMaxLen := -1 typeFieldMaxLen := 6 ownerFieldMaxLen := 20 lockState, timeDiff := getTimeDiff(u.Lock.Timestamp) return console.Colorize(lockState, newPrettyTable(" ", Field{"Time", timeFieldMaxLen}, Field{"Type", typeFieldMaxLen}, Field{"Owner", ownerFieldMaxLen}, Field{"Resource", resourceFieldMaxLen}, ).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource)) }
go
func (u lockMessage) String() string { timeFieldMaxLen := 20 resourceFieldMaxLen := -1 typeFieldMaxLen := 6 ownerFieldMaxLen := 20 lockState, timeDiff := getTimeDiff(u.Lock.Timestamp) return console.Colorize(lockState, newPrettyTable(" ", Field{"Time", timeFieldMaxLen}, Field{"Type", typeFieldMaxLen}, Field{"Owner", ownerFieldMaxLen}, Field{"Resource", resourceFieldMaxLen}, ).buildRow(timeDiff, u.Lock.Type, u.Lock.Owner, u.Lock.Resource)) }
[ "func", "(", "u", "lockMessage", ")", "String", "(", ")", "string", "{", "timeFieldMaxLen", ":=", "20", "\n", "resourceFieldMaxLen", ":=", "-", "1", "\n", "typeFieldMaxLen", ":=", "6", "\n", "ownerFieldMaxLen", ":=", "20", "\n\n", "lockState", ",", "timeDiff", ":=", "getTimeDiff", "(", "u", ".", "Lock", ".", "Timestamp", ")", "\n", "return", "console", ".", "Colorize", "(", "lockState", ",", "newPrettyTable", "(", "\"", "\"", ",", "Field", "{", "\"", "\"", ",", "timeFieldMaxLen", "}", ",", "Field", "{", "\"", "\"", ",", "typeFieldMaxLen", "}", ",", "Field", "{", "\"", "\"", ",", "ownerFieldMaxLen", "}", ",", "Field", "{", "\"", "\"", ",", "resourceFieldMaxLen", "}", ",", ")", ".", "buildRow", "(", "timeDiff", ",", "u", ".", "Lock", ".", "Type", ",", "u", ".", "Lock", ".", "Owner", ",", "u", ".", "Lock", ".", "Resource", ")", ")", "\n", "}" ]
// String colorized oldest locks message.
[ "String", "colorized", "oldest", "locks", "message", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-top-locks.go#L75-L88
train
minio/mc
cmd/admin-top-locks.go
checkAdminTopLocksSyntax
func checkAdminTopLocksSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 { cli.ShowCommandHelpAndExit(ctx, "locks", 1) // last argument is exit code } }
go
func checkAdminTopLocksSyntax(ctx *cli.Context) { if len(ctx.Args()) == 0 || len(ctx.Args()) > 1 { cli.ShowCommandHelpAndExit(ctx, "locks", 1) // last argument is exit code } }
[ "func", "checkAdminTopLocksSyntax", "(", "ctx", "*", "cli", ".", "Context", ")", "{", "if", "len", "(", "ctx", ".", "Args", "(", ")", ")", "==", "0", "||", "len", "(", "ctx", ".", "Args", "(", ")", ")", ">", "1", "{", "cli", ".", "ShowCommandHelpAndExit", "(", "ctx", ",", "\"", "\"", ",", "1", ")", "// last argument is exit code", "\n", "}", "\n", "}" ]
// checkAdminTopLocksSyntax - validate all the passed arguments
[ "checkAdminTopLocksSyntax", "-", "validate", "all", "the", "passed", "arguments" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-top-locks.go#L99-L103
train
minio/mc
cmd/admin-top-locks.go
printLocks
func printLocks(locks madmin.LockEntries) { if !globalJSON { printHeaders() } for _, entry := range locks { printMsg(lockMessage{Lock: entry}) } }
go
func printLocks(locks madmin.LockEntries) { if !globalJSON { printHeaders() } for _, entry := range locks { printMsg(lockMessage{Lock: entry}) } }
[ "func", "printLocks", "(", "locks", "madmin", ".", "LockEntries", ")", "{", "if", "!", "globalJSON", "{", "printHeaders", "(", ")", "\n", "}", "\n", "for", "_", ",", "entry", ":=", "range", "locks", "{", "printMsg", "(", "lockMessage", "{", "Lock", ":", "entry", "}", ")", "\n", "}", "\n", "}" ]
// Prints oldest locks.
[ "Prints", "oldest", "locks", "." ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/admin-top-locks.go#L144-L151
train
minio/mc
cmd/watch.go
NewWatcher
func NewWatcher(sessionStartTime time.Time) *Watcher { return &Watcher{ sessionStartTime: sessionStartTime, errorChan: make(chan *probe.Error), eventInfoChan: make(chan EventInfo), o: []*watchObject{}, } }
go
func NewWatcher(sessionStartTime time.Time) *Watcher { return &Watcher{ sessionStartTime: sessionStartTime, errorChan: make(chan *probe.Error), eventInfoChan: make(chan EventInfo), o: []*watchObject{}, } }
[ "func", "NewWatcher", "(", "sessionStartTime", "time", ".", "Time", ")", "*", "Watcher", "{", "return", "&", "Watcher", "{", "sessionStartTime", ":", "sessionStartTime", ",", "errorChan", ":", "make", "(", "chan", "*", "probe", ".", "Error", ")", ",", "eventInfoChan", ":", "make", "(", "chan", "EventInfo", ")", ",", "o", ":", "[", "]", "*", "watchObject", "{", "}", ",", "}", "\n", "}" ]
// NewWatcher creates a new watcher
[ "NewWatcher", "creates", "a", "new", "watcher" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/watch.go#L102-L109
train
minio/mc
cmd/watch.go
Join
func (w *Watcher) Join(client Client, recursive bool) *probe.Error { wo, err := client.Watch(watchParams{ recursive: recursive, events: []string{"put", "delete"}, }) if err != nil { return err } w.o = append(w.o, wo) // join monitoring waitgroup w.wg.Add(1) // wait for events and errors of individual client watchers // and sent then to eventsChan and errorsChan go func() { defer w.wg.Done() for { select { case event, ok := <-wo.Events(): if !ok { return } w.eventInfoChan <- event case err, ok := <-wo.Errors(): if !ok { return } w.errorChan <- err } } }() return nil }
go
func (w *Watcher) Join(client Client, recursive bool) *probe.Error { wo, err := client.Watch(watchParams{ recursive: recursive, events: []string{"put", "delete"}, }) if err != nil { return err } w.o = append(w.o, wo) // join monitoring waitgroup w.wg.Add(1) // wait for events and errors of individual client watchers // and sent then to eventsChan and errorsChan go func() { defer w.wg.Done() for { select { case event, ok := <-wo.Events(): if !ok { return } w.eventInfoChan <- event case err, ok := <-wo.Errors(): if !ok { return } w.errorChan <- err } } }() return nil }
[ "func", "(", "w", "*", "Watcher", ")", "Join", "(", "client", "Client", ",", "recursive", "bool", ")", "*", "probe", ".", "Error", "{", "wo", ",", "err", ":=", "client", ".", "Watch", "(", "watchParams", "{", "recursive", ":", "recursive", ",", "events", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "w", ".", "o", "=", "append", "(", "w", ".", "o", ",", "wo", ")", "\n\n", "// join monitoring waitgroup", "w", ".", "wg", ".", "Add", "(", "1", ")", "\n\n", "// wait for events and errors of individual client watchers", "// and sent then to eventsChan and errorsChan", "go", "func", "(", ")", "{", "defer", "w", ".", "wg", ".", "Done", "(", ")", "\n\n", "for", "{", "select", "{", "case", "event", ",", "ok", ":=", "<-", "wo", ".", "Events", "(", ")", ":", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "w", ".", "eventInfoChan", "<-", "event", "\n", "case", "err", ",", "ok", ":=", "<-", "wo", ".", "Errors", "(", ")", ":", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "w", ".", "errorChan", "<-", "err", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Join the watcher with client
[ "Join", "the", "watcher", "with", "client" ]
f0f156aca82e451c80b05d5be8eb01a04fee29dd
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/cmd/watch.go#L145-L183
train
boombuler/barcode
code39/encoder.go
Encode
func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.BarcodeIntCS, error) { if fullASCIIMode { var err error content, err = prepare(content) if err != nil { return nil, err } } else if strings.ContainsRune(content, '*') { return nil, errors.New("invalid data! try full ascii mode") } data := "*" + content if includeChecksum { data += getChecksum(content) } data += "*" result := new(utils.BitList) for i, r := range data { if i != 0 { result.AddBit(false) } info, ok := encodeTable[r] if !ok { return nil, errors.New("invalid data! try full ascii mode") } result.AddBit(info.data...) } checkSum, err := strconv.ParseInt(getChecksum(content), 10, 64) if err != nil { checkSum = 0 } return utils.New1DCodeIntCheckSum(barcode.TypeCode39, content, result, int(checkSum)), nil }
go
func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.BarcodeIntCS, error) { if fullASCIIMode { var err error content, err = prepare(content) if err != nil { return nil, err } } else if strings.ContainsRune(content, '*') { return nil, errors.New("invalid data! try full ascii mode") } data := "*" + content if includeChecksum { data += getChecksum(content) } data += "*" result := new(utils.BitList) for i, r := range data { if i != 0 { result.AddBit(false) } info, ok := encodeTable[r] if !ok { return nil, errors.New("invalid data! try full ascii mode") } result.AddBit(info.data...) } checkSum, err := strconv.ParseInt(getChecksum(content), 10, 64) if err != nil { checkSum = 0 } return utils.New1DCodeIntCheckSum(barcode.TypeCode39, content, result, int(checkSum)), nil }
[ "func", "Encode", "(", "content", "string", ",", "includeChecksum", "bool", ",", "fullASCIIMode", "bool", ")", "(", "barcode", ".", "BarcodeIntCS", ",", "error", ")", "{", "if", "fullASCIIMode", "{", "var", "err", "error", "\n", "content", ",", "err", "=", "prepare", "(", "content", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "if", "strings", ".", "ContainsRune", "(", "content", ",", "'*'", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "data", ":=", "\"", "\"", "+", "content", "\n", "if", "includeChecksum", "{", "data", "+=", "getChecksum", "(", "content", ")", "\n", "}", "\n", "data", "+=", "\"", "\"", "\n\n", "result", ":=", "new", "(", "utils", ".", "BitList", ")", "\n\n", "for", "i", ",", "r", ":=", "range", "data", "{", "if", "i", "!=", "0", "{", "result", ".", "AddBit", "(", "false", ")", "\n", "}", "\n\n", "info", ",", "ok", ":=", "encodeTable", "[", "r", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "result", ".", "AddBit", "(", "info", ".", "data", "...", ")", "\n", "}", "\n\n", "checkSum", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "getChecksum", "(", "content", ")", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "checkSum", "=", "0", "\n", "}", "\n", "return", "utils", ".", "New1DCodeIntCheckSum", "(", "barcode", ".", "TypeCode39", ",", "content", ",", "result", ",", "int", "(", "checkSum", ")", ")", ",", "nil", "\n", "}" ]
// Encode returns a code39 barcode for the given content // if includeChecksum is set to true, a checksum character is calculated and added to the content
[ "Encode", "returns", "a", "code39", "barcode", "for", "the", "given", "content", "if", "includeChecksum", "is", "set", "to", "true", "a", "checksum", "character", "is", "calculated", "and", "added", "to", "the", "content" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/code39/encoder.go#L116-L152
train
boombuler/barcode
utils/galoisfield.go
NewGaloisField
func NewGaloisField(pp, fieldSize, b int) *GaloisField { result := new(GaloisField) result.Size = fieldSize result.Base = b result.ALogTbl = make([]int, fieldSize) result.LogTbl = make([]int, fieldSize) x := 1 for i := 0; i < fieldSize; i++ { result.ALogTbl[i] = x x = x * 2 if x >= fieldSize { x = (x ^ pp) & (fieldSize - 1) } } for i := 0; i < fieldSize; i++ { result.LogTbl[result.ALogTbl[i]] = int(i) } return result }
go
func NewGaloisField(pp, fieldSize, b int) *GaloisField { result := new(GaloisField) result.Size = fieldSize result.Base = b result.ALogTbl = make([]int, fieldSize) result.LogTbl = make([]int, fieldSize) x := 1 for i := 0; i < fieldSize; i++ { result.ALogTbl[i] = x x = x * 2 if x >= fieldSize { x = (x ^ pp) & (fieldSize - 1) } } for i := 0; i < fieldSize; i++ { result.LogTbl[result.ALogTbl[i]] = int(i) } return result }
[ "func", "NewGaloisField", "(", "pp", ",", "fieldSize", ",", "b", "int", ")", "*", "GaloisField", "{", "result", ":=", "new", "(", "GaloisField", ")", "\n\n", "result", ".", "Size", "=", "fieldSize", "\n", "result", ".", "Base", "=", "b", "\n", "result", ".", "ALogTbl", "=", "make", "(", "[", "]", "int", ",", "fieldSize", ")", "\n", "result", ".", "LogTbl", "=", "make", "(", "[", "]", "int", ",", "fieldSize", ")", "\n\n", "x", ":=", "1", "\n", "for", "i", ":=", "0", ";", "i", "<", "fieldSize", ";", "i", "++", "{", "result", ".", "ALogTbl", "[", "i", "]", "=", "x", "\n", "x", "=", "x", "*", "2", "\n", "if", "x", ">=", "fieldSize", "{", "x", "=", "(", "x", "^", "pp", ")", "&", "(", "fieldSize", "-", "1", ")", "\n", "}", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "fieldSize", ";", "i", "++", "{", "result", ".", "LogTbl", "[", "result", ".", "ALogTbl", "[", "i", "]", "]", "=", "int", "(", "i", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// NewGaloisField creates a new galois field
[ "NewGaloisField", "creates", "a", "new", "galois", "field" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/galoisfield.go#L12-L34
train
boombuler/barcode
utils/galoisfield.go
Multiply
func (gf *GaloisField) Multiply(a, b int) int { if a == 0 || b == 0 { return 0 } return gf.ALogTbl[(gf.LogTbl[a]+gf.LogTbl[b])%(gf.Size-1)] }
go
func (gf *GaloisField) Multiply(a, b int) int { if a == 0 || b == 0 { return 0 } return gf.ALogTbl[(gf.LogTbl[a]+gf.LogTbl[b])%(gf.Size-1)] }
[ "func", "(", "gf", "*", "GaloisField", ")", "Multiply", "(", "a", ",", "b", "int", ")", "int", "{", "if", "a", "==", "0", "||", "b", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "gf", ".", "ALogTbl", "[", "(", "gf", ".", "LogTbl", "[", "a", "]", "+", "gf", ".", "LogTbl", "[", "b", "]", ")", "%", "(", "gf", ".", "Size", "-", "1", ")", "]", "\n", "}" ]
// Multiply multiplys two numbers
[ "Multiply", "multiplys", "two", "numbers" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/galoisfield.go#L46-L51
train
boombuler/barcode
utils/galoisfield.go
Divide
func (gf *GaloisField) Divide(a, b int) int { if b == 0 { panic("divide by zero") } else if a == 0 { return 0 } return gf.ALogTbl[(gf.LogTbl[a]-gf.LogTbl[b])%(gf.Size-1)] }
go
func (gf *GaloisField) Divide(a, b int) int { if b == 0 { panic("divide by zero") } else if a == 0 { return 0 } return gf.ALogTbl[(gf.LogTbl[a]-gf.LogTbl[b])%(gf.Size-1)] }
[ "func", "(", "gf", "*", "GaloisField", ")", "Divide", "(", "a", ",", "b", "int", ")", "int", "{", "if", "b", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "else", "if", "a", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "gf", ".", "ALogTbl", "[", "(", "gf", ".", "LogTbl", "[", "a", "]", "-", "gf", ".", "LogTbl", "[", "b", "]", ")", "%", "(", "gf", ".", "Size", "-", "1", ")", "]", "\n", "}" ]
// Divide divides two numbers
[ "Divide", "divides", "two", "numbers" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/galoisfield.go#L54-L61
train
boombuler/barcode
utils/gfpoly.go
GetCoefficient
func (gp *GFPoly) GetCoefficient(degree int) int { return gp.Coefficients[gp.Degree()-degree] }
go
func (gp *GFPoly) GetCoefficient(degree int) int { return gp.Coefficients[gp.Degree()-degree] }
[ "func", "(", "gp", "*", "GFPoly", ")", "GetCoefficient", "(", "degree", "int", ")", "int", "{", "return", "gp", ".", "Coefficients", "[", "gp", ".", "Degree", "(", ")", "-", "degree", "]", "\n", "}" ]
// GetCoefficient returns the coefficient of x ^ degree
[ "GetCoefficient", "returns", "the", "coefficient", "of", "x", "^", "degree" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/gfpoly.go#L17-L19
train
boombuler/barcode
utils/base1dcode.go
New1DCodeIntCheckSum
func New1DCodeIntCheckSum(codeKind, content string, bars *BitList, checksum int) barcode.BarcodeIntCS { return &base1DCodeIntCS{base1DCode{bars, codeKind, content}, checksum} }
go
func New1DCodeIntCheckSum(codeKind, content string, bars *BitList, checksum int) barcode.BarcodeIntCS { return &base1DCodeIntCS{base1DCode{bars, codeKind, content}, checksum} }
[ "func", "New1DCodeIntCheckSum", "(", "codeKind", ",", "content", "string", ",", "bars", "*", "BitList", ",", "checksum", "int", ")", "barcode", ".", "BarcodeIntCS", "{", "return", "&", "base1DCodeIntCS", "{", "base1DCode", "{", "bars", ",", "codeKind", ",", "content", "}", ",", "checksum", "}", "\n", "}" ]
// New1DCodeIntCheckSum creates a new 1D barcode where the bars are represented by the bits in the bars BitList
[ "New1DCodeIntCheckSum", "creates", "a", "new", "1D", "barcode", "where", "the", "bars", "are", "represented", "by", "the", "bits", "in", "the", "bars", "BitList" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/base1dcode.go#L50-L52
train
boombuler/barcode
utils/base1dcode.go
New1DCode
func New1DCode(codeKind, content string, bars *BitList) barcode.Barcode { return &base1DCode{bars, codeKind, content} }
go
func New1DCode(codeKind, content string, bars *BitList) barcode.Barcode { return &base1DCode{bars, codeKind, content} }
[ "func", "New1DCode", "(", "codeKind", ",", "content", "string", ",", "bars", "*", "BitList", ")", "barcode", ".", "Barcode", "{", "return", "&", "base1DCode", "{", "bars", ",", "codeKind", ",", "content", "}", "\n", "}" ]
// New1DCode creates a new 1D barcode where the bars are represented by the bits in the bars BitList
[ "New1DCode", "creates", "a", "new", "1D", "barcode", "where", "the", "bars", "are", "represented", "by", "the", "bits", "in", "the", "bars", "BitList" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/base1dcode.go#L55-L57
train
boombuler/barcode
code128/encode.go
Encode
func Encode(content string) (barcode.BarcodeIntCS, error) { contentRunes := strToRunes(content) if len(contentRunes) <= 0 || len(contentRunes) > 80 { return nil, fmt.Errorf("content length should be between 1 and 80 runes but got %d", len(contentRunes)) } idxList := getCodeIndexList(contentRunes) if idxList == nil { return nil, fmt.Errorf("\"%s\" could not be encoded", content) } result := new(utils.BitList) sum := 0 for i, idx := range idxList.GetBytes() { if i == 0 { sum = int(idx) } else { sum += i * int(idx) } result.AddBit(encodingTable[idx]...) } sum = sum % 103 result.AddBit(encodingTable[sum]...) result.AddBit(encodingTable[stopSymbol]...) return utils.New1DCodeIntCheckSum(barcode.TypeCode128, content, result, sum), nil }
go
func Encode(content string) (barcode.BarcodeIntCS, error) { contentRunes := strToRunes(content) if len(contentRunes) <= 0 || len(contentRunes) > 80 { return nil, fmt.Errorf("content length should be between 1 and 80 runes but got %d", len(contentRunes)) } idxList := getCodeIndexList(contentRunes) if idxList == nil { return nil, fmt.Errorf("\"%s\" could not be encoded", content) } result := new(utils.BitList) sum := 0 for i, idx := range idxList.GetBytes() { if i == 0 { sum = int(idx) } else { sum += i * int(idx) } result.AddBit(encodingTable[idx]...) } sum = sum % 103 result.AddBit(encodingTable[sum]...) result.AddBit(encodingTable[stopSymbol]...) return utils.New1DCodeIntCheckSum(barcode.TypeCode128, content, result, sum), nil }
[ "func", "Encode", "(", "content", "string", ")", "(", "barcode", ".", "BarcodeIntCS", ",", "error", ")", "{", "contentRunes", ":=", "strToRunes", "(", "content", ")", "\n", "if", "len", "(", "contentRunes", ")", "<=", "0", "||", "len", "(", "contentRunes", ")", ">", "80", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "contentRunes", ")", ")", "\n", "}", "\n", "idxList", ":=", "getCodeIndexList", "(", "contentRunes", ")", "\n\n", "if", "idxList", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "content", ")", "\n", "}", "\n\n", "result", ":=", "new", "(", "utils", ".", "BitList", ")", "\n", "sum", ":=", "0", "\n", "for", "i", ",", "idx", ":=", "range", "idxList", ".", "GetBytes", "(", ")", "{", "if", "i", "==", "0", "{", "sum", "=", "int", "(", "idx", ")", "\n", "}", "else", "{", "sum", "+=", "i", "*", "int", "(", "idx", ")", "\n", "}", "\n", "result", ".", "AddBit", "(", "encodingTable", "[", "idx", "]", "...", ")", "\n", "}", "\n", "sum", "=", "sum", "%", "103", "\n", "result", ".", "AddBit", "(", "encodingTable", "[", "sum", "]", "...", ")", "\n", "result", ".", "AddBit", "(", "encodingTable", "[", "stopSymbol", "]", "...", ")", "\n", "return", "utils", ".", "New1DCodeIntCheckSum", "(", "barcode", ".", "TypeCode128", ",", "content", ",", "result", ",", "sum", ")", ",", "nil", "\n", "}" ]
// Encode creates a Code 128 barcode for the given content
[ "Encode", "creates", "a", "Code", "128", "barcode", "for", "the", "given", "content" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/code128/encode.go#L159-L184
train
boombuler/barcode
utils/bitlist.go
NewBitList
func NewBitList(capacity int) *BitList { bl := new(BitList) bl.count = capacity x := 0 if capacity%32 != 0 { x = 1 } bl.data = make([]int32, capacity/32+x) return bl }
go
func NewBitList(capacity int) *BitList { bl := new(BitList) bl.count = capacity x := 0 if capacity%32 != 0 { x = 1 } bl.data = make([]int32, capacity/32+x) return bl }
[ "func", "NewBitList", "(", "capacity", "int", ")", "*", "BitList", "{", "bl", ":=", "new", "(", "BitList", ")", "\n", "bl", ".", "count", "=", "capacity", "\n", "x", ":=", "0", "\n", "if", "capacity", "%", "32", "!=", "0", "{", "x", "=", "1", "\n", "}", "\n", "bl", ".", "data", "=", "make", "(", "[", "]", "int32", ",", "capacity", "/", "32", "+", "x", ")", "\n", "return", "bl", "\n", "}" ]
// NewBitList returns a new BitList with the given length // all bits are initialize with false
[ "NewBitList", "returns", "a", "new", "BitList", "with", "the", "given", "length", "all", "bits", "are", "initialize", "with", "false" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L11-L20
train
boombuler/barcode
utils/bitlist.go
AddBit
func (bl *BitList) AddBit(bits ...bool) { for _, bit := range bits { itmIndex := bl.count / 32 for itmIndex >= len(bl.data) { bl.grow() } bl.SetBit(bl.count, bit) bl.count++ } }
go
func (bl *BitList) AddBit(bits ...bool) { for _, bit := range bits { itmIndex := bl.count / 32 for itmIndex >= len(bl.data) { bl.grow() } bl.SetBit(bl.count, bit) bl.count++ } }
[ "func", "(", "bl", "*", "BitList", ")", "AddBit", "(", "bits", "...", "bool", ")", "{", "for", "_", ",", "bit", ":=", "range", "bits", "{", "itmIndex", ":=", "bl", ".", "count", "/", "32", "\n", "for", "itmIndex", ">=", "len", "(", "bl", ".", "data", ")", "{", "bl", ".", "grow", "(", ")", "\n", "}", "\n", "bl", ".", "SetBit", "(", "bl", ".", "count", ",", "bit", ")", "\n", "bl", ".", "count", "++", "\n", "}", "\n", "}" ]
// AddBit appends the given bits to the end of the list
[ "AddBit", "appends", "the", "given", "bits", "to", "the", "end", "of", "the", "list" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L41-L50
train
boombuler/barcode
utils/bitlist.go
SetBit
func (bl *BitList) SetBit(index int, value bool) { itmIndex := index / 32 itmBitShift := 31 - (index % 32) if value { bl.data[itmIndex] = bl.data[itmIndex] | 1<<uint(itmBitShift) } else { bl.data[itmIndex] = bl.data[itmIndex] & ^(1 << uint(itmBitShift)) } }
go
func (bl *BitList) SetBit(index int, value bool) { itmIndex := index / 32 itmBitShift := 31 - (index % 32) if value { bl.data[itmIndex] = bl.data[itmIndex] | 1<<uint(itmBitShift) } else { bl.data[itmIndex] = bl.data[itmIndex] & ^(1 << uint(itmBitShift)) } }
[ "func", "(", "bl", "*", "BitList", ")", "SetBit", "(", "index", "int", ",", "value", "bool", ")", "{", "itmIndex", ":=", "index", "/", "32", "\n", "itmBitShift", ":=", "31", "-", "(", "index", "%", "32", ")", "\n", "if", "value", "{", "bl", ".", "data", "[", "itmIndex", "]", "=", "bl", ".", "data", "[", "itmIndex", "]", "|", "1", "<<", "uint", "(", "itmBitShift", ")", "\n", "}", "else", "{", "bl", ".", "data", "[", "itmIndex", "]", "=", "bl", ".", "data", "[", "itmIndex", "]", "&", "^", "(", "1", "<<", "uint", "(", "itmBitShift", ")", ")", "\n", "}", "\n", "}" ]
// SetBit sets the bit at the given index to the given value
[ "SetBit", "sets", "the", "bit", "at", "the", "given", "index", "to", "the", "given", "value" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L53-L61
train
boombuler/barcode
utils/bitlist.go
GetBit
func (bl *BitList) GetBit(index int) bool { itmIndex := index / 32 itmBitShift := 31 - (index % 32) return ((bl.data[itmIndex] >> uint(itmBitShift)) & 1) == 1 }
go
func (bl *BitList) GetBit(index int) bool { itmIndex := index / 32 itmBitShift := 31 - (index % 32) return ((bl.data[itmIndex] >> uint(itmBitShift)) & 1) == 1 }
[ "func", "(", "bl", "*", "BitList", ")", "GetBit", "(", "index", "int", ")", "bool", "{", "itmIndex", ":=", "index", "/", "32", "\n", "itmBitShift", ":=", "31", "-", "(", "index", "%", "32", ")", "\n", "return", "(", "(", "bl", ".", "data", "[", "itmIndex", "]", ">>", "uint", "(", "itmBitShift", ")", ")", "&", "1", ")", "==", "1", "\n", "}" ]
// GetBit returns the bit at the given index
[ "GetBit", "returns", "the", "bit", "at", "the", "given", "index" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L64-L68
train
boombuler/barcode
utils/bitlist.go
AddByte
func (bl *BitList) AddByte(b byte) { for i := 7; i >= 0; i-- { bl.AddBit(((b >> uint(i)) & 1) == 1) } }
go
func (bl *BitList) AddByte(b byte) { for i := 7; i >= 0; i-- { bl.AddBit(((b >> uint(i)) & 1) == 1) } }
[ "func", "(", "bl", "*", "BitList", ")", "AddByte", "(", "b", "byte", ")", "{", "for", "i", ":=", "7", ";", "i", ">=", "0", ";", "i", "--", "{", "bl", ".", "AddBit", "(", "(", "(", "b", ">>", "uint", "(", "i", ")", ")", "&", "1", ")", "==", "1", ")", "\n", "}", "\n", "}" ]
// AddByte appends all 8 bits of the given byte to the end of the list
[ "AddByte", "appends", "all", "8", "bits", "of", "the", "given", "byte", "to", "the", "end", "of", "the", "list" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L71-L75
train
boombuler/barcode
utils/bitlist.go
IterateBytes
func (bl *BitList) IterateBytes() <-chan byte { res := make(chan byte) go func() { c := bl.count shift := 24 i := 0 for c > 0 { res <- byte((bl.data[i] >> uint(shift)) & 0xFF) shift -= 8 if shift < 0 { shift = 24 i++ } c -= 8 } close(res) }() return res }
go
func (bl *BitList) IterateBytes() <-chan byte { res := make(chan byte) go func() { c := bl.count shift := 24 i := 0 for c > 0 { res <- byte((bl.data[i] >> uint(shift)) & 0xFF) shift -= 8 if shift < 0 { shift = 24 i++ } c -= 8 } close(res) }() return res }
[ "func", "(", "bl", "*", "BitList", ")", "IterateBytes", "(", ")", "<-", "chan", "byte", "{", "res", ":=", "make", "(", "chan", "byte", ")", "\n\n", "go", "func", "(", ")", "{", "c", ":=", "bl", ".", "count", "\n", "shift", ":=", "24", "\n", "i", ":=", "0", "\n", "for", "c", ">", "0", "{", "res", "<-", "byte", "(", "(", "bl", ".", "data", "[", "i", "]", ">>", "uint", "(", "shift", ")", ")", "&", "0xFF", ")", "\n", "shift", "-=", "8", "\n", "if", "shift", "<", "0", "{", "shift", "=", "24", "\n", "i", "++", "\n", "}", "\n", "c", "-=", "8", "\n", "}", "\n", "close", "(", "res", ")", "\n", "}", "(", ")", "\n\n", "return", "res", "\n", "}" ]
// IterateBytes iterates through all bytes contained in the BitList
[ "IterateBytes", "iterates", "through", "all", "bytes", "contained", "in", "the", "BitList" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/utils/bitlist.go#L99-L119
train
boombuler/barcode
qr/encoder.go
Encode
func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) { bits, vi, err := mode.getEncoder()(content, level) if err != nil { return nil, err } blocks := splitToBlocks(bits.IterateBytes(), vi) data := blocks.interleave(vi) result := render(data, vi) result.content = content return result, nil }
go
func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) { bits, vi, err := mode.getEncoder()(content, level) if err != nil { return nil, err } blocks := splitToBlocks(bits.IterateBytes(), vi) data := blocks.interleave(vi) result := render(data, vi) result.content = content return result, nil }
[ "func", "Encode", "(", "content", "string", ",", "level", "ErrorCorrectionLevel", ",", "mode", "Encoding", ")", "(", "barcode", ".", "Barcode", ",", "error", ")", "{", "bits", ",", "vi", ",", "err", ":=", "mode", ".", "getEncoder", "(", ")", "(", "content", ",", "level", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "blocks", ":=", "splitToBlocks", "(", "bits", ".", "IterateBytes", "(", ")", ",", "vi", ")", "\n", "data", ":=", "blocks", ".", "interleave", "(", "vi", ")", "\n", "result", ":=", "render", "(", "data", ",", "vi", ")", "\n", "result", ".", "content", "=", "content", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Encode returns a QR barcode with the given content, error correction level and uses the given encoding
[ "Encode", "returns", "a", "QR", "barcode", "with", "the", "given", "content", "error", "correction", "level", "and", "uses", "the", "given", "encoding" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/qr/encoder.go#L58-L69
train
boombuler/barcode
code93/encoder.go
Encode
func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.Barcode, error) { if fullASCIIMode { var err error content, err = prepare(content) if err != nil { return nil, err } } else if strings.ContainsRune(content, '*') { return nil, errors.New("invalid data! content may not contain '*'") } data := content + string(getChecksum(content, 20)) data += string(getChecksum(data, 15)) data = "*" + data + "*" result := new(utils.BitList) for _, r := range data { info, ok := encodeTable[r] if !ok { return nil, errors.New("invalid data!") } result.AddBits(info.data, 9) } result.AddBit(true) return utils.New1DCode(barcode.TypeCode93, content, result), nil }
go
func Encode(content string, includeChecksum bool, fullASCIIMode bool) (barcode.Barcode, error) { if fullASCIIMode { var err error content, err = prepare(content) if err != nil { return nil, err } } else if strings.ContainsRune(content, '*') { return nil, errors.New("invalid data! content may not contain '*'") } data := content + string(getChecksum(content, 20)) data += string(getChecksum(data, 15)) data = "*" + data + "*" result := new(utils.BitList) for _, r := range data { info, ok := encodeTable[r] if !ok { return nil, errors.New("invalid data!") } result.AddBits(info.data, 9) } result.AddBit(true) return utils.New1DCode(barcode.TypeCode93, content, result), nil }
[ "func", "Encode", "(", "content", "string", ",", "includeChecksum", "bool", ",", "fullASCIIMode", "bool", ")", "(", "barcode", ".", "Barcode", ",", "error", ")", "{", "if", "fullASCIIMode", "{", "var", "err", "error", "\n", "content", ",", "err", "=", "prepare", "(", "content", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "if", "strings", ".", "ContainsRune", "(", "content", ",", "'*'", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "data", ":=", "content", "+", "string", "(", "getChecksum", "(", "content", ",", "20", ")", ")", "\n", "data", "+=", "string", "(", "getChecksum", "(", "data", ",", "15", ")", ")", "\n\n", "data", "=", "\"", "\"", "+", "data", "+", "\"", "\"", "\n", "result", ":=", "new", "(", "utils", ".", "BitList", ")", "\n\n", "for", "_", ",", "r", ":=", "range", "data", "{", "info", ",", "ok", ":=", "encodeTable", "[", "r", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "result", ".", "AddBits", "(", "info", ".", "data", ",", "9", ")", "\n", "}", "\n", "result", ".", "AddBit", "(", "true", ")", "\n\n", "return", "utils", ".", "New1DCode", "(", "barcode", ".", "TypeCode93", ",", "content", ",", "result", ")", ",", "nil", "\n", "}" ]
// Encode returns a code93 barcode for the given content // if includeChecksum is set to true, two checksum characters are calculated and added to the content
[ "Encode", "returns", "a", "code93", "barcode", "for", "the", "given", "content", "if", "includeChecksum", "is", "set", "to", "true", "two", "checksum", "characters", "are", "calculated", "and", "added", "to", "the", "content" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/code93/encoder.go#L79-L106
train
boombuler/barcode
aztec/highlevel.go
updateStateForChar
func updateStateForChar(s *state, data []byte, index int) stateSlice { var result stateSlice = nil ch := data[index] charInCurrentTable := charMap[s.mode][ch] > 0 var stateNoBinary *state = nil for mode := mode_upper; mode <= mode_punct; mode++ { charInMode := charMap[mode][ch] if charInMode > 0 { if stateNoBinary == nil { // Only create stateNoBinary the first time it's required. stateNoBinary = s.endBinaryShift(index) } // Try generating the character by latching to its mode if !charInCurrentTable || mode == s.mode || mode == mode_digit { // If the character is in the current table, we don't want to latch to // any other mode except possibly digit (which uses only 4 bits). Any // other latch would be equally successful *after* this character, and // so wouldn't save any bits. res := stateNoBinary.latchAndAppend(mode, charInMode) result = append(result, res) } // Try generating the character by switching to its mode. if _, ok := shiftTable[s.mode][mode]; !charInCurrentTable && ok { // It never makes sense to temporarily shift to another mode if the // character exists in the current mode. That can never save bits. res := stateNoBinary.shiftAndAppend(mode, charInMode) result = append(result, res) } } } if s.bShiftByteCount > 0 || charMap[s.mode][ch] == 0 { // It's never worthwhile to go into binary shift mode if you're not already // in binary shift mode, and the character exists in your current mode. // That can never save bits over just outputting the char in the current mode. res := s.addBinaryShiftChar(index) result = append(result, res) } return result }
go
func updateStateForChar(s *state, data []byte, index int) stateSlice { var result stateSlice = nil ch := data[index] charInCurrentTable := charMap[s.mode][ch] > 0 var stateNoBinary *state = nil for mode := mode_upper; mode <= mode_punct; mode++ { charInMode := charMap[mode][ch] if charInMode > 0 { if stateNoBinary == nil { // Only create stateNoBinary the first time it's required. stateNoBinary = s.endBinaryShift(index) } // Try generating the character by latching to its mode if !charInCurrentTable || mode == s.mode || mode == mode_digit { // If the character is in the current table, we don't want to latch to // any other mode except possibly digit (which uses only 4 bits). Any // other latch would be equally successful *after* this character, and // so wouldn't save any bits. res := stateNoBinary.latchAndAppend(mode, charInMode) result = append(result, res) } // Try generating the character by switching to its mode. if _, ok := shiftTable[s.mode][mode]; !charInCurrentTable && ok { // It never makes sense to temporarily shift to another mode if the // character exists in the current mode. That can never save bits. res := stateNoBinary.shiftAndAppend(mode, charInMode) result = append(result, res) } } } if s.bShiftByteCount > 0 || charMap[s.mode][ch] == 0 { // It's never worthwhile to go into binary shift mode if you're not already // in binary shift mode, and the character exists in your current mode. // That can never save bits over just outputting the char in the current mode. res := s.addBinaryShiftChar(index) result = append(result, res) } return result }
[ "func", "updateStateForChar", "(", "s", "*", "state", ",", "data", "[", "]", "byte", ",", "index", "int", ")", "stateSlice", "{", "var", "result", "stateSlice", "=", "nil", "\n", "ch", ":=", "data", "[", "index", "]", "\n", "charInCurrentTable", ":=", "charMap", "[", "s", ".", "mode", "]", "[", "ch", "]", ">", "0", "\n\n", "var", "stateNoBinary", "*", "state", "=", "nil", "\n", "for", "mode", ":=", "mode_upper", ";", "mode", "<=", "mode_punct", ";", "mode", "++", "{", "charInMode", ":=", "charMap", "[", "mode", "]", "[", "ch", "]", "\n", "if", "charInMode", ">", "0", "{", "if", "stateNoBinary", "==", "nil", "{", "// Only create stateNoBinary the first time it's required.", "stateNoBinary", "=", "s", ".", "endBinaryShift", "(", "index", ")", "\n", "}", "\n", "// Try generating the character by latching to its mode", "if", "!", "charInCurrentTable", "||", "mode", "==", "s", ".", "mode", "||", "mode", "==", "mode_digit", "{", "// If the character is in the current table, we don't want to latch to", "// any other mode except possibly digit (which uses only 4 bits). Any", "// other latch would be equally successful *after* this character, and", "// so wouldn't save any bits.", "res", ":=", "stateNoBinary", ".", "latchAndAppend", "(", "mode", ",", "charInMode", ")", "\n", "result", "=", "append", "(", "result", ",", "res", ")", "\n", "}", "\n", "// Try generating the character by switching to its mode.", "if", "_", ",", "ok", ":=", "shiftTable", "[", "s", ".", "mode", "]", "[", "mode", "]", ";", "!", "charInCurrentTable", "&&", "ok", "{", "// It never makes sense to temporarily shift to another mode if the", "// character exists in the current mode. That can never save bits.", "res", ":=", "stateNoBinary", ".", "shiftAndAppend", "(", "mode", ",", "charInMode", ")", "\n", "result", "=", "append", "(", "result", ",", "res", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "s", ".", "bShiftByteCount", ">", "0", "||", "charMap", "[", "s", ".", "mode", "]", "[", "ch", "]", "==", "0", "{", "// It's never worthwhile to go into binary shift mode if you're not already", "// in binary shift mode, and the character exists in your current mode.", "// That can never save bits over just outputting the char in the current mode.", "res", ":=", "s", ".", "addBinaryShiftChar", "(", "index", ")", "\n", "result", "=", "append", "(", "result", ",", "res", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Return a set of states that represent the possible ways of updating this // state for the next character. The resulting set of states are added to // the "result" list.
[ "Return", "a", "set", "of", "states", "that", "represent", "the", "possible", "ways", "of", "updating", "this", "state", "for", "the", "next", "character", ".", "The", "resulting", "set", "of", "states", "are", "added", "to", "the", "result", "list", "." ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/aztec/highlevel.go#L94-L133
train
boombuler/barcode
ean/encoder.go
Encode
func Encode(code string) (barcode.BarcodeIntCS, error) { var checkSum int if len(code) == 7 || len(code) == 12 { code += string(calcCheckNum(code)) checkSum = utils.RuneToInt(calcCheckNum(code)) } else if len(code) == 8 || len(code) == 13 { check := code[0 : len(code)-1] check += string(calcCheckNum(check)) if check != code { return nil, errors.New("checksum missmatch") } checkSum = utils.RuneToInt(rune(code[len(code)-1])) } if len(code) == 8 { result := encodeEAN8(code) if result != nil { return utils.New1DCodeIntCheckSum(barcode.TypeEAN8, code, result, checkSum), nil } } else if len(code) == 13 { result := encodeEAN13(code) if result != nil { return utils.New1DCodeIntCheckSum(barcode.TypeEAN13, code, result, checkSum), nil } } return nil, errors.New("invalid ean code data") }
go
func Encode(code string) (barcode.BarcodeIntCS, error) { var checkSum int if len(code) == 7 || len(code) == 12 { code += string(calcCheckNum(code)) checkSum = utils.RuneToInt(calcCheckNum(code)) } else if len(code) == 8 || len(code) == 13 { check := code[0 : len(code)-1] check += string(calcCheckNum(check)) if check != code { return nil, errors.New("checksum missmatch") } checkSum = utils.RuneToInt(rune(code[len(code)-1])) } if len(code) == 8 { result := encodeEAN8(code) if result != nil { return utils.New1DCodeIntCheckSum(barcode.TypeEAN8, code, result, checkSum), nil } } else if len(code) == 13 { result := encodeEAN13(code) if result != nil { return utils.New1DCodeIntCheckSum(barcode.TypeEAN13, code, result, checkSum), nil } } return nil, errors.New("invalid ean code data") }
[ "func", "Encode", "(", "code", "string", ")", "(", "barcode", ".", "BarcodeIntCS", ",", "error", ")", "{", "var", "checkSum", "int", "\n", "if", "len", "(", "code", ")", "==", "7", "||", "len", "(", "code", ")", "==", "12", "{", "code", "+=", "string", "(", "calcCheckNum", "(", "code", ")", ")", "\n", "checkSum", "=", "utils", ".", "RuneToInt", "(", "calcCheckNum", "(", "code", ")", ")", "\n", "}", "else", "if", "len", "(", "code", ")", "==", "8", "||", "len", "(", "code", ")", "==", "13", "{", "check", ":=", "code", "[", "0", ":", "len", "(", "code", ")", "-", "1", "]", "\n", "check", "+=", "string", "(", "calcCheckNum", "(", "check", ")", ")", "\n", "if", "check", "!=", "code", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "checkSum", "=", "utils", ".", "RuneToInt", "(", "rune", "(", "code", "[", "len", "(", "code", ")", "-", "1", "]", ")", ")", "\n", "}", "\n\n", "if", "len", "(", "code", ")", "==", "8", "{", "result", ":=", "encodeEAN8", "(", "code", ")", "\n", "if", "result", "!=", "nil", "{", "return", "utils", ".", "New1DCodeIntCheckSum", "(", "barcode", ".", "TypeEAN8", ",", "code", ",", "result", ",", "checkSum", ")", ",", "nil", "\n", "}", "\n", "}", "else", "if", "len", "(", "code", ")", "==", "13", "{", "result", ":=", "encodeEAN13", "(", "code", ")", "\n", "if", "result", "!=", "nil", "{", "return", "utils", ".", "New1DCodeIntCheckSum", "(", "barcode", ".", "TypeEAN13", ",", "code", ",", "result", ",", "checkSum", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Encode returns a EAN 8 or EAN 13 barcode for the given code
[ "Encode", "returns", "a", "EAN", "8", "or", "EAN", "13", "barcode", "for", "the", "given", "code" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/ean/encoder.go#L161-L187
train
boombuler/barcode
aztec/state.go
shiftAndAppend
func (s *state) shiftAndAppend(mode encodingMode, value int) *state { tokens := s.tokens // Shifts exist only to UPPER and PUNCT, both with tokens size 5. tokens = newSimpleToken(tokens, shiftTable[s.mode][mode], s.mode.BitCount()) tokens = newSimpleToken(tokens, value, 5) return &state{ mode: s.mode, tokens: tokens, bShiftByteCount: 0, bitCount: s.bitCount + int(s.mode.BitCount()) + 5, } }
go
func (s *state) shiftAndAppend(mode encodingMode, value int) *state { tokens := s.tokens // Shifts exist only to UPPER and PUNCT, both with tokens size 5. tokens = newSimpleToken(tokens, shiftTable[s.mode][mode], s.mode.BitCount()) tokens = newSimpleToken(tokens, value, 5) return &state{ mode: s.mode, tokens: tokens, bShiftByteCount: 0, bitCount: s.bitCount + int(s.mode.BitCount()) + 5, } }
[ "func", "(", "s", "*", "state", ")", "shiftAndAppend", "(", "mode", "encodingMode", ",", "value", "int", ")", "*", "state", "{", "tokens", ":=", "s", ".", "tokens", "\n\n", "// Shifts exist only to UPPER and PUNCT, both with tokens size 5.", "tokens", "=", "newSimpleToken", "(", "tokens", ",", "shiftTable", "[", "s", ".", "mode", "]", "[", "mode", "]", ",", "s", ".", "mode", ".", "BitCount", "(", ")", ")", "\n", "tokens", "=", "newSimpleToken", "(", "tokens", ",", "value", ",", "5", ")", "\n\n", "return", "&", "state", "{", "mode", ":", "s", ".", "mode", ",", "tokens", ":", "tokens", ",", "bShiftByteCount", ":", "0", ",", "bitCount", ":", "s", ".", "bitCount", "+", "int", "(", "s", ".", "mode", ".", "BitCount", "(", ")", ")", "+", "5", ",", "}", "\n", "}" ]
// Create a new state representing this state, with a temporary shift // to a different mode to output a single value.
[ "Create", "a", "new", "state", "representing", "this", "state", "with", "a", "temporary", "shift", "to", "a", "different", "mode", "to", "output", "a", "single", "value", "." ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/aztec/state.go#L171-L184
train
boombuler/barcode
aztec/state.go
addBinaryShiftChar
func (s *state) addBinaryShiftChar(index int) *state { tokens := s.tokens mode := s.mode bitCnt := s.bitCount if s.mode == mode_punct || s.mode == mode_digit { latch := latchTable[s.mode][mode_upper] tokens = newSimpleToken(tokens, latch&0xFFFF, byte(latch>>16)) bitCnt += latch >> 16 mode = mode_upper } deltaBitCount := 8 if s.bShiftByteCount == 0 || s.bShiftByteCount == 31 { deltaBitCount = 18 } else if s.bShiftByteCount == 62 { deltaBitCount = 9 } result := &state{ mode: mode, tokens: tokens, bShiftByteCount: s.bShiftByteCount + 1, bitCount: bitCnt + deltaBitCount, } if result.bShiftByteCount == 2047+31 { // The string is as long as it's allowed to be. We should end it. result = result.endBinaryShift(index + 1) } return result }
go
func (s *state) addBinaryShiftChar(index int) *state { tokens := s.tokens mode := s.mode bitCnt := s.bitCount if s.mode == mode_punct || s.mode == mode_digit { latch := latchTable[s.mode][mode_upper] tokens = newSimpleToken(tokens, latch&0xFFFF, byte(latch>>16)) bitCnt += latch >> 16 mode = mode_upper } deltaBitCount := 8 if s.bShiftByteCount == 0 || s.bShiftByteCount == 31 { deltaBitCount = 18 } else if s.bShiftByteCount == 62 { deltaBitCount = 9 } result := &state{ mode: mode, tokens: tokens, bShiftByteCount: s.bShiftByteCount + 1, bitCount: bitCnt + deltaBitCount, } if result.bShiftByteCount == 2047+31 { // The string is as long as it's allowed to be. We should end it. result = result.endBinaryShift(index + 1) } return result }
[ "func", "(", "s", "*", "state", ")", "addBinaryShiftChar", "(", "index", "int", ")", "*", "state", "{", "tokens", ":=", "s", ".", "tokens", "\n", "mode", ":=", "s", ".", "mode", "\n", "bitCnt", ":=", "s", ".", "bitCount", "\n", "if", "s", ".", "mode", "==", "mode_punct", "||", "s", ".", "mode", "==", "mode_digit", "{", "latch", ":=", "latchTable", "[", "s", ".", "mode", "]", "[", "mode_upper", "]", "\n", "tokens", "=", "newSimpleToken", "(", "tokens", ",", "latch", "&", "0xFFFF", ",", "byte", "(", "latch", ">>", "16", ")", ")", "\n", "bitCnt", "+=", "latch", ">>", "16", "\n", "mode", "=", "mode_upper", "\n", "}", "\n", "deltaBitCount", ":=", "8", "\n", "if", "s", ".", "bShiftByteCount", "==", "0", "||", "s", ".", "bShiftByteCount", "==", "31", "{", "deltaBitCount", "=", "18", "\n", "}", "else", "if", "s", ".", "bShiftByteCount", "==", "62", "{", "deltaBitCount", "=", "9", "\n", "}", "\n", "result", ":=", "&", "state", "{", "mode", ":", "mode", ",", "tokens", ":", "tokens", ",", "bShiftByteCount", ":", "s", ".", "bShiftByteCount", "+", "1", ",", "bitCount", ":", "bitCnt", "+", "deltaBitCount", ",", "}", "\n", "if", "result", ".", "bShiftByteCount", "==", "2047", "+", "31", "{", "// The string is as long as it's allowed to be. We should end it.", "result", "=", "result", ".", "endBinaryShift", "(", "index", "+", "1", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// Create a new state representing this state, but an additional character // output in Binary Shift mode.
[ "Create", "a", "new", "state", "representing", "this", "state", "but", "an", "additional", "character", "output", "in", "Binary", "Shift", "mode", "." ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/aztec/state.go#L188-L216
train
boombuler/barcode
aztec/state.go
endBinaryShift
func (s *state) endBinaryShift(index int) *state { if s.bShiftByteCount == 0 { return s } tokens := newShiftToken(s.tokens, index-s.bShiftByteCount, s.bShiftByteCount) return &state{ mode: s.mode, tokens: tokens, bShiftByteCount: 0, bitCount: s.bitCount, } }
go
func (s *state) endBinaryShift(index int) *state { if s.bShiftByteCount == 0 { return s } tokens := newShiftToken(s.tokens, index-s.bShiftByteCount, s.bShiftByteCount) return &state{ mode: s.mode, tokens: tokens, bShiftByteCount: 0, bitCount: s.bitCount, } }
[ "func", "(", "s", "*", "state", ")", "endBinaryShift", "(", "index", "int", ")", "*", "state", "{", "if", "s", ".", "bShiftByteCount", "==", "0", "{", "return", "s", "\n", "}", "\n", "tokens", ":=", "newShiftToken", "(", "s", ".", "tokens", ",", "index", "-", "s", ".", "bShiftByteCount", ",", "s", ".", "bShiftByteCount", ")", "\n", "return", "&", "state", "{", "mode", ":", "s", ".", "mode", ",", "tokens", ":", "tokens", ",", "bShiftByteCount", ":", "0", ",", "bitCount", ":", "s", ".", "bitCount", ",", "}", "\n", "}" ]
// Create the state identical to this one, but we are no longer in // Binary Shift mode.
[ "Create", "the", "state", "identical", "to", "this", "one", "but", "we", "are", "no", "longer", "in", "Binary", "Shift", "mode", "." ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/aztec/state.go#L220-L231
train
boombuler/barcode
datamatrix/encoder.go
Encode
func Encode(content string) (barcode.Barcode, error) { data := encodeText(content) var size *dmCodeSize for _, s := range codeSizes { if s.DataCodewords() >= len(data) { size = s break } } if size == nil { return nil, errors.New("to much data to encode") } data = addPadding(data, size.DataCodewords()) data = ec.calcECC(data, size) code := render(data, size) if code != nil { code.content = content return code, nil } return nil, errors.New("unable to render barcode") }
go
func Encode(content string) (barcode.Barcode, error) { data := encodeText(content) var size *dmCodeSize for _, s := range codeSizes { if s.DataCodewords() >= len(data) { size = s break } } if size == nil { return nil, errors.New("to much data to encode") } data = addPadding(data, size.DataCodewords()) data = ec.calcECC(data, size) code := render(data, size) if code != nil { code.content = content return code, nil } return nil, errors.New("unable to render barcode") }
[ "func", "Encode", "(", "content", "string", ")", "(", "barcode", ".", "Barcode", ",", "error", ")", "{", "data", ":=", "encodeText", "(", "content", ")", "\n\n", "var", "size", "*", "dmCodeSize", "\n", "for", "_", ",", "s", ":=", "range", "codeSizes", "{", "if", "s", ".", "DataCodewords", "(", ")", ">=", "len", "(", "data", ")", "{", "size", "=", "s", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "size", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "data", "=", "addPadding", "(", "data", ",", "size", ".", "DataCodewords", "(", ")", ")", "\n", "data", "=", "ec", ".", "calcECC", "(", "data", ",", "size", ")", "\n", "code", ":=", "render", "(", "data", ",", "size", ")", "\n", "if", "code", "!=", "nil", "{", "code", ".", "content", "=", "content", "\n", "return", "code", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Encode returns a Datamatrix barcode for the given content
[ "Encode", "returns", "a", "Datamatrix", "barcode", "for", "the", "given", "content" ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/datamatrix/encoder.go#L11-L32
train
boombuler/barcode
pdf417/encoder.go
Encode
func Encode(data string, securityLevel byte) (barcode.Barcode, error) { if securityLevel >= 9 { return nil, fmt.Errorf("Invalid security level %d", securityLevel) } sl := securitylevel(securityLevel) dataWords, err := highlevelEncode(data) if err != nil { return nil, err } columns, rows := calcDimensions(len(dataWords), sl.ErrorCorrectionWordCount()) if columns < minCols || columns > maxCols || rows < minRows || rows > maxRows { return nil, fmt.Errorf("Unable to fit data in barcode") } barcode := new(pdfBarcode) barcode.data = data codeWords, err := encodeData(dataWords, columns, sl) if err != nil { return nil, err } grid := [][]int{} for i := 0; i < len(codeWords); i += columns { grid = append(grid, codeWords[i:min(i+columns, len(codeWords))]) } codes := [][]int{} for rowNum, row := range grid { table := rowNum % 3 rowCodes := make([]int, 0, columns+4) rowCodes = append(rowCodes, start_word) rowCodes = append(rowCodes, getCodeword(table, getLeftCodeWord(rowNum, rows, columns, securityLevel))) for _, word := range row { rowCodes = append(rowCodes, getCodeword(table, word)) } rowCodes = append(rowCodes, getCodeword(table, getRightCodeWord(rowNum, rows, columns, securityLevel))) rowCodes = append(rowCodes, stop_word) codes = append(codes, rowCodes) } barcode.code = renderBarcode(codes) barcode.width = (columns+4)*17 + 1 return barcode, nil }
go
func Encode(data string, securityLevel byte) (barcode.Barcode, error) { if securityLevel >= 9 { return nil, fmt.Errorf("Invalid security level %d", securityLevel) } sl := securitylevel(securityLevel) dataWords, err := highlevelEncode(data) if err != nil { return nil, err } columns, rows := calcDimensions(len(dataWords), sl.ErrorCorrectionWordCount()) if columns < minCols || columns > maxCols || rows < minRows || rows > maxRows { return nil, fmt.Errorf("Unable to fit data in barcode") } barcode := new(pdfBarcode) barcode.data = data codeWords, err := encodeData(dataWords, columns, sl) if err != nil { return nil, err } grid := [][]int{} for i := 0; i < len(codeWords); i += columns { grid = append(grid, codeWords[i:min(i+columns, len(codeWords))]) } codes := [][]int{} for rowNum, row := range grid { table := rowNum % 3 rowCodes := make([]int, 0, columns+4) rowCodes = append(rowCodes, start_word) rowCodes = append(rowCodes, getCodeword(table, getLeftCodeWord(rowNum, rows, columns, securityLevel))) for _, word := range row { rowCodes = append(rowCodes, getCodeword(table, word)) } rowCodes = append(rowCodes, getCodeword(table, getRightCodeWord(rowNum, rows, columns, securityLevel))) rowCodes = append(rowCodes, stop_word) codes = append(codes, rowCodes) } barcode.code = renderBarcode(codes) barcode.width = (columns+4)*17 + 1 return barcode, nil }
[ "func", "Encode", "(", "data", "string", ",", "securityLevel", "byte", ")", "(", "barcode", ".", "Barcode", ",", "error", ")", "{", "if", "securityLevel", ">=", "9", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "securityLevel", ")", "\n", "}", "\n\n", "sl", ":=", "securitylevel", "(", "securityLevel", ")", "\n\n", "dataWords", ",", "err", ":=", "highlevelEncode", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "columns", ",", "rows", ":=", "calcDimensions", "(", "len", "(", "dataWords", ")", ",", "sl", ".", "ErrorCorrectionWordCount", "(", ")", ")", "\n", "if", "columns", "<", "minCols", "||", "columns", ">", "maxCols", "||", "rows", "<", "minRows", "||", "rows", ">", "maxRows", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "barcode", ":=", "new", "(", "pdfBarcode", ")", "\n", "barcode", ".", "data", "=", "data", "\n\n", "codeWords", ",", "err", ":=", "encodeData", "(", "dataWords", ",", "columns", ",", "sl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "grid", ":=", "[", "]", "[", "]", "int", "{", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "codeWords", ")", ";", "i", "+=", "columns", "{", "grid", "=", "append", "(", "grid", ",", "codeWords", "[", "i", ":", "min", "(", "i", "+", "columns", ",", "len", "(", "codeWords", ")", ")", "]", ")", "\n", "}", "\n\n", "codes", ":=", "[", "]", "[", "]", "int", "{", "}", "\n\n", "for", "rowNum", ",", "row", ":=", "range", "grid", "{", "table", ":=", "rowNum", "%", "3", "\n", "rowCodes", ":=", "make", "(", "[", "]", "int", ",", "0", ",", "columns", "+", "4", ")", "\n\n", "rowCodes", "=", "append", "(", "rowCodes", ",", "start_word", ")", "\n", "rowCodes", "=", "append", "(", "rowCodes", ",", "getCodeword", "(", "table", ",", "getLeftCodeWord", "(", "rowNum", ",", "rows", ",", "columns", ",", "securityLevel", ")", ")", ")", "\n\n", "for", "_", ",", "word", ":=", "range", "row", "{", "rowCodes", "=", "append", "(", "rowCodes", ",", "getCodeword", "(", "table", ",", "word", ")", ")", "\n", "}", "\n\n", "rowCodes", "=", "append", "(", "rowCodes", ",", "getCodeword", "(", "table", ",", "getRightCodeWord", "(", "rowNum", ",", "rows", ",", "columns", ",", "securityLevel", ")", ")", ")", "\n", "rowCodes", "=", "append", "(", "rowCodes", ",", "stop_word", ")", "\n\n", "codes", "=", "append", "(", "codes", ",", "rowCodes", ")", "\n", "}", "\n\n", "barcode", ".", "code", "=", "renderBarcode", "(", "codes", ")", "\n", "barcode", ".", "width", "=", "(", "columns", "+", "4", ")", "*", "17", "+", "1", "\n\n", "return", "barcode", ",", "nil", "\n", "}" ]
// Encodes the given data as PDF417 barcode. // securityLevel should be between 0 and 8. The higher the number, the more // additional error-correction codes are added.
[ "Encodes", "the", "given", "data", "as", "PDF417", "barcode", ".", "securityLevel", "should", "be", "between", "0", "and", "8", ".", "The", "higher", "the", "number", "the", "more", "additional", "error", "-", "correction", "codes", "are", "added", "." ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/pdf417/encoder.go#L18-L71
train
boombuler/barcode
scaledbarcode.go
Scale
func Scale(bc Barcode, width, height int) (Barcode, error) { switch bc.Metadata().Dimensions { case 1: return scale1DCode(bc, width, height) case 2: return scale2DCode(bc, width, height) } return nil, errors.New("unsupported barcode format") }
go
func Scale(bc Barcode, width, height int) (Barcode, error) { switch bc.Metadata().Dimensions { case 1: return scale1DCode(bc, width, height) case 2: return scale2DCode(bc, width, height) } return nil, errors.New("unsupported barcode format") }
[ "func", "Scale", "(", "bc", "Barcode", ",", "width", ",", "height", "int", ")", "(", "Barcode", ",", "error", ")", "{", "switch", "bc", ".", "Metadata", "(", ")", ".", "Dimensions", "{", "case", "1", ":", "return", "scale1DCode", "(", "bc", ",", "width", ",", "height", ")", "\n", "case", "2", ":", "return", "scale2DCode", "(", "bc", ",", "width", ",", "height", ")", "\n", "}", "\n\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Scale returns a resized barcode with the given width and height.
[ "Scale", "returns", "a", "resized", "barcode", "with", "the", "given", "width", "and", "height", "." ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/scaledbarcode.go#L51-L60
train
boombuler/barcode
twooffive/encoder.go
AddCheckSum
func AddCheckSum(content string) (string, error) { if content == "" { return "", errors.New("content is empty") } even := len(content)%2 == 1 sum := 0 for _, r := range content { if _, ok := encodingTable[r]; ok { value := utils.RuneToInt(r) if even { sum += value * 3 } else { sum += value } even = !even } else { return "", fmt.Errorf("can not encode \"%s\"", content) } } return content + string(utils.IntToRune(sum%10)), nil }
go
func AddCheckSum(content string) (string, error) { if content == "" { return "", errors.New("content is empty") } even := len(content)%2 == 1 sum := 0 for _, r := range content { if _, ok := encodingTable[r]; ok { value := utils.RuneToInt(r) if even { sum += value * 3 } else { sum += value } even = !even } else { return "", fmt.Errorf("can not encode \"%s\"", content) } } return content + string(utils.IntToRune(sum%10)), nil }
[ "func", "AddCheckSum", "(", "content", "string", ")", "(", "string", ",", "error", ")", "{", "if", "content", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "even", ":=", "len", "(", "content", ")", "%", "2", "==", "1", "\n", "sum", ":=", "0", "\n", "for", "_", ",", "r", ":=", "range", "content", "{", "if", "_", ",", "ok", ":=", "encodingTable", "[", "r", "]", ";", "ok", "{", "value", ":=", "utils", ".", "RuneToInt", "(", "r", ")", "\n", "if", "even", "{", "sum", "+=", "value", "*", "3", "\n", "}", "else", "{", "sum", "+=", "value", "\n", "}", "\n", "even", "=", "!", "even", "\n", "}", "else", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "content", ")", "\n", "}", "\n", "}", "\n\n", "return", "content", "+", "string", "(", "utils", ".", "IntToRune", "(", "sum", "%", "10", ")", ")", ",", "nil", "\n", "}" ]
// AddCheckSum calculates the correct check-digit and appends it to the given content.
[ "AddCheckSum", "calculates", "the", "correct", "check", "-", "digit", "and", "appends", "it", "to", "the", "given", "content", "." ]
6c824513baccd76c674ce72112c29ef550187b08
https://github.com/boombuler/barcode/blob/6c824513baccd76c674ce72112c29ef550187b08/twooffive/encoder.go#L57-L79
train
thoas/go-funk
zip.go
Zip
func Zip(slice1 interface{}, slice2 interface{}) []Tuple { inValue1 := reflect.ValueOf(slice1) inValue2 := reflect.ValueOf(slice2) kind1 := inValue1.Type().Kind() kind2 := inValue2.Type().Kind() result := []Tuple{} for _, kind := range []reflect.Kind{kind1, kind2} { if kind != reflect.Slice && kind != reflect.Array { return result } } var minLength int length1 := inValue1.Len() length2 := inValue2.Len() if length1 <= length2 { minLength = length1 } else { minLength = length2 } for i := 0; i < minLength; i++ { newTuple := Tuple{ Element1: inValue1.Index(i).Interface(), Element2: inValue2.Index(i).Interface(), } result = append(result, newTuple) } return result }
go
func Zip(slice1 interface{}, slice2 interface{}) []Tuple { inValue1 := reflect.ValueOf(slice1) inValue2 := reflect.ValueOf(slice2) kind1 := inValue1.Type().Kind() kind2 := inValue2.Type().Kind() result := []Tuple{} for _, kind := range []reflect.Kind{kind1, kind2} { if kind != reflect.Slice && kind != reflect.Array { return result } } var minLength int length1 := inValue1.Len() length2 := inValue2.Len() if length1 <= length2 { minLength = length1 } else { minLength = length2 } for i := 0; i < minLength; i++ { newTuple := Tuple{ Element1: inValue1.Index(i).Interface(), Element2: inValue2.Index(i).Interface(), } result = append(result, newTuple) } return result }
[ "func", "Zip", "(", "slice1", "interface", "{", "}", ",", "slice2", "interface", "{", "}", ")", "[", "]", "Tuple", "{", "inValue1", ":=", "reflect", ".", "ValueOf", "(", "slice1", ")", "\n", "inValue2", ":=", "reflect", ".", "ValueOf", "(", "slice2", ")", "\n", "kind1", ":=", "inValue1", ".", "Type", "(", ")", ".", "Kind", "(", ")", "\n", "kind2", ":=", "inValue2", ".", "Type", "(", ")", ".", "Kind", "(", ")", "\n\n", "result", ":=", "[", "]", "Tuple", "{", "}", "\n", "for", "_", ",", "kind", ":=", "range", "[", "]", "reflect", ".", "Kind", "{", "kind1", ",", "kind2", "}", "{", "if", "kind", "!=", "reflect", ".", "Slice", "&&", "kind", "!=", "reflect", ".", "Array", "{", "return", "result", "\n", "}", "\n", "}", "\n\n", "var", "minLength", "int", "\n", "length1", ":=", "inValue1", ".", "Len", "(", ")", "\n", "length2", ":=", "inValue2", ".", "Len", "(", ")", "\n", "if", "length1", "<=", "length2", "{", "minLength", "=", "length1", "\n", "}", "else", "{", "minLength", "=", "length2", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "minLength", ";", "i", "++", "{", "newTuple", ":=", "Tuple", "{", "Element1", ":", "inValue1", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", ",", "Element2", ":", "inValue2", ".", "Index", "(", "i", ")", ".", "Interface", "(", ")", ",", "}", "\n", "result", "=", "append", "(", "result", ",", "newTuple", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Zip returns a list of tuples, where the i-th tuple contains the i-th element // from each of the input iterables. The returned list is truncated in length // to the length of the shortest input iterable.
[ "Zip", "returns", "a", "list", "of", "tuples", "where", "the", "i", "-", "th", "tuple", "contains", "the", "i", "-", "th", "element", "from", "each", "of", "the", "input", "iterables", ".", "The", "returned", "list", "is", "truncated", "in", "length", "to", "the", "length", "of", "the", "shortest", "input", "iterable", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/zip.go#L16-L46
train
thoas/go-funk
typesafe.go
FindFloat64
func FindFloat64(s []float64, cb func(s float64) bool) (float64, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0.0, false }
go
func FindFloat64(s []float64, cb func(s float64) bool) (float64, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0.0, false }
[ "func", "FindFloat64", "(", "s", "[", "]", "float64", ",", "cb", "func", "(", "s", "float64", ")", "bool", ")", "(", "float64", ",", "bool", ")", "{", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "return", "i", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "0.0", ",", "false", "\n", "}" ]
// FindFloat64 iterates over a collection of float64, returning an array of // all float64 elements predicate returns truthy for.
[ "FindFloat64", "iterates", "over", "a", "collection", "of", "float64", "returning", "an", "array", "of", "all", "float64", "elements", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L39-L49
train
thoas/go-funk
typesafe.go
FindFloat32
func FindFloat32(s []float32, cb func(s float32) bool) (float32, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0.0, false }
go
func FindFloat32(s []float32, cb func(s float32) bool) (float32, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0.0, false }
[ "func", "FindFloat32", "(", "s", "[", "]", "float32", ",", "cb", "func", "(", "s", "float32", ")", "bool", ")", "(", "float32", ",", "bool", ")", "{", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "return", "i", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "0.0", ",", "false", "\n", "}" ]
// FindFloat32 iterates over a collection of float32, returning the first // float32 element predicate returns truthy for.
[ "FindFloat32", "iterates", "over", "a", "collection", "of", "float32", "returning", "the", "first", "float32", "element", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L53-L63
train
thoas/go-funk
typesafe.go
FindInt
func FindInt(s []int, cb func(s int) bool) (int, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0, false }
go
func FindInt(s []int, cb func(s int) bool) (int, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0, false }
[ "func", "FindInt", "(", "s", "[", "]", "int", ",", "cb", "func", "(", "s", "int", ")", "bool", ")", "(", "int", ",", "bool", ")", "{", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "return", "i", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "0", ",", "false", "\n", "}" ]
// FindInt iterates over a collection of int, returning the first // int element predicate returns truthy for.
[ "FindInt", "iterates", "over", "a", "collection", "of", "int", "returning", "the", "first", "int", "element", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L67-L77
train
thoas/go-funk
typesafe.go
FindInt32
func FindInt32(s []int32, cb func(s int32) bool) (int32, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0, false }
go
func FindInt32(s []int32, cb func(s int32) bool) (int32, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0, false }
[ "func", "FindInt32", "(", "s", "[", "]", "int32", ",", "cb", "func", "(", "s", "int32", ")", "bool", ")", "(", "int32", ",", "bool", ")", "{", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "return", "i", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "0", ",", "false", "\n", "}" ]
// FindInt32 iterates over a collection of int32, returning the first // int32 element predicate returns truthy for.
[ "FindInt32", "iterates", "over", "a", "collection", "of", "int32", "returning", "the", "first", "int32", "element", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L81-L91
train
thoas/go-funk
typesafe.go
FindInt64
func FindInt64(s []int64, cb func(s int64) bool) (int64, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0, false }
go
func FindInt64(s []int64, cb func(s int64) bool) (int64, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return 0, false }
[ "func", "FindInt64", "(", "s", "[", "]", "int64", ",", "cb", "func", "(", "s", "int64", ")", "bool", ")", "(", "int64", ",", "bool", ")", "{", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "return", "i", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "0", ",", "false", "\n", "}" ]
// FindInt64 iterates over a collection of int64, returning the first // int64 element predicate returns truthy for.
[ "FindInt64", "iterates", "over", "a", "collection", "of", "int64", "returning", "the", "first", "int64", "element", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L95-L105
train
thoas/go-funk
typesafe.go
FindString
func FindString(s []string, cb func(s string) bool) (string, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return "", false }
go
func FindString(s []string, cb func(s string) bool) (string, bool) { for _, i := range s { result := cb(i) if result { return i, true } } return "", false }
[ "func", "FindString", "(", "s", "[", "]", "string", ",", "cb", "func", "(", "s", "string", ")", "bool", ")", "(", "string", ",", "bool", ")", "{", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "return", "i", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "false", "\n", "}" ]
// FindString iterates over a collection of string, returning the first // string element predicate returns truthy for.
[ "FindString", "iterates", "over", "a", "collection", "of", "string", "returning", "the", "first", "string", "element", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L109-L119
train
thoas/go-funk
typesafe.go
FilterFloat64
func FilterFloat64(s []float64, cb func(s float64) bool) []float64 { results := []float64{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
go
func FilterFloat64(s []float64, cb func(s float64) bool) []float64 { results := []float64{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
[ "func", "FilterFloat64", "(", "s", "[", "]", "float64", ",", "cb", "func", "(", "s", "float64", ")", "bool", ")", "[", "]", "float64", "{", "results", ":=", "[", "]", "float64", "{", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "results", "=", "append", "(", "results", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// FilterFloat64 iterates over a collection of float64, returning an array of // all float64 elements predicate returns truthy for.
[ "FilterFloat64", "iterates", "over", "a", "collection", "of", "float64", "returning", "an", "array", "of", "all", "float64", "elements", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L123-L135
train
thoas/go-funk
typesafe.go
FilterFloat32
func FilterFloat32(s []float32, cb func(s float32) bool) []float32 { results := []float32{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
go
func FilterFloat32(s []float32, cb func(s float32) bool) []float32 { results := []float32{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
[ "func", "FilterFloat32", "(", "s", "[", "]", "float32", ",", "cb", "func", "(", "s", "float32", ")", "bool", ")", "[", "]", "float32", "{", "results", ":=", "[", "]", "float32", "{", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "results", "=", "append", "(", "results", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// FilterFloat32 iterates over a collection of float32, returning an array of // all float32 elements predicate returns truthy for.
[ "FilterFloat32", "iterates", "over", "a", "collection", "of", "float32", "returning", "an", "array", "of", "all", "float32", "elements", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L139-L151
train
thoas/go-funk
typesafe.go
FilterInt
func FilterInt(s []int, cb func(s int) bool) []int { results := []int{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
go
func FilterInt(s []int, cb func(s int) bool) []int { results := []int{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
[ "func", "FilterInt", "(", "s", "[", "]", "int", ",", "cb", "func", "(", "s", "int", ")", "bool", ")", "[", "]", "int", "{", "results", ":=", "[", "]", "int", "{", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "results", "=", "append", "(", "results", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// FilterInt iterates over a collection of int, returning an array of // all int elements predicate returns truthy for.
[ "FilterInt", "iterates", "over", "a", "collection", "of", "int", "returning", "an", "array", "of", "all", "int", "elements", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L155-L167
train
thoas/go-funk
typesafe.go
FilterInt32
func FilterInt32(s []int32, cb func(s int32) bool) []int32 { results := []int32{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
go
func FilterInt32(s []int32, cb func(s int32) bool) []int32 { results := []int32{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
[ "func", "FilterInt32", "(", "s", "[", "]", "int32", ",", "cb", "func", "(", "s", "int32", ")", "bool", ")", "[", "]", "int32", "{", "results", ":=", "[", "]", "int32", "{", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "results", "=", "append", "(", "results", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// FilterInt32 iterates over a collection of int32, returning an array of // all int32 elements predicate returns truthy for.
[ "FilterInt32", "iterates", "over", "a", "collection", "of", "int32", "returning", "an", "array", "of", "all", "int32", "elements", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L171-L183
train
thoas/go-funk
typesafe.go
FilterInt64
func FilterInt64(s []int64, cb func(s int64) bool) []int64 { results := []int64{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
go
func FilterInt64(s []int64, cb func(s int64) bool) []int64 { results := []int64{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
[ "func", "FilterInt64", "(", "s", "[", "]", "int64", ",", "cb", "func", "(", "s", "int64", ")", "bool", ")", "[", "]", "int64", "{", "results", ":=", "[", "]", "int64", "{", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "results", "=", "append", "(", "results", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// FilterInt64 iterates over a collection of int64, returning an array of // all int64 elements predicate returns truthy for.
[ "FilterInt64", "iterates", "over", "a", "collection", "of", "int64", "returning", "an", "array", "of", "all", "int64", "elements", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L187-L199
train
thoas/go-funk
typesafe.go
FilterString
func FilterString(s []string, cb func(s string) bool) []string { results := []string{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
go
func FilterString(s []string, cb func(s string) bool) []string { results := []string{} for _, i := range s { result := cb(i) if result { results = append(results, i) } } return results }
[ "func", "FilterString", "(", "s", "[", "]", "string", ",", "cb", "func", "(", "s", "string", ")", "bool", ")", "[", "]", "string", "{", "results", ":=", "[", "]", "string", "{", "}", "\n\n", "for", "_", ",", "i", ":=", "range", "s", "{", "result", ":=", "cb", "(", "i", ")", "\n\n", "if", "result", "{", "results", "=", "append", "(", "results", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// FilterString iterates over a collection of string, returning an array of // all string elements predicate returns truthy for.
[ "FilterString", "iterates", "over", "a", "collection", "of", "string", "returning", "an", "array", "of", "all", "string", "elements", "predicate", "returns", "truthy", "for", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L203-L215
train
thoas/go-funk
typesafe.go
ContainsInt
func ContainsInt(s []int, v int) bool { for _, vv := range s { if vv == v { return true } } return false }
go
func ContainsInt(s []int, v int) bool { for _, vv := range s { if vv == v { return true } } return false }
[ "func", "ContainsInt", "(", "s", "[", "]", "int", ",", "v", "int", ")", "bool", "{", "for", "_", ",", "vv", ":=", "range", "s", "{", "if", "vv", "==", "v", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ContainsInt returns true if an int is present in a iteratee.
[ "ContainsInt", "returns", "true", "if", "an", "int", "is", "present", "in", "a", "iteratee", "." ]
a0a199e85d6d961670e46df4998f8868a3e3309b
https://github.com/thoas/go-funk/blob/a0a199e85d6d961670e46df4998f8868a3e3309b/typesafe.go#L218-L225
train