Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7f4b63212 | ||
|
|
12adf3be32 | ||
|
|
087516a783 | ||
|
|
1b2a2fc7f9 | ||
|
|
3e205dba15 | ||
|
|
ff874575e1 | ||
|
|
1e1516c968 | ||
|
|
aeb6de996c | ||
|
|
82d87111fc | ||
|
|
49953d53ed | ||
|
|
13a4133da5 | ||
|
|
a02ae19de2 | ||
|
|
9617f22fcd | ||
|
|
e156d62e44 | ||
|
|
f4e8352f5a | ||
|
|
deb7f72be2 | ||
|
|
a5a57fa2be | ||
|
|
c3fb1d52f4 | ||
|
|
9820dce775 | ||
|
|
426df2c9ab | ||
|
|
20c7a00af5 | ||
|
|
00d0f1e9d9 | ||
|
|
4cecac4ea4 | ||
|
|
b0e2bde84d | ||
|
|
49851c8795 | ||
|
|
7bdb39c743 | ||
|
|
09495582c4 | ||
|
|
f15be9582a | ||
|
|
c022107515 | ||
|
|
373b593c3e | ||
|
|
ca06c0e09f | ||
|
|
bd1086c244 | ||
|
|
69c8bf7959 | ||
|
|
db6b4f1344 | ||
|
|
05db6e3981 | ||
|
|
2623eeb82e | ||
|
|
cbebadc16a | ||
|
|
614d6d81e5 | ||
|
|
cac451c83e | ||
|
|
54a86c69e1 | ||
|
|
ea8f5c0f33 | ||
|
|
340d576931 | ||
|
|
7db8820042 | ||
|
|
54761b22fd | ||
|
|
253f13640c | ||
|
|
97110c9676 | ||
|
|
9805c4d907 | ||
|
|
56d548ad10 | ||
|
|
c196f6ee08 | ||
|
|
db55841e7d | ||
|
|
fb70ef7b1c | ||
|
|
fa82223c50 | ||
|
|
6f3cd87993 | ||
|
|
3ca7ac613d | ||
|
|
fe5b2f97e3 | ||
|
|
220bf92a3c | ||
|
|
5219fd59e8 | ||
|
|
4832da5cda | ||
|
|
4ef3dcffc4 | ||
|
|
fbe4768658 | ||
|
|
f63de3cc30 | ||
|
|
7c7d9e07a2 | ||
|
|
708f1e17f4 | ||
|
|
8fc48cf24a |
@@ -2,3 +2,5 @@ cover.out
|
||||
mc
|
||||
*~
|
||||
*.test
|
||||
release
|
||||
experimental
|
||||
+2
-2
@@ -13,10 +13,10 @@ env:
|
||||
- ARCH=i686
|
||||
|
||||
go:
|
||||
- 1.5.2
|
||||
- 1.5.3
|
||||
- 1.6
|
||||
|
||||
script:
|
||||
- make
|
||||
- diff -au <(gofmt -d *.go) <(printf "")
|
||||
- diff -au <(gofmt -d pkg) <(printf "")
|
||||
|
||||
|
||||
+5
-5
@@ -7,15 +7,15 @@ This installation guide is based on Ubuntu 14.04+ on x86-64 platform.
|
||||
$ sudo apt-get install git build-essential
|
||||
```
|
||||
|
||||
##### Install Go 1.5+
|
||||
##### Install Go 1.6+
|
||||
|
||||
Download Go 1.5+ from [https://golang.org/dl/](https://golang.org/dl/).
|
||||
Download Go 1.6+ from [https://golang.org/dl/](https://golang.org/dl/).
|
||||
|
||||
```sh
|
||||
$ wget https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz
|
||||
$ wget https://storage.googleapis.com/golang/go1.6.linux-amd64.tar.gz
|
||||
$ mkdir -p ${HOME}/bin/
|
||||
$ mkdir -p ${HOME}/go/
|
||||
$ tar -C ${HOME}/bin/ -xzf go1.5.1.linux-amd64.tar.gz
|
||||
$ tar -C ${HOME}/bin/ -xzf go1.6.linux-amd64.tar.gz
|
||||
```
|
||||
##### Setup GOROOT and GOPATH
|
||||
|
||||
@@ -53,7 +53,7 @@ $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/maste
|
||||
$ brew install git python
|
||||
```
|
||||
|
||||
##### Install Go 1.5+
|
||||
##### Install Go 1.6+
|
||||
|
||||
Install golang binaries using `brew`
|
||||
|
||||
|
||||
+1
-1
@@ -38,4 +38,4 @@ $
|
||||
|
||||
`mc` doesn't follow semantic versioning style, `mc` instead uses the release date and time as the release versions.
|
||||
|
||||
`make release` will install new released binary into your `GOPATH`
|
||||
`make release` will generate new binary into `release` directory.
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
BUILD_LDFLAGS := '$(LDFLAGS)'
|
||||
|
||||
all: install
|
||||
|
||||
checkdeps:
|
||||
checks:
|
||||
@echo "Checking deps:"
|
||||
@(env bash $(PWD)/buildscripts/checkdeps.sh)
|
||||
@(env bash buildscripts/checkdeps.sh)
|
||||
@(env bash buildscripts/checkgopath.sh)
|
||||
|
||||
checkgopath:
|
||||
@echo "Checking if project is at ${GOPATH}"
|
||||
@for mcpath in $(echo ${GOPATH} | sed 's/:/\n/g'); do if [ ! -d ${mcpath}/src/github.com/minio/mc ]; then echo "Project not found in ${mcpath}, please follow instructions provided at https://github.com/minio/minio/blob/master/CONTRIBUTING.md#setup-your-minio-github-repository" && exit 1; fi done
|
||||
@echo "BUILD_LDFLAGS: ${BUILD_LDFLAGS}"
|
||||
|
||||
getdeps: checkdeps checkgopath
|
||||
getdeps: checks
|
||||
@go get github.com/golang/lint/golint && echo "Installed golint:"
|
||||
@go get golang.org/x/tools/cmd/vet && echo "Installed vet:"
|
||||
@go get github.com/fzipp/gocyclo && echo "Installed gocyclo:"
|
||||
@@ -34,17 +29,17 @@ fmt:
|
||||
@GO15VENDOREXPERIMENT=1 gofmt -s -l pkg
|
||||
lint:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 golint .
|
||||
@GO15VENDOREXPERIMENT=1 golint github.com/minio/mc/pkg...
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/golint .
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/golint github.com/minio/mc/pkg...
|
||||
|
||||
cyclo:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 *.go
|
||||
@GO15VENDOREXPERIMENT=1 gocyclo -over 40 pkg
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/gocyclo -over 40 *.go
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/gocyclo -over 40 pkg
|
||||
|
||||
deadcode:
|
||||
@echo "Running $@:"
|
||||
@GO15VENDOREXPERIMENT=1 deadcode
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/deadcode
|
||||
|
||||
build: verifiers
|
||||
@echo "Installing mc:"
|
||||
@@ -55,7 +50,7 @@ test: verifiers
|
||||
@GO15VENDOREXPERIMENT=1 go test $(GOFLAGS) github.com/minio/mc/pkg...
|
||||
|
||||
gomake-all: build
|
||||
@GO15VENDOREXPERIMENT=1 go build --ldflags $(BUILD_LDFLAGS) -o $(GOPATH)/bin/mc
|
||||
@GO15VENDOREXPERIMENT=1 go build --ldflags "$(LDFLAGS)" -o $(GOPATH)/bin/mc
|
||||
@mkdir -p $(HOME)/.mc
|
||||
|
||||
coverage:
|
||||
@@ -63,13 +58,16 @@ coverage:
|
||||
@go tool cover -html=cover.out && echo "Visit your browser"
|
||||
|
||||
pkg-add:
|
||||
@GO15VENDOREXPERIMENT=1 govendor add $(PKG)
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor add $(PKG)
|
||||
|
||||
pkg-update:
|
||||
@GO15VENDOREXPERIMENT=1 govendor update $(PKG)
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor update $(PKG)
|
||||
|
||||
pkg-remove:
|
||||
@GO15VENDOREXPERIMENT=1 govendor remove $(PKG)
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor remove $(PKG)
|
||||
|
||||
pkg-list:
|
||||
@GO15VENDOREXPERIMENT=1 $(GOPATH)/bin/govendor list
|
||||
|
||||
install: gomake-all
|
||||
|
||||
@@ -77,9 +75,14 @@ all-tests: test
|
||||
# TODO disable them for now.
|
||||
#@./tests/test-minio.sh
|
||||
|
||||
release:
|
||||
@./release.sh
|
||||
release: verifiers
|
||||
@MC_RELEASE=RELEASE GO15VENDOREXPERIMENT=1 ./buildscripts/build.sh
|
||||
|
||||
experimental: verifiers
|
||||
@MC_RELEASE=EXPERIMENTAL GO15VENDOREXPERIMENT=1 ./buildscripts/build.sh
|
||||
|
||||
clean:
|
||||
@rm -fv cover.out
|
||||
@rm -fv mc
|
||||
@rm -f cover.out
|
||||
@rm -f mc
|
||||
@find . -name '*.test' | xargs rm -fv
|
||||
@rm -fr release
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Minio Client (mc) [](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, parallel copy. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
|
||||
``mc`` provides minimal tools to work with Amazon S3 compatible cloud storage and filesystems. It has features like resumable uploads/downloads, progress bar, mirroring etc. ``mc`` is written in golang and released under [Apache license v2](./LICENSE).
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -28,21 +28,21 @@
|
||||
|
||||
Download ``mc`` for:
|
||||
|
||||
- ``64-bit Intel`` from https://dl.minio.io/client/mc/release/linux-amd64/mc
|
||||
- ``32-bit Intel`` from https://dl.minio.io/client/mc/release/linux-386/mc
|
||||
- ``32-bit ARM`` from https://dl.minio.io/client/mc/release/linux-arm/mc
|
||||
- ``64-bit Intel`` from https://dl.minio.io/client/mc/release/linux-amd64/mc.tar.gz
|
||||
- ``32-bit Intel`` from https://dl.minio.io/client/mc/release/linux-386/mc.tar.gz
|
||||
- ``32-bit ARM`` from https://dl.minio.io/client/mc/release/linux-arm/mc.tar.gz
|
||||
|
||||
~~~
|
||||
$ chmod +x mc
|
||||
$ tar -xzf mc.tar.gz
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### OS X
|
||||
|
||||
Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc
|
||||
Download ``mc`` from https://dl.minio.io/client/mc/release/darwin-amd64/mc.zip
|
||||
|
||||
~~~
|
||||
$ chmod 755 mc
|
||||
$ unzip mc.zip
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
@@ -50,13 +50,33 @@ $ ./mc --help
|
||||
|
||||
Download ``mc`` for:
|
||||
|
||||
- ``64-bit`` from https://dl.minio.io/client/mc/release/windows-amd64/mc.exe
|
||||
- ``32-bit`` from https://dl.minio.io/client/mc/release/windows-386/mc.exe
|
||||
- ``64-bit`` from https://dl.minio.io/client/mc/release/windows-amd64/mc.zip
|
||||
- ``32-bit`` from https://dl.minio.io/client/mc/release/windows-386/mc.zip
|
||||
|
||||
Extract the downloaded zip file.
|
||||
|
||||
~~~
|
||||
C:\Users\Username\Downloads> mc.exe --help
|
||||
~~~
|
||||
|
||||
#### Solaris/Illumos
|
||||
|
||||
Download ``mc`` from https://dl.minio.io/client/mc/release/solaris-amd64/mc.tar.gz
|
||||
|
||||
~~~
|
||||
$ tar -xzf mc.tar.gz
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### FreeBSD
|
||||
|
||||
Download ``mc`` from https://dl.minio.io/client/mc/release/freebsd-amd64/mc.tar.gz
|
||||
|
||||
~~~
|
||||
$ tar -xzf mc.tar.gz
|
||||
$ ./mc --help
|
||||
~~~
|
||||
|
||||
#### Source
|
||||
<blockquote>
|
||||
NOTE: Source installation is intended for only developers and advanced users. ‘mc update’ continuous delivery mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#mc.
|
||||
|
||||
+47
-71
@@ -18,12 +18,11 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -35,40 +34,38 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
// Set access permissions.
|
||||
// Set public access permissions.
|
||||
var accessCmd = cli.Command{
|
||||
Name: "access",
|
||||
Usage: "Manage bucket access permissions.",
|
||||
Usage: "Set public access permissions.",
|
||||
Action: mainAccess,
|
||||
Flags: append(accessFlags, globalFlags...),
|
||||
CustomHelpTemplate: `Name:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} [FLAGS] set PERMISSION TARGET [TARGET...]
|
||||
mc {{.Name}} [FLAGS] get TARGET [TARGET...]
|
||||
mc {{.Name}} [FLAGS] PERMISSION TARGET
|
||||
mc {{.Name}} [FLAGS] TARGET
|
||||
|
||||
PERMISSION:
|
||||
Allowed permissions are: [private, readonly, public, authorized].
|
||||
Allowed permissions are: [none, readonly, readwrite, writeonly].
|
||||
|
||||
FLAGS:
|
||||
{{range .Flags}}{{.}}
|
||||
{{end}}
|
||||
EXAMPLES:
|
||||
1. Set bucket to "private" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} set private s3/burningman2011
|
||||
1. Set bucket to "readonly" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} readonly s3/burningman2011
|
||||
|
||||
2. Set bucket to "public" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} set public s3/shared
|
||||
2. Set bucket to "readwrite" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} readwrite s3/shared
|
||||
|
||||
3. Set bucket to "authenticated" on Amazon S3 cloud storage to provide read access to IAM Authenticated Users group.
|
||||
$ mc {{.Name}} set authorized s3/shared-authenticated
|
||||
3. Set bucket to "writeonly" on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} writeonly s3/incoming
|
||||
|
||||
4. Get bucket permissions.
|
||||
$ mc {{.Name}} get s3/shared
|
||||
$ mc {{.Name}} s3/shared
|
||||
|
||||
5. Get bucket permissions.
|
||||
$ mc {{.Name}} get gcs/miniocloud
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -107,29 +104,19 @@ func checkAccessSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
if len(ctx.Args()) < 2 {
|
||||
if len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
switch ctx.Args().First() {
|
||||
case "set":
|
||||
if len(ctx.Args().Tail()) < 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
perms := accessPerms(ctx.Args().Tail().Get(0))
|
||||
if len(ctx.Args()) == 2 {
|
||||
perms := accessPerms(ctx.Args().Get(0))
|
||||
if !perms.isValidAccessPERM() {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Unrecognized permission ‘"+perms.String()+"’. Allowed values are [private, public, readonly, authorized].")
|
||||
}
|
||||
for _, arg := range ctx.Args().Tail().Tail() {
|
||||
if strings.TrimSpace(arg) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
case "get":
|
||||
if len(ctx.Args().Tail()) < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
"Unrecognized permission ‘"+string(perms)+"’. Allowed values are [none, readonly, readwrite, writeonly].")
|
||||
}
|
||||
}
|
||||
if len(ctx.Args()) < 1 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "access", 1) // last argument is exit code.
|
||||
}
|
||||
}
|
||||
|
||||
// doSetAccess do set access.
|
||||
@@ -138,8 +125,8 @@ func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error {
|
||||
if err != nil {
|
||||
return err.Trace(targetURL)
|
||||
}
|
||||
if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil {
|
||||
return err.Trace(targetURL, targetPERMS.String())
|
||||
if err = clnt.SetAccess(string(targetPERMS)); err != nil {
|
||||
return err.Trace(targetURL, string(targetPERMS))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -150,11 +137,11 @@ func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) {
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
acl, err := clnt.GetBucketAccess()
|
||||
perm, err := clnt.GetAccess()
|
||||
if err != nil {
|
||||
return "", err.Trace(targetURL)
|
||||
}
|
||||
return aclToPerms(acl), nil
|
||||
return accessPerms(perm), nil
|
||||
}
|
||||
|
||||
func mainAccess(ctx *cli.Context) {
|
||||
@@ -167,39 +154,28 @@ func mainAccess(ctx *cli.Context) {
|
||||
// Additional command speific theme customization.
|
||||
console.SetColor("Access", color.New(color.FgGreen, color.Bold))
|
||||
|
||||
switch ctx.Args().First() {
|
||||
case "set":
|
||||
perms := accessPerms(ctx.Args().Tail().First())
|
||||
URLs := ctx.Args().Tail().Tail()
|
||||
for _, targetURL := range URLs {
|
||||
err := doSetAccess(targetURL, perms)
|
||||
// Upon error, print and continue.
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL, string(perms)),
|
||||
"Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "set",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
case "get":
|
||||
URLs := ctx.Args().Tail()
|
||||
for _, targetURL := range URLs {
|
||||
perms, err := doGetAccess(targetURL)
|
||||
if err != nil {
|
||||
errorIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
|
||||
continue
|
||||
}
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "get",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
perms := accessPerms(ctx.Args().First())
|
||||
if perms.isValidAccessPERM() {
|
||||
targetURL := ctx.Args().Last()
|
||||
err := doSetAccess(targetURL, perms)
|
||||
// Upon error exit.
|
||||
fatalIf(err.Trace(targetURL, string(perms)),
|
||||
"Unable to set access permission ‘"+string(perms)+"’ for ‘"+targetURL+"’.")
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "set",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
} else {
|
||||
targetURL := ctx.Args().First()
|
||||
perms, err := doGetAccess(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to get access permission for ‘"+targetURL+"’.")
|
||||
printMsg(accessMessage{
|
||||
Status: "success",
|
||||
Operation: "get",
|
||||
Bucket: targetURL,
|
||||
Perms: perms,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+8
-67
@@ -18,79 +18,20 @@ package main
|
||||
|
||||
// isValidAccessPERM - is provided access perm string supported.
|
||||
func (b accessPerms) isValidAccessPERM() bool {
|
||||
switch true {
|
||||
case b.isPrivate():
|
||||
fallthrough
|
||||
case b.isReadOnly():
|
||||
fallthrough
|
||||
case b.isPublic():
|
||||
fallthrough
|
||||
case b.isAuthorized():
|
||||
switch b {
|
||||
case accessNone, accessReadOnly, accessReadWrite, accessWriteOnly:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// accessPerms - access level.
|
||||
type accessPerms string
|
||||
|
||||
// different types of Access perm's currently supported by accesss command.
|
||||
// different types of Access perm's currently supported by access command.
|
||||
const (
|
||||
accessPrivate = accessPerms("private")
|
||||
accessReadOnly = accessPerms("readonly")
|
||||
accessPublic = accessPerms("public")
|
||||
accessAuthorized = accessPerms("authorized")
|
||||
accessNone = accessPerms("none")
|
||||
accessReadOnly = accessPerms("readonly")
|
||||
accessReadWrite = accessPerms("readwrite")
|
||||
accessWriteOnly = accessPerms("writeonly")
|
||||
)
|
||||
|
||||
func (b accessPerms) String() string {
|
||||
if !b.isValidAccessPERM() {
|
||||
return string(b)
|
||||
}
|
||||
if b.isReadOnly() {
|
||||
return "public-read"
|
||||
}
|
||||
if b.isPublic() {
|
||||
return "public-read-write"
|
||||
}
|
||||
if b.isAuthorized() {
|
||||
return "authenticated-read"
|
||||
}
|
||||
return "private"
|
||||
}
|
||||
|
||||
// convert acl's to access perms
|
||||
func aclToPerms(acl string) accessPerms {
|
||||
switch acl {
|
||||
case "private":
|
||||
return accessPerms("private")
|
||||
case "public-read":
|
||||
return accessPerms("readonly")
|
||||
case "public-read-write":
|
||||
return accessPerms("public")
|
||||
case "authenticated-read":
|
||||
return accessPerms("authorized")
|
||||
default:
|
||||
return accessPerms(acl)
|
||||
}
|
||||
}
|
||||
|
||||
// isPrivate - is acl Private.
|
||||
func (b accessPerms) isPrivate() bool {
|
||||
return b == accessPrivate
|
||||
}
|
||||
|
||||
// isPublicRead - is acl PublicRead.
|
||||
func (b accessPerms) isReadOnly() bool {
|
||||
return b == accessReadOnly
|
||||
}
|
||||
|
||||
// isPublicReadWrite - is acl PublicReadWrite.
|
||||
func (b accessPerms) isPublic() bool {
|
||||
return b == accessPublic
|
||||
}
|
||||
|
||||
// isAuthorized - is acl AuthorizedRead.
|
||||
func (b accessPerms) isAuthorized() bool {
|
||||
return b == accessAuthorized
|
||||
}
|
||||
|
||||
+5
-3
@@ -14,14 +14,16 @@ environment:
|
||||
# scripts that run after cloning repository
|
||||
install:
|
||||
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
|
||||
- rd C:\Go /s /q
|
||||
- appveyor DownloadFile https://storage.googleapis.com/golang/go1.6.windows-amd64.zip
|
||||
- 7z x go1.6.windows-amd64.zip -oC:\ >nul
|
||||
- go version
|
||||
- go env
|
||||
- go get -u github.com/golang/lint/golint
|
||||
- go get -u golang.org/x/tools/cmd/vet
|
||||
- go get -u github.com/fzipp/gocyclo
|
||||
- go get -u github.com/remyoudompheng/go-misc/deadcode
|
||||
- go get -u github.com/alecthomas/gometalinter
|
||||
- go get -u github.com/client9/misspell
|
||||
- go get -u github.com/client9/misspell/cmd/misspell
|
||||
|
||||
# to run your custom scripts instead of automatic MSBuild
|
||||
build_script:
|
||||
@@ -30,7 +32,7 @@ build_script:
|
||||
- gofmt -s -l pkg
|
||||
- golint .
|
||||
- golint github.com/minio/mc/pkg...
|
||||
- gometalinter --disable-all --linter='misspell:misspell ./*.go:PATH:LINE:COL:MESSAGE' --enable=misspell ./...
|
||||
- misspell .
|
||||
- gocyclo -over 40 pkg
|
||||
- deadcode
|
||||
- go test -race .
|
||||
|
||||
+3
-3
@@ -18,11 +18,11 @@ package main
|
||||
|
||||
var (
|
||||
// mcVersion - version time.RFC3339.
|
||||
mcVersion = "UNOFFICIAL.GOGET"
|
||||
mcVersion = "DEVELOPMENT.GOGET"
|
||||
// mcReleaseTag - release tag in TAG.%Y-%m-%dT%H-%M-%SZ.
|
||||
mcReleaseTag = "UNOFFICIAL.GOGET"
|
||||
mcReleaseTag = "DEVELOPMENT.GOGET"
|
||||
// mcCommitID - latest commit id.
|
||||
mcCommitID = "UNOFFICIAL.GOGET"
|
||||
mcCommitID = "DEVELOPMENT.GOGET"
|
||||
// mcShortCommitID - first 12 characters from mcCommitID.
|
||||
mcShortCommitID = mcCommitID[:12]
|
||||
)
|
||||
|
||||
Executable
+116
@@ -0,0 +1,116 @@
|
||||
#!/bin/bash
|
||||
|
||||
_init() {
|
||||
# Save release LDFLAGS
|
||||
LDFLAGS=$(go run buildscripts/gen-ldflags.go)
|
||||
|
||||
# Extract release tag
|
||||
release_tag=$(echo $LDFLAGS | awk {'print $4'} | cut -f2 -d=)
|
||||
|
||||
# Verify release tag.
|
||||
if [ -z "$release_tag" ]; then
|
||||
echo "Release tag cannot be empty. Please check return value of \`go run buildscripts/gen-ldflags.go\`"
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# Extract release string.
|
||||
release_str=$(echo $MC_RELEASE | tr '[:upper:]' '[:lower:]')
|
||||
|
||||
# Verify release string.
|
||||
if [ -z "$release_str" ]; then
|
||||
echo "Release string cannot be empty. Please set \`MC_RELEASE\` env variable."
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
# List of supported architectures
|
||||
SUPPORTED_OSARCH='linux/386 linux/amd64 linux/arm windows/386 windows/amd64 darwin/amd64 solaris/amd64 freebsd/amd64'
|
||||
|
||||
## System binaries
|
||||
CP=`which cp`
|
||||
SHASUM=`which shasum`
|
||||
GZIP=`which gzip`
|
||||
ZIP=`which zip`
|
||||
SED=`which sed`
|
||||
TAR=`which tar`
|
||||
}
|
||||
|
||||
go_build() {
|
||||
local osarch=$1
|
||||
os=$(echo $osarch | cut -f1 -d'/')
|
||||
arch=$(echo $osarch | cut -f2 -d'/')
|
||||
package=$(go list -f '{{.ImportPath}}')
|
||||
echo -n "-->"
|
||||
printf "%15s:%s\n" "${osarch}" "${package}"
|
||||
|
||||
# Release binary name
|
||||
release_bin="$release_str/$os-$arch/$(basename $package).$release_tag"
|
||||
# Release binary downloadable name
|
||||
release_real_bin="$release_str/$os-$arch/$(basename $package)"
|
||||
# Release shasum name
|
||||
release_shasum="$release_str/$os-$arch/$(basename $package).shasum"
|
||||
# Release zip file.
|
||||
release_real_zip="$(basename $package).zip"
|
||||
release_real_tgz="$(basename $package).tar.gz"
|
||||
|
||||
# Go build to build the binary.
|
||||
GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_bin
|
||||
|
||||
# Create copy
|
||||
if [ $os == "windows" ]; then
|
||||
$CP -p $release_bin ${release_real_bin}.exe
|
||||
else
|
||||
$CP -p $release_bin $release_real_bin
|
||||
fi
|
||||
|
||||
# Calculate shasum
|
||||
shasum_str=$(${SHASUM} ${release_bin})
|
||||
echo ${shasum_str} | $SED "s/$release_str\/$os-$arch\///g" > $release_shasum
|
||||
|
||||
# Create a compressed file.
|
||||
if [ $os == "windows" ]; then
|
||||
cd "$release_str/$os-$arch"
|
||||
$ZIP -r $release_real_zip $(basename $package).exe $(basename $package).shasum
|
||||
cd -
|
||||
elif [ $os == "darwin" ]; then
|
||||
cd "$release_str/$os-$arch"
|
||||
$ZIP -r $release_real_zip $(basename $package) $(basename $package).shasum
|
||||
cd -
|
||||
else
|
||||
cd "$release_str/$os-$arch"
|
||||
$TAR -czf $release_real_tgz $(basename $package) $(basename $package).shasum
|
||||
cd -
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
# Build releases.
|
||||
echo "Executing $release_str builds for OS: ${SUPPORTED_OSARCH}"
|
||||
echo "Choose an OS Arch from the below"
|
||||
for osarch in ${SUPPORTED_OSARCH}; do
|
||||
echo ${osarch}
|
||||
done
|
||||
|
||||
read -p "If you want to build for all, Just press Enter: " chosen_osarch
|
||||
if [ "$chosen_osarch" = "" ]; then
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
go_build ${each_osarch}
|
||||
done
|
||||
else
|
||||
local found=0
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
if [ "$chosen_osarch" = "$each_osarch" ]; then
|
||||
found=1
|
||||
fi
|
||||
done
|
||||
if [ ${found} -eq 1 ]; then
|
||||
go_build ${chosen_osarch}
|
||||
else
|
||||
echo "Unknown architecture \"${chosen_osarch}\""
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
# Run main.
|
||||
_init && main
|
||||
@@ -21,7 +21,7 @@ _init() {
|
||||
|
||||
## Minimum required versions for build dependencies
|
||||
GIT_VERSION="1.0"
|
||||
GO_VERSION="1.5.1"
|
||||
GO_VERSION="1.6"
|
||||
OSX_VERSION="10.8"
|
||||
UNAME=$(uname -sm)
|
||||
|
||||
@@ -136,36 +136,51 @@ check_golang_env() {
|
||||
}
|
||||
|
||||
is_supported_os() {
|
||||
local supported
|
||||
case ${UNAME%% *} in
|
||||
"Linux")
|
||||
os="linux"
|
||||
supported=1
|
||||
;;
|
||||
"Darwin")
|
||||
osx_host_version=$(env sw_vers -productVersion)
|
||||
check_version "${osx_host_version}" "${OSX_VERSION}"
|
||||
[[ $? -ge 2 ]] && die "Minimum OSX version supported is ${OSX_VERSION}"
|
||||
supported=1
|
||||
;;
|
||||
"SunOS")
|
||||
supported=1
|
||||
;;
|
||||
"FreeBSD")
|
||||
supported=1
|
||||
;;
|
||||
"*")
|
||||
echo "Exiting.. unsupported operating system found"
|
||||
exit 1;
|
||||
supported=0
|
||||
;;
|
||||
esac
|
||||
if [ "x$supported" != "x1" ]; then
|
||||
echo "Invalid os: ${UNAME} not supported"
|
||||
exit 1;
|
||||
fi
|
||||
}
|
||||
|
||||
is_supported_arch() {
|
||||
local supported
|
||||
case ${UNAME##* } in
|
||||
"x86_64")
|
||||
"x86_64" | "amd64")
|
||||
supported=1
|
||||
;;
|
||||
"arm"*)
|
||||
supported=1
|
||||
;;
|
||||
"i86pc"*)
|
||||
supported=1
|
||||
;;
|
||||
*)
|
||||
supported=0
|
||||
;;
|
||||
esac
|
||||
if [ $supported -eq 0 ]; then
|
||||
echo "Invalid arch: ${UNAME} not supported, please use x86_64/amd64"
|
||||
if [ "x$supported" != "x1" ]; then
|
||||
echo "Invalid arch: ${UNAME} not supported"
|
||||
exit 1;
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Minio Cloud Storage, (C) 2015, 2016 Minio, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
## use a portable implementation here `realpath` doesn't exist on Darwin/OS X.
|
||||
realpath() {
|
||||
[[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
|
||||
}
|
||||
|
||||
_init() {
|
||||
|
||||
shopt -s extglob
|
||||
|
||||
# Fetch real paths instead of symlinks before comparing them
|
||||
PWD=$(env pwd -P)
|
||||
GOPATH=$(realpath $(go env GOPATH))
|
||||
}
|
||||
|
||||
main() {
|
||||
echo "Checking if project is at ${GOPATH}"
|
||||
for mc in $(echo ${GOPATH} | tr ':' ' '); do
|
||||
if [ ! -d ${mc}/src/github.com/minio/mc ]; then
|
||||
echo "Project not found in ${mc}, please follow instructions provided at https://github.com/minio/mc/blob/master/CONTRIBUTING.md#setup-your-mc-github-repository" \
|
||||
&& exit 1
|
||||
fi
|
||||
if [ "x${mc}/src/github.com/minio/mc" != "x${PWD}" ]; then
|
||||
echo "Build outside of ${mc}, two source checkouts found. Exiting." && exit 1
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
_init && main
|
||||
|
||||
@@ -37,7 +37,7 @@ func genLDFlags(version string) string {
|
||||
|
||||
// genReleaseTag prints release tag to the console for easy git tagging.
|
||||
func releaseTag(version string) string {
|
||||
relPrefix := "UNOFFICIAL"
|
||||
relPrefix := "DEVELOPMENT"
|
||||
if prefix := os.Getenv("MC_RELEASE"); prefix != "" {
|
||||
relPrefix = prefix
|
||||
}
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -14,12 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "fmt"
|
||||
|
||||
/// Collection of standard errors
|
||||
|
||||
@@ -33,15 +30,6 @@ func (e APINotImplemented) Error() string {
|
||||
return "‘" + e.API + "’ feature " + "is not implemented for ‘" + e.APIType + "’."
|
||||
}
|
||||
|
||||
// InvalidRange - invalid range requested
|
||||
type InvalidRange struct {
|
||||
Offset int64
|
||||
}
|
||||
|
||||
func (e InvalidRange) Error() string {
|
||||
return "Invalid range offset: ‘" + strconv.FormatInt(e.Offset, 10) + "’."
|
||||
}
|
||||
|
||||
// GenericBucketError - generic bucket operations error
|
||||
type GenericBucketError struct {
|
||||
Bucket string
|
||||
@@ -61,13 +49,6 @@ func (e BucketExists) Error() string {
|
||||
return "Bucket ‘" + e.Bucket + "’ exists."
|
||||
}
|
||||
|
||||
// InvalidBucketName - bucket name invalid (http://goo.gl/wJlzDz)
|
||||
type InvalidBucketName GenericBucketError
|
||||
|
||||
func (e InvalidBucketName) Error() string {
|
||||
return "Invalid bucketname [‘" + e.Bucket + "’], please read http://goo.gl/wJlzDz."
|
||||
}
|
||||
|
||||
// BucketNameEmpty - bucket name empty (http://goo.gl/wJlzDz)
|
||||
type BucketNameEmpty struct{}
|
||||
|
||||
@@ -75,10 +56,13 @@ func (e BucketNameEmpty) Error() string {
|
||||
return "Bucket name cannot be empty."
|
||||
}
|
||||
|
||||
// GenericObjectError - generic object operations error
|
||||
type GenericObjectError struct {
|
||||
// BucketInvalid - bucket name invalid.
|
||||
type BucketInvalid struct {
|
||||
Bucket string
|
||||
Object string
|
||||
}
|
||||
|
||||
func (e BucketInvalid) Error() string {
|
||||
return "Bucket name " + e.Bucket + " not valid."
|
||||
}
|
||||
|
||||
// ObjectAlreadyExists - typed return for MethodNotAllowed
|
||||
@@ -90,13 +74,6 @@ func (e ObjectAlreadyExists) Error() string {
|
||||
return "Object ‘" + e.Object + "’ already exists."
|
||||
}
|
||||
|
||||
// InvalidObjectName - object requested is invalid
|
||||
type InvalidObjectName GenericObjectError
|
||||
|
||||
func (e InvalidObjectName) Error() string {
|
||||
return "Object ‘" + e.Object + "’ at ‘" + e.Bucket + "’ is invalid."
|
||||
}
|
||||
|
||||
// BucketNameTopLevel - generic error
|
||||
type BucketNameTopLevel struct{}
|
||||
|
||||
@@ -14,44 +14,45 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/hookreader"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/ioutils"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// filesystem client
|
||||
type fsClient struct {
|
||||
PathURL *client.URL
|
||||
PathURL *clientURL
|
||||
}
|
||||
|
||||
const (
|
||||
partSuffix = ".part.mc"
|
||||
partSuffix = ".part.minio"
|
||||
)
|
||||
|
||||
// New - instantiate a new fs client.
|
||||
func New(path string) (client.Client, *probe.Error) {
|
||||
// fsNew - instantiate a new fs
|
||||
func fsNew(path string) (Client, *probe.Error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return nil, probe.NewError(client.EmptyPath{})
|
||||
return nil, probe.NewError(EmptyPath{})
|
||||
}
|
||||
return &fsClient{
|
||||
PathURL: client.NewURL(normalizePath(path)),
|
||||
PathURL: newURL(normalizePath(path)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// URL get url.
|
||||
func (f *fsClient) GetURL() client.URL {
|
||||
func (f *fsClient) GetURL() clientURL {
|
||||
return *f.PathURL
|
||||
}
|
||||
|
||||
@@ -71,7 +72,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
|
||||
if e == nil {
|
||||
// If the destination exists and is not a regular file.
|
||||
if !st.Mode().IsRegular() {
|
||||
return 0, probe.NewError(client.PathIsNotRegular{
|
||||
return 0, probe.NewError(PathIsNotRegular{
|
||||
Path: objectPath,
|
||||
})
|
||||
}
|
||||
@@ -88,7 +89,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
|
||||
objectPartPath := objectPath + partSuffix
|
||||
if objectDir != "" {
|
||||
// Create any missing top level directories.
|
||||
if e := os.MkdirAll(objectDir, 0700); e != nil {
|
||||
if e = os.MkdirAll(objectDir, 0700); e != nil {
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return 0, err.Trace(f.PathURL.Path)
|
||||
}
|
||||
@@ -143,7 +144,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
|
||||
// corruption return here.
|
||||
if readAtSize != writtenSize {
|
||||
// Unexpected write (less data was written than expected).
|
||||
return 0, probe.NewError(client.UnexpectedShortWrite{
|
||||
return 0, probe.NewError(UnexpectedShortWrite{
|
||||
InputSize: readAtSize,
|
||||
WriteSize: writtenSize,
|
||||
})
|
||||
@@ -180,13 +181,13 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
|
||||
// Close the input reader as well, if possible.
|
||||
closer, ok := reader.(io.Closer)
|
||||
if ok {
|
||||
if e := closer.Close(); e != nil {
|
||||
if e = closer.Close(); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Close the file before rename.
|
||||
if e := partFile.Close(); e != nil {
|
||||
if e = partFile.Close(); e != nil {
|
||||
return totalWritten, probe.NewError(e)
|
||||
}
|
||||
|
||||
@@ -194,14 +195,14 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
|
||||
if size > 0 {
|
||||
// Unexpected EOF reached (less data was written than expected).
|
||||
if totalWritten < size {
|
||||
return totalWritten, probe.NewError(client.UnexpectedEOF{
|
||||
return totalWritten, probe.NewError(UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: totalWritten,
|
||||
})
|
||||
}
|
||||
// Unexpected ExcessRead (more data was written than expected).
|
||||
if totalWritten > size {
|
||||
return totalWritten, probe.NewError(client.UnexpectedExcessRead{
|
||||
return totalWritten, probe.NewError(UnexpectedExcessRead{
|
||||
TotalSize: size,
|
||||
TotalWritten: totalWritten,
|
||||
})
|
||||
@@ -217,7 +218,7 @@ func (f *fsClient) Put(reader io.Reader, size int64, contentType string, progres
|
||||
|
||||
// ShareDownload - share download not implemented for filesystem.
|
||||
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(client.APINotImplemented{
|
||||
return "", probe.NewError(APINotImplemented{
|
||||
API: "ShareDownload",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
@@ -225,7 +226,7 @@ func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
|
||||
// ShareUpload - share upload not implemented for filesystem.
|
||||
func (f *fsClient) ShareUpload(startsWith bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
|
||||
return nil, probe.NewError(client.APINotImplemented{
|
||||
return nil, probe.NewError(APINotImplemented{
|
||||
API: "ShareUpload",
|
||||
APIType: "filesystem",
|
||||
})
|
||||
@@ -266,8 +267,8 @@ func (f *fsClient) Remove(incomplete bool) *probe.Error {
|
||||
}
|
||||
|
||||
// List - list files and folders.
|
||||
func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
|
||||
contentCh := make(chan *client.Content)
|
||||
func (f *fsClient) List(recursive, incomplete bool) <-chan *clientContent {
|
||||
contentCh := make(chan *clientContent)
|
||||
switch recursive {
|
||||
case true:
|
||||
go f.listRecursiveInRoutine(contentCh, incomplete)
|
||||
@@ -277,13 +278,50 @@ func (f *fsClient) List(recursive, incomplete bool) <-chan *client.Content {
|
||||
return contentCh
|
||||
}
|
||||
|
||||
// byDirName implements sort.Interface.
|
||||
type byDirName []os.FileInfo
|
||||
|
||||
func (f byDirName) Len() int { return len(f) }
|
||||
func (f byDirName) Less(i, j int) bool {
|
||||
// For directory add an ending separator fortrue lexical
|
||||
// order.
|
||||
if f[i].Mode().IsDir() {
|
||||
return f[i].Name()+string(filepath.Separator) < f[j].Name()
|
||||
}
|
||||
// For directory add an ending separator for true lexical
|
||||
// order.
|
||||
if f[j].Mode().IsDir() {
|
||||
return f[i].Name() < f[j].Name()+string(filepath.Separator)
|
||||
}
|
||||
return f[i].Name() < f[j].Name()
|
||||
}
|
||||
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
|
||||
|
||||
// readDir reads the directory named by dirname and returns
|
||||
// a list of sorted directory entries.
|
||||
func readDir(dirname string) ([]os.FileInfo, error) {
|
||||
f, e := os.Open(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
list, e := f.Readdir(-1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Sort(byDirName(list))
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// listPrefixes - list all files for any given prefix.
|
||||
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content, incomplete bool) {
|
||||
func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *clientContent, incomplete bool) {
|
||||
dirName := filepath.Dir(prefix)
|
||||
files, e := readDir(dirName)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, dirName)
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: err.Trace(dirName),
|
||||
}
|
||||
return
|
||||
@@ -303,7 +341,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
|
||||
newPath := filepath.Join(prefix, fi.Name())
|
||||
lfi, le := f.handleWindowsSymlinks(newPath)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: le.Trace(newPath),
|
||||
}
|
||||
continue
|
||||
@@ -318,19 +356,19 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
|
||||
}
|
||||
}
|
||||
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
Type: lfi.Mode(),
|
||||
Err: probe.NewError(client.PathInsufficientPermission{
|
||||
Err: probe.NewError(PathInsufficientPermission{
|
||||
Path: pathURL.Path,
|
||||
}),
|
||||
}
|
||||
continue
|
||||
} else {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.PathInsufficientPermission{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(PathInsufficientPermission{
|
||||
Path: pathURL.Path,
|
||||
}),
|
||||
}
|
||||
@@ -338,15 +376,15 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
|
||||
}
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.BrokenSymlink{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(BrokenSymlink{
|
||||
Path: pathURL.Path,
|
||||
}),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
continue
|
||||
@@ -362,8 +400,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
|
||||
continue
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: *client.NewURL(file),
|
||||
contentCh <- &clientContent{
|
||||
URL: *newURL(file),
|
||||
Time: st.ModTime(),
|
||||
Size: st.Size(),
|
||||
Type: st.Mode(),
|
||||
@@ -382,8 +420,8 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
|
||||
continue
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: *client.NewURL(file),
|
||||
contentCh <- &clientContent{
|
||||
URL: *newURL(file),
|
||||
Time: fi.ModTime(),
|
||||
Size: fi.Size(),
|
||||
Type: fi.Mode(),
|
||||
@@ -394,7 +432,7 @@ func (f *fsClient) listPrefixes(prefix string, contentCh chan<- *client.Content,
|
||||
return
|
||||
}
|
||||
|
||||
func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bool) {
|
||||
func (f *fsClient) listInRoutine(contentCh chan<- *clientContent, incomplete bool) {
|
||||
// close the channel when the function returns.
|
||||
defer close(contentCh)
|
||||
|
||||
@@ -404,14 +442,14 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
|
||||
|
||||
fst, err := f.fsStat()
|
||||
if err != nil {
|
||||
if _, ok := err.ToGoError().(client.PathNotFound); ok {
|
||||
if _, ok := err.ToGoError().(PathNotFound); ok {
|
||||
// If file does not exist treat it like a prefix and list all prefixes if any.
|
||||
prefix := fpath
|
||||
f.listPrefixes(prefix, contentCh, incomplete)
|
||||
return
|
||||
}
|
||||
// For all other errors we return genuine error back to the caller.
|
||||
contentCh <- &client.Content{Err: err.Trace(fpath)}
|
||||
contentCh <- &clientContent{Err: err.Trace(fpath)}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -427,7 +465,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
|
||||
case true:
|
||||
files, e := readDir(fpath)
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{Err: probe.NewError(e)}
|
||||
contentCh <- &clientContent{Err: probe.NewError(e)}
|
||||
return
|
||||
}
|
||||
for _, file := range files {
|
||||
@@ -443,7 +481,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
|
||||
newPath := filepath.Join(fpath, fi.Name())
|
||||
lfi, le := f.handleWindowsSymlinks(newPath)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: le.Trace(newPath),
|
||||
}
|
||||
continue
|
||||
@@ -459,29 +497,29 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
|
||||
}
|
||||
pathURL = *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, lfi.Name())
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
Type: lfi.Mode(),
|
||||
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
|
||||
Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}),
|
||||
}
|
||||
continue
|
||||
} else {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.PathInsufficientPermission{Path: pathURL.Path}),
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(PathInsufficientPermission{Path: pathURL.Path}),
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.BrokenSymlink{Path: file.Name()}),
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(BrokenSymlink{Path: file.Name()}),
|
||||
}
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
continue
|
||||
@@ -499,7 +537,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
|
||||
}
|
||||
pathURL = *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, fi.Name())
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
URL: pathURL,
|
||||
Time: fi.ModTime(),
|
||||
Size: fi.Size(),
|
||||
@@ -518,7 +556,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
|
||||
return
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
URL: pathURL,
|
||||
Time: fst.ModTime(),
|
||||
Size: fst.Size(),
|
||||
@@ -528,7 +566,7 @@ func (f *fsClient) listInRoutine(contentCh chan<- *client.Content, incomplete bo
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomplete bool) {
|
||||
func (f *fsClient) listRecursiveInRoutine(contentCh chan *clientContent, incomplete bool) {
|
||||
// close channels upon return.
|
||||
defer close(contentCh)
|
||||
var dirName string
|
||||
@@ -555,7 +593,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
!strings.HasPrefix(filePrefix, fp) {
|
||||
if e == nil {
|
||||
if fi.IsDir() {
|
||||
return errSkipDir
|
||||
return ioutils.ErrSkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -571,7 +609,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
if e != nil {
|
||||
// If operation is not permitted, we throw quickly back.
|
||||
if strings.Contains(e.Error(), "operation not permitted") {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
return nil
|
||||
@@ -580,12 +618,12 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
if runtime.GOOS == "windows" {
|
||||
lfi, le := f.handleWindowsSymlinks(fp)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: le.Trace(fp),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
pathURL := *f.PathURL
|
||||
pathURL = *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, dirName)
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
@@ -596,7 +634,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
return nil
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
@@ -604,8 +642,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
} else {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.PathInsufficientPermission{Path: fp}),
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(PathInsufficientPermission{Path: fp}),
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -619,12 +657,12 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
if runtime.GOOS == "windows" {
|
||||
lfi, le := f.handleWindowsSymlinks(fp)
|
||||
if le != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: le.Trace(fp),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
pathURL := *f.PathURL
|
||||
pathURL = *f.PathURL
|
||||
pathURL.Path = filepath.Join(pathURL.Path, dirName)
|
||||
if incomplete {
|
||||
if !strings.HasSuffix(lfi.Name(), partSuffix) {
|
||||
@@ -635,7 +673,7 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
return nil
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
URL: pathURL,
|
||||
Time: lfi.ModTime(),
|
||||
Size: lfi.Size(),
|
||||
@@ -644,22 +682,22 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
}
|
||||
return nil
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Ignore in-accessible broken symlinks.
|
||||
if os.IsNotExist(e) {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.BrokenSymlink{Path: fp}),
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(BrokenSymlink{Path: fp}),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Ignore symlink loops.
|
||||
if strings.Contains(e.Error(), "too many levels of symbolic links") {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(client.TooManyLevelsSymlink{Path: fp}),
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(TooManyLevelsSymlink{Path: fp}),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -676,8 +714,8 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
return nil
|
||||
}
|
||||
}
|
||||
contentCh <- &client.Content{
|
||||
URL: *client.NewURL(fp),
|
||||
contentCh <- &clientContent{
|
||||
URL: *newURL(fp),
|
||||
Time: fi.ModTime(),
|
||||
Size: fi.Size(),
|
||||
Type: fi.Mode(),
|
||||
@@ -703,9 +741,9 @@ func (f *fsClient) listRecursiveInRoutine(contentCh chan *client.Content, incomp
|
||||
filePrefix = pathURL.Path
|
||||
}
|
||||
// walks invokes our custom function.
|
||||
e := walk(dirName, visitFS)
|
||||
e := ioutils.FTW(dirName, visitFS)
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
}
|
||||
@@ -720,26 +758,130 @@ func (f *fsClient) MakeBucket(region string) *probe.Error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketACL - get bucket access.
|
||||
func (f *fsClient) GetBucketAccess() (acl string, err *probe.Error) {
|
||||
return "", probe.NewError(client.APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
|
||||
// GetAccess - get access policy permissions.
|
||||
func (f *fsClient) GetAccess() (access string, err *probe.Error) {
|
||||
// For windows this feature is not implemented.
|
||||
if runtime.GOOS == "windows" {
|
||||
return "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
|
||||
}
|
||||
st, err := f.fsStat()
|
||||
if err != nil {
|
||||
return "", err.Trace(f.PathURL.String())
|
||||
}
|
||||
if !st.Mode().IsDir() {
|
||||
return "", probe.NewError(APINotImplemented{API: "GetAccess", APIType: "filesystem"})
|
||||
}
|
||||
switch {
|
||||
case st.Mode() == os.FileMode(0777):
|
||||
return "readwrite", nil
|
||||
case st.Mode() == os.FileMode(0555):
|
||||
return "readonly", nil
|
||||
case st.Mode() == os.FileMode(0333):
|
||||
return "writeonly", nil
|
||||
}
|
||||
return "none", nil
|
||||
}
|
||||
|
||||
// SetBucketAccess - set bucket access.
|
||||
func (f *fsClient) SetBucketAccess(acl string) *probe.Error {
|
||||
return probe.NewError(client.APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"})
|
||||
// SetAccess - set access policy permissions.
|
||||
func (f *fsClient) SetAccess(access string) *probe.Error {
|
||||
// For windows this feature is not implemented.
|
||||
if runtime.GOOS == "windows" {
|
||||
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
|
||||
}
|
||||
st, err := f.fsStat()
|
||||
if err != nil {
|
||||
return err.Trace(f.PathURL.String())
|
||||
}
|
||||
if !st.Mode().IsDir() {
|
||||
return probe.NewError(APINotImplemented{API: "SetAccess", APIType: "filesystem"})
|
||||
}
|
||||
var mode os.FileMode
|
||||
switch access {
|
||||
case "readonly":
|
||||
mode = os.FileMode(0555)
|
||||
case "writeonly":
|
||||
mode = os.FileMode(0333)
|
||||
case "readwrite":
|
||||
mode = os.FileMode(0777)
|
||||
case "none":
|
||||
mode = os.FileMode(0755)
|
||||
}
|
||||
e := os.Chmod(f.PathURL.Path, mode)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stat - get metadata from path.
|
||||
func (f *fsClient) Stat() (content *client.Content, err *probe.Error) {
|
||||
func (f *fsClient) Stat() (content *clientContent, err *probe.Error) {
|
||||
st, err := f.fsStat()
|
||||
if err != nil {
|
||||
return nil, err.Trace(f.PathURL.String())
|
||||
}
|
||||
content = new(client.Content)
|
||||
content = &clientContent{}
|
||||
content.URL = *f.PathURL
|
||||
content.Size = st.Size()
|
||||
content.Time = st.ModTime()
|
||||
content.Type = st.Mode()
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// toClientError error constructs a typed client error for known filesystem errors.
|
||||
func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
|
||||
if os.IsPermission(e) {
|
||||
return probe.NewError(PathInsufficientPermission{Path: fpath})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return probe.NewError(PathNotFound{Path: fpath})
|
||||
}
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// handle windows symlinks - eg: junction files.
|
||||
func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) {
|
||||
// On windows there are directory symlinks which are called junction files.
|
||||
// These files carry special meaning on windows they cannot be,
|
||||
// accessed with regular operations.
|
||||
file, e := os.Lstat(fpath)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, fpath)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// fsStat - wrapper function to get file stat.
|
||||
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
|
||||
fpath := f.PathURL.Path
|
||||
// Golang strips trailing / if you clean(..) or
|
||||
// EvalSymlinks(..). Adding '.' prevents it from doing so.
|
||||
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
|
||||
fpath = fpath + "."
|
||||
}
|
||||
fpath, e := filepath.EvalSymlinks(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(f.PathURL.Path)
|
||||
}
|
||||
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
st, e := os.Stat(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(fpath)
|
||||
}
|
||||
return nil, probe.NewError(PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return nil, probe.NewError(PathNotFound{Path: f.PathURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs_test
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -22,28 +22,20 @@ import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"runtime"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/client/fs"
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test list files in a folder.
|
||||
func (s *MySuite) TestList(c *C) {
|
||||
func (s *TestSuite) TestList(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
// Create multiple files.
|
||||
objectPath := filepath.Join(root, "object1")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
@@ -55,7 +47,7 @@ func (s *MySuite) TestList(c *C) {
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
objectPath = filepath.Join(root, "object2")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
@@ -63,11 +55,11 @@ func (s *MySuite) TestList(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
// Verify previously create files and list them.
|
||||
var contents []*client.Content
|
||||
var contents []*clientContent
|
||||
for content := range fsClient.List(false, false) {
|
||||
if content.Err != nil {
|
||||
err = content.Err
|
||||
@@ -81,7 +73,7 @@ func (s *MySuite) TestList(c *C) {
|
||||
|
||||
// Create another file.
|
||||
objectPath = filepath.Join(root, "test1/newObject1")
|
||||
fsClient, err = fs.New(objectPath)
|
||||
fsClient, err = fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
reader = bytes.NewReader([]byte(data))
|
||||
@@ -89,7 +81,7 @@ func (s *MySuite) TestList(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(n, Equals, int64(len(data)))
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
@@ -105,7 +97,7 @@ func (s *MySuite) TestList(c *C) {
|
||||
c.Assert(len(contents), Equals, 1)
|
||||
c.Assert(contents[0].Type.IsDir(), Equals, true)
|
||||
|
||||
fsClient, err = fs.New(root)
|
||||
fsClient, err = fsNew(root)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
contents = nil
|
||||
@@ -139,27 +131,27 @@ func (s *MySuite) TestList(c *C) {
|
||||
}
|
||||
|
||||
// Test put bucket aka 'mkdir()' operation.
|
||||
func (s *MySuite) TestPutBucket(c *C) {
|
||||
func (s *TestSuite) TestPutBucket(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
// Test stat bucket aka 'stat()' operation.
|
||||
func (s *MySuite) TestStatBucket(c *C) {
|
||||
func (s *TestSuite) TestStatBucket(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
@@ -168,32 +160,35 @@ func (s *MySuite) TestStatBucket(c *C) {
|
||||
}
|
||||
|
||||
// Test bucket acl fails for directories.
|
||||
func (s *MySuite) TestBucketACLFails(c *C) {
|
||||
func (s *TestSuite) TestBucketACLFails(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
bucketPath := filepath.Join(root, "bucket")
|
||||
fsClient, err := fs.New(bucketPath)
|
||||
fsClient, err := fsNew(bucketPath)
|
||||
c.Assert(err, IsNil)
|
||||
err = fsClient.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = fsClient.SetBucketAccess("private")
|
||||
c.Assert(err, Not(IsNil))
|
||||
// On windows setting permissions is not supported.
|
||||
if runtime.GOOS != "windows" {
|
||||
err = fsClient.SetAccess("readonly")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
_, err = fsClient.GetBucketAccess()
|
||||
c.Assert(err, Not(IsNil))
|
||||
_, err = fsClient.GetAccess()
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
}
|
||||
|
||||
// Test creating a file.
|
||||
func (s *MySuite) TestPut(c *C) {
|
||||
func (s *TestSuite) TestPut(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
@@ -205,13 +200,13 @@ func (s *MySuite) TestPut(c *C) {
|
||||
}
|
||||
|
||||
// Test read a file.
|
||||
func (s *MySuite) TestGet(c *C) {
|
||||
func (s *TestSuite) TestGet(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
@@ -231,13 +226,13 @@ func (s *MySuite) TestGet(c *C) {
|
||||
}
|
||||
|
||||
// Test get range in a file.
|
||||
func (s *MySuite) TestGetRange(c *C) {
|
||||
func (s *TestSuite) TestGetRange(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello world"
|
||||
@@ -260,13 +255,13 @@ func (s *MySuite) TestGetRange(c *C) {
|
||||
}
|
||||
|
||||
// Test stat file.
|
||||
func (s *MySuite) TestStatObject(c *C) {
|
||||
func (s *TestSuite) TestStatObject(c *C) {
|
||||
root, e := ioutil.TempDir(os.TempDir(), "fs-")
|
||||
c.Assert(e, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
|
||||
objectPath := filepath.Join(root, "object")
|
||||
fsClient, err := fs.New(objectPath)
|
||||
fsClient, err := fsNew(objectPath)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
data := "hello"
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -25,16 +25,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV2 - tracing structure
|
||||
type TraceV2 struct{}
|
||||
// traceV2 - tracing structure for signature version '2'.
|
||||
type traceV2 struct{}
|
||||
|
||||
// NewTraceV2 - initialize Trace structure
|
||||
func NewTraceV2() httptracer.HTTPTracer {
|
||||
return TraceV2{}
|
||||
// newTraceV2 - initialize Trace structure
|
||||
func newTraceV2() httptracer.HTTPTracer {
|
||||
return traceV2{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV2) Request(req *http.Request) (err error) {
|
||||
func (t traceV2) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
@@ -57,7 +57,7 @@ func (t TraceV2) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV2) Response(res *http.Response) (err error) {
|
||||
func (t traceV2) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -26,16 +26,16 @@ import (
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
)
|
||||
|
||||
// TraceV4 - tracing structure
|
||||
type TraceV4 struct{}
|
||||
// traceV4 - tracing structure for signature version '4'.
|
||||
type traceV4 struct{}
|
||||
|
||||
// NewTraceV4 - initialize Trace structure
|
||||
func NewTraceV4() httptracer.HTTPTracer {
|
||||
return TraceV4{}
|
||||
// newTraceV4 - initialize Trace structure
|
||||
func newTraceV4() httptracer.HTTPTracer {
|
||||
return traceV4{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
func (t traceV4) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
@@ -66,7 +66,7 @@ func (t TraceV4) Request(req *http.Request) (err error) {
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t TraceV4) Response(res *http.Response) (err error) {
|
||||
func (t traceV4) Response(res *http.Response) (err error) {
|
||||
var resTrace []byte
|
||||
// For errors we make sure to dump response body as well.
|
||||
if res.StatusCode != http.StatusOK &&
|
||||
+128
-123
@@ -14,13 +14,14 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
@@ -28,36 +29,35 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/httptracer"
|
||||
"github.com/minio/minio-go"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// S3 client
|
||||
type s3Client struct {
|
||||
mutex *sync.Mutex
|
||||
targetURL *client.URL
|
||||
api minio.CloudStorageClient
|
||||
targetURL *clientURL
|
||||
api *minio.Client
|
||||
virtualStyle bool
|
||||
}
|
||||
|
||||
// newFactory encloses New function with client cache.
|
||||
func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
|
||||
clientCache := make(map[uint32]minio.CloudStorageClient)
|
||||
func newFactory() func(config *Config) (Client, *probe.Error) {
|
||||
clientCache := make(map[uint32]*minio.Client)
|
||||
mutex := &sync.Mutex{}
|
||||
|
||||
// Return New function.
|
||||
return func(config *client.Config) (client.Client, *probe.Error) {
|
||||
return func(config *Config) (Client, *probe.Error) {
|
||||
// Creates a parsed URL.
|
||||
targetURL := client.NewURL(config.HostURL)
|
||||
targetURL := newURL(config.HostURL)
|
||||
// By default enable HTTPs.
|
||||
inSecure := false
|
||||
if targetURL.Scheme == "http" {
|
||||
inSecure = true
|
||||
}
|
||||
|
||||
// Instantiate s3 client.
|
||||
// Instantiate s3
|
||||
s3Clnt := &s3Client{}
|
||||
// Allocate a new mutex.
|
||||
s3Clnt.mutex = new(sync.Mutex)
|
||||
@@ -87,10 +87,10 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
|
||||
// Lookup previous cache by hash.
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
var api minio.CloudStorageClient
|
||||
var api *minio.Client
|
||||
found := false
|
||||
if api, found = clientCache[confSum]; !found {
|
||||
// Not found. Instantiate a new minio client.
|
||||
// Not found. Instantiate a new minio
|
||||
var e error
|
||||
if config.Signature == "S3v2" {
|
||||
// if Signature version '2' use NewV2 directly.
|
||||
@@ -111,15 +111,16 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
|
||||
if config.Debug {
|
||||
transport := http.DefaultTransport
|
||||
if config.Signature == "S3v4" {
|
||||
transport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV4(), http.DefaultTransport)
|
||||
}
|
||||
if config.Signature == "S3v2" {
|
||||
transport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)
|
||||
transport = httptracer.GetNewTraceTransport(newTraceV2(), http.DefaultTransport)
|
||||
}
|
||||
// Set custom transport.
|
||||
api.SetCustomTransport(transport)
|
||||
}
|
||||
|
||||
// ListObjects on a prefix with 10 million entries takes around 8 minutes.
|
||||
api.SetClientTimeout(8 * time.Minute)
|
||||
// Store the new api object.
|
||||
s3Clnt.api = api
|
||||
|
||||
@@ -127,12 +128,12 @@ func newFactory() func(config *client.Config) (client.Client, *probe.Error) {
|
||||
}
|
||||
}
|
||||
|
||||
// New returns an initialized s3Client structure. If debug is enabled,
|
||||
// s3New returns an initialized s3Client structure. If debug is enabled,
|
||||
// it also enables an internal trace transport.
|
||||
var New = newFactory()
|
||||
var s3New = newFactory()
|
||||
|
||||
// GetURL get url.
|
||||
func (c *s3Client) GetURL() client.URL {
|
||||
func (c *s3Client) GetURL() clientURL {
|
||||
return *c.targetURL
|
||||
}
|
||||
|
||||
@@ -143,7 +144,7 @@ func (c *s3Client) Get() (io.Reader, *probe.Error) {
|
||||
if e != nil {
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "AccessDenied" {
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: c.targetURL.String()})
|
||||
return nil, probe.NewError(PathInsufficientPermission{Path: c.targetURL.String()})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
@@ -160,32 +161,40 @@ func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progres
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
if bucket == "" {
|
||||
return 0, probe.NewError(BucketNameEmpty{})
|
||||
}
|
||||
n, e := c.api.PutObjectWithProgress(bucket, object, reader, contentType, progress)
|
||||
if e != nil {
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "UnexpectedEOF" || e == io.EOF {
|
||||
return n, probe.NewError(client.UnexpectedEOF{
|
||||
return n, probe.NewError(UnexpectedEOF{
|
||||
TotalSize: size,
|
||||
TotalWritten: n,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "AccessDenied" {
|
||||
return n, probe.NewError(client.PathInsufficientPermission{
|
||||
return n, probe.NewError(PathInsufficientPermission{
|
||||
Path: c.targetURL.String(),
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "MethodNotAllowed" {
|
||||
return n, probe.NewError(client.ObjectAlreadyExists{
|
||||
return n, probe.NewError(ObjectAlreadyExists{
|
||||
Object: object,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "NoSuchBucket" {
|
||||
return n, probe.NewError(client.BucketDoesNotExist{
|
||||
return n, probe.NewError(BucketDoesNotExist{
|
||||
Bucket: bucket,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "InvalidArgument" {
|
||||
return n, probe.NewError(client.ObjectMissing{})
|
||||
if errResponse.Code == "InvalidBucketName" {
|
||||
return n, probe.NewError(BucketInvalid{
|
||||
Bucket: bucket,
|
||||
})
|
||||
}
|
||||
if errResponse.Code == "NoSuchKey" || errResponse.Code == "InvalidArgument" {
|
||||
return n, probe.NewError(ObjectMissing{})
|
||||
}
|
||||
return n, probe.NewError(e)
|
||||
}
|
||||
@@ -232,44 +241,38 @@ func isValidBucketName(bucketName string) *probe.Error {
|
||||
func (c *s3Client) MakeBucket(region string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.BucketNameTopLevel{})
|
||||
return probe.NewError(BucketNameTopLevel{})
|
||||
}
|
||||
if err := isValidBucketName(bucket); err != nil {
|
||||
return err.Trace(bucket)
|
||||
}
|
||||
e := c.api.MakeBucket(bucket, minio.BucketACL("private"), region)
|
||||
e := c.api.MakeBucket(bucket, region)
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketAccess get acl on a bucket.
|
||||
func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
|
||||
// GetAccess get access policy permissions.
|
||||
func (c *s3Client) GetAccess() (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return "", probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
|
||||
}
|
||||
if bucket == "" {
|
||||
return "", probe.NewError(client.BucketNameEmpty{})
|
||||
return "", probe.NewError(BucketNameEmpty{})
|
||||
}
|
||||
bucketACL, e := c.api.GetBucketACL(bucket)
|
||||
bucketPolicy, e := c.api.GetBucketPolicy(bucket, object)
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
return bucketACL.String(), nil
|
||||
return string(bucketPolicy), nil
|
||||
}
|
||||
|
||||
// SetBucketAccess set acl on a bucket
|
||||
func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
|
||||
// SetAccess set access policy permissions.
|
||||
func (c *s3Client) SetAccess(bucketPolicy string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
|
||||
}
|
||||
if bucket == "" {
|
||||
return probe.NewError(client.BucketNameEmpty{})
|
||||
return probe.NewError(BucketNameEmpty{})
|
||||
}
|
||||
e := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
|
||||
e := c.api.SetBucketPolicy(bucket, object, minio.BucketPolicy(bucketPolicy))
|
||||
if e != nil {
|
||||
return probe.NewError(e)
|
||||
}
|
||||
@@ -277,63 +280,56 @@ func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
|
||||
}
|
||||
|
||||
// Stat - send a 'HEAD' on a bucket or object to fetch its metadata.
|
||||
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
|
||||
func (c *s3Client) Stat() (*clientContent, *probe.Error) {
|
||||
c.mutex.Lock()
|
||||
objectMetadata := new(client.Content)
|
||||
objectMetadata := &clientContent{}
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
switch {
|
||||
// valid case for 'ls -r s3/'
|
||||
case bucket == "" && object == "":
|
||||
_, e := c.api.ListBuckets()
|
||||
// Bucket name cannot be empty, stat on URL has no meaning.
|
||||
if bucket == "" {
|
||||
c.mutex.Unlock()
|
||||
return nil, probe.NewError(BucketNameEmpty{})
|
||||
} else if object == "" {
|
||||
e := c.api.BucketExists(bucket)
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
bucketMetadata := &clientContent{}
|
||||
bucketMetadata.URL = *c.targetURL
|
||||
bucketMetadata.Type = os.ModeDir
|
||||
c.mutex.Unlock()
|
||||
return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil
|
||||
return bucketMetadata, nil
|
||||
}
|
||||
if object != "" {
|
||||
metadata, e := c.api.StatObject(bucket, object)
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "NoSuchKey" {
|
||||
// Append "/" to the object name proactively and see if the Listing
|
||||
// produces an output. If yes, then we treat it as a directory.
|
||||
prefixName := object
|
||||
// Trim any trailing separators and add it.
|
||||
prefixName = strings.TrimSuffix(prefixName, string(c.targetURL.Separator)) + string(c.targetURL.Separator)
|
||||
isRecursive := false
|
||||
for objectStat := range c.api.ListObjects(bucket, prefixName, isRecursive, nil) {
|
||||
if objectStat.Err != nil {
|
||||
return nil, probe.NewError(objectStat.Err)
|
||||
}
|
||||
content := client.Content{}
|
||||
content.URL = *c.targetURL
|
||||
content.Type = os.ModeDir
|
||||
return &content, nil
|
||||
}
|
||||
return nil, probe.NewError(client.PathNotFound{Path: c.targetURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
objectMetadata.URL = *c.targetURL
|
||||
objectMetadata.Time = metadata.LastModified
|
||||
objectMetadata.Size = metadata.Size
|
||||
objectMetadata.Type = os.FileMode(0664)
|
||||
c.mutex.Unlock()
|
||||
return objectMetadata, nil
|
||||
}
|
||||
e := c.api.BucketExists(bucket)
|
||||
metadata, e := c.api.StatObject(bucket, object)
|
||||
if e != nil {
|
||||
c.mutex.Unlock()
|
||||
errResponse := minio.ToErrorResponse(e)
|
||||
if errResponse.Code == "NoSuchKey" {
|
||||
// Append "/" to the object name proactively and see if the Listing
|
||||
// produces an output. If yes, then we treat it as a directory.
|
||||
prefixName := object
|
||||
// Trim any trailing separators and add it.
|
||||
prefixName = strings.TrimSuffix(prefixName, string(c.targetURL.Separator)) + string(c.targetURL.Separator)
|
||||
isRecursive := false
|
||||
for objectStat := range c.api.ListObjects(bucket, prefixName, isRecursive, nil) {
|
||||
if objectStat.Err != nil {
|
||||
return nil, probe.NewError(objectStat.Err)
|
||||
}
|
||||
content := clientContent{}
|
||||
content.URL = *c.targetURL
|
||||
content.Type = os.ModeDir
|
||||
return &content, nil
|
||||
}
|
||||
return nil, probe.NewError(PathNotFound{Path: c.targetURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
bucketMetadata := new(client.Content)
|
||||
bucketMetadata.URL = *c.targetURL
|
||||
bucketMetadata.Type = os.ModeDir
|
||||
objectMetadata.URL = *c.targetURL
|
||||
objectMetadata.Time = metadata.LastModified
|
||||
objectMetadata.Size = metadata.Size
|
||||
objectMetadata.Type = os.FileMode(0664)
|
||||
c.mutex.Unlock()
|
||||
return bucketMetadata, nil
|
||||
return objectMetadata, nil
|
||||
}
|
||||
|
||||
func isAmazon(host string) bool {
|
||||
@@ -389,11 +385,11 @@ func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
|
||||
/// Bucket API operations.
|
||||
|
||||
// List - list at delimited path, if not recursive.
|
||||
func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
|
||||
func (c *s3Client) List(recursive, incomplete bool) <-chan *clientContent {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
contentCh := make(chan *client.Content)
|
||||
contentCh := make(chan *clientContent)
|
||||
if incomplete {
|
||||
if recursive {
|
||||
go c.listIncompleteRecursiveInRoutine(contentCh)
|
||||
@@ -410,7 +406,7 @@ func (c *s3Client) List(recursive, incomplete bool) <-chan *client.Content {
|
||||
return contentCh
|
||||
}
|
||||
|
||||
func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
|
||||
func (c *s3Client) listIncompleteInRoutine(contentCh chan *clientContent) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
@@ -418,7 +414,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
@@ -427,12 +423,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
|
||||
for _, bucket := range buckets {
|
||||
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
url := *c.targetURL
|
||||
// Join bucket with - incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), bucket.Name, object.Key)
|
||||
@@ -458,12 +454,12 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
|
||||
isRecursive := false
|
||||
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
url := *c.targetURL
|
||||
// Join bucket with - incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
@@ -487,7 +483,7 @@ func (c *s3Client) listIncompleteInRoutine(contentCh chan *client.Content) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *clientContent) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
@@ -495,7 +491,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
@@ -504,14 +500,14 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
|
||||
for _, bucket := range buckets {
|
||||
for object := range c.api.ListIncompleteUploads(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
url := *c.targetURL
|
||||
url.Path = filepath.Join(url.Path, bucket.Name, object.Key)
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
@@ -523,7 +519,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
|
||||
isRecursive := true
|
||||
for object := range c.api.ListIncompleteUploads(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
@@ -534,7 +530,7 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
|
||||
if c.virtualStyle {
|
||||
url.Path = filepath.Join(string(url.Separator), object.Key)
|
||||
}
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
content.URL = url
|
||||
content.Size = object.Size
|
||||
content.Time = object.Initiated
|
||||
@@ -544,23 +540,23 @@ func (c *s3Client) listIncompleteRecursiveInRoutine(contentCh chan *client.Conte
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
|
||||
func (c *s3Client) listInRoutine(contentCh chan *clientContent) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
Err: probe.NewError(err),
|
||||
buckets, e := c.api.ListBuckets()
|
||||
if e != nil {
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, bucket := range buckets {
|
||||
url := *c.targetURL
|
||||
url.Path = filepath.Join(url.Path, bucket.Name)
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
content.URL = url
|
||||
content.Size = 0
|
||||
content.Time = bucket.CreationDate
|
||||
@@ -568,21 +564,28 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
|
||||
contentCh <- content
|
||||
}
|
||||
case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "":
|
||||
e := c.api.BucketExists(b)
|
||||
buckets, e := c.api.ListBuckets()
|
||||
if e != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(e),
|
||||
}
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.URL = *c.targetURL
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- content
|
||||
for _, bucket := range buckets {
|
||||
if bucket.Name == b {
|
||||
content := &clientContent{}
|
||||
content.URL = *c.targetURL
|
||||
content.Size = 0
|
||||
content.Time = bucket.CreationDate
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- content
|
||||
break
|
||||
}
|
||||
}
|
||||
default:
|
||||
metadata, e := c.api.StatObject(b, o)
|
||||
switch e.(type) {
|
||||
case nil:
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
content.URL = *c.targetURL
|
||||
content.Time = metadata.LastModified
|
||||
content.Size = metadata.Size
|
||||
@@ -592,12 +595,12 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
|
||||
isRecursive := false
|
||||
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
@@ -622,7 +625,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
func (c *s3Client) listRecursiveInRoutine(contentCh chan *clientContent) {
|
||||
defer close(contentCh)
|
||||
// get bucket and object from URL.
|
||||
b, o := c.url2BucketAndObject()
|
||||
@@ -630,7 +633,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
case b == "" && o == "":
|
||||
buckets, err := c.api.ListBuckets()
|
||||
if err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(err),
|
||||
}
|
||||
return
|
||||
@@ -638,7 +641,7 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
for _, bucket := range buckets {
|
||||
bucketURL := *c.targetURL
|
||||
bucketURL.Path = filepath.Join(bucketURL.Path, bucket.Name)
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
URL: bucketURL,
|
||||
Type: os.ModeDir,
|
||||
Time: bucket.CreationDate,
|
||||
@@ -646,12 +649,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
isRecursive := true
|
||||
for object := range c.api.ListObjects(bucket.Name, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
objectURL := *c.targetURL
|
||||
objectURL.Path = filepath.Join(objectURL.Path, bucket.Name, object.Key)
|
||||
content.URL = objectURL
|
||||
@@ -665,12 +668,12 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
isRecursive := true
|
||||
for object := range c.api.ListObjects(b, o, isRecursive, nil) {
|
||||
if object.Err != nil {
|
||||
contentCh <- &client.Content{
|
||||
contentCh <- &clientContent{
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := new(client.Content)
|
||||
content := &clientContent{}
|
||||
url := *c.targetURL
|
||||
// Join bucket and incoming object key.
|
||||
url.Path = filepath.Join(string(url.Separator), b, object.Key)
|
||||
@@ -690,7 +693,9 @@ func (c *s3Client) listRecursiveInRoutine(contentCh chan *client.Content) {
|
||||
// ShareDownload - get a usable presigned object url to share.
|
||||
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, e := c.api.PresignedGetObject(bucket, object, expires)
|
||||
// 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)
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package s3
|
||||
package main
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
@@ -23,11 +23,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
@@ -60,13 +57,6 @@ func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case r.Method == "PUT":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
// Handler for incoming SetBucketACL request.
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
if r.Header.Get("x-amz-acl") != "public-read-write" {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
@@ -168,36 +158,27 @@ func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
// Test bucket operations.
|
||||
func (s *MySuite) TestBucketOperations(c *C) {
|
||||
func (s *TestSuite) TestBucketOperations(c *C) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket/",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf := new(Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
s3c, err := s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket("us-east-1")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.SetBucketAccess("public-read-write")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.GetURL().Separator)
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
@@ -206,7 +187,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket"
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
@@ -215,7 +196,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket/"
|
||||
s3c, err = New(conf)
|
||||
s3c, err = s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false, false) {
|
||||
@@ -225,7 +206,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
|
||||
}
|
||||
|
||||
// Test all object operations.
|
||||
func (s *MySuite) TestObjectOperations(c *C) {
|
||||
func (s *TestSuite) TestObjectOperations(c *C) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
@@ -233,12 +214,12 @@ func (s *MySuite) TestObjectOperations(c *C) {
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf := new(Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
conf.AccessKey = "WLGDGYAQYIGI833EV05A"
|
||||
conf.SecretKey = "BYvgJM101sHngl2uzjXS/OBF/aMxAN06JrJ3qJlF"
|
||||
conf.Signature = "S3v4"
|
||||
s3c, err := New(conf)
|
||||
s3c, err := s3New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
var reader io.Reader
|
||||
@@ -14,26 +14,28 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Client - client interface
|
||||
type Client interface {
|
||||
// Common operations
|
||||
Stat() (content *Content, err *probe.Error)
|
||||
List(recursive, incomplete bool) <-chan *Content
|
||||
Stat() (content *clientContent, err *probe.Error)
|
||||
List(recursive, incomplete bool) <-chan *clientContent
|
||||
|
||||
// Bucket operations
|
||||
MakeBucket(region string) *probe.Error
|
||||
GetBucketAccess() (access string, error *probe.Error)
|
||||
SetBucketAccess(access string) *probe.Error
|
||||
|
||||
// Access policy operations.
|
||||
GetAccess() (access string, error *probe.Error)
|
||||
SetAccess(access string) *probe.Error
|
||||
|
||||
// I/O operations
|
||||
Get() (reader io.Reader, err *probe.Error)
|
||||
@@ -47,12 +49,12 @@ type Client interface {
|
||||
Remove(incomplete bool) *probe.Error
|
||||
|
||||
// GetURL returns back internal url
|
||||
GetURL() URL
|
||||
GetURL() clientURL
|
||||
}
|
||||
|
||||
// Content container for content metadata
|
||||
type Content struct {
|
||||
URL URL
|
||||
type clientContent struct {
|
||||
URL clientURL
|
||||
Time time.Time
|
||||
Size int64
|
||||
Type os.FileMode
|
||||
+34
-12
@@ -23,15 +23,13 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/client/fs"
|
||||
"github.com/minio/mc/pkg/client/s3"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Check if the target URL represents folder. It may or may not exist yet.
|
||||
func isTargetURLDir(targetURL string) bool {
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
targetURLParse := newURL(targetURL)
|
||||
_, targetContent, err := url2Stat(targetURL)
|
||||
if err != nil {
|
||||
_, aliasedTargetURL, _ := mustExpandAlias(targetURL)
|
||||
@@ -101,12 +99,12 @@ func putTargetStream(urlStr string, reader io.Reader, size int64) (int64, *probe
|
||||
// newClientFromAlias gives a new client interface for matching
|
||||
// alias entry in the mc config file. If no matching host config entry
|
||||
// is found, fs client is returned.
|
||||
func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Error) {
|
||||
func newClientFromAlias(alias string, urlStr string) (Client, *probe.Error) {
|
||||
hostCfg := mustGetHostConfig(alias)
|
||||
if hostCfg == nil {
|
||||
// No matching host config. So we treat it like a
|
||||
// filesystem.
|
||||
fsClient, err := fs.New(urlStr)
|
||||
fsClient, err := fsNew(urlStr)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
@@ -115,9 +113,33 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
|
||||
|
||||
// We have a valid alias and hostConfig. We populate the
|
||||
// credentials from the match found in the config file.
|
||||
s3Config := new(client.Config)
|
||||
s3Config.AccessKey = hostCfg.AccessKey
|
||||
s3Config.SecretKey = hostCfg.SecretKey
|
||||
s3Config := new(Config)
|
||||
|
||||
// secretKey retrieved from the environement overrides the one
|
||||
// present in the config file
|
||||
keysPairEnv := os.Getenv("MC_SECRET_" + alias)
|
||||
keysPairArray := strings.Split(keysPairEnv, ":")
|
||||
var accessKeyEnv, secretKeyEnv string
|
||||
if len(keysPairArray) >= 1 {
|
||||
accessKeyEnv = keysPairArray[0]
|
||||
}
|
||||
if len(keysPairArray) >= 2 {
|
||||
secretKeyEnv = keysPairArray[1]
|
||||
}
|
||||
if len(keysPairEnv) > 0 &&
|
||||
isValidAccessKey(accessKeyEnv) && isValidSecretKey(secretKeyEnv) {
|
||||
s3Config.AccessKey = accessKeyEnv
|
||||
s3Config.SecretKey = secretKeyEnv
|
||||
} else {
|
||||
if len(keysPairEnv) > 0 {
|
||||
console.Errorln("Access/Secret keys associated to `" + alias + "' " +
|
||||
"are found in your environment but not suitable for use. " +
|
||||
"Falling back to the standard config.")
|
||||
}
|
||||
s3Config.AccessKey = hostCfg.AccessKey
|
||||
s3Config.SecretKey = hostCfg.SecretKey
|
||||
}
|
||||
|
||||
s3Config.Signature = hostCfg.API
|
||||
s3Config.AppName = "mc"
|
||||
s3Config.AppVersion = mcVersion
|
||||
@@ -125,7 +147,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
|
||||
s3Config.HostURL = urlStr
|
||||
s3Config.Debug = globalDebug
|
||||
|
||||
s3Client, err := s3.New(s3Config)
|
||||
s3Client, err := s3New(s3Config)
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias, urlStr)
|
||||
}
|
||||
@@ -136,7 +158,7 @@ func newClientFromAlias(alias string, urlStr string) (client.Client, *probe.Erro
|
||||
var urlRgx = regexp.MustCompile("^https?://")
|
||||
|
||||
// newClient gives a new client interface
|
||||
func newClient(aliasedURL string) (client.Client, *probe.Error) {
|
||||
func newClient(aliasedURL string) (Client, *probe.Error) {
|
||||
alias, urlStrFull, hostCfg, err := expandAlias(aliasedURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(aliasedURL)
|
||||
|
||||
+2
-3
@@ -20,9 +20,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
func fixConfig() {
|
||||
@@ -132,7 +131,7 @@ func fixConfigV6ForHosts() {
|
||||
newCfgV6.Aliases[k] = v
|
||||
}
|
||||
|
||||
url := new(client.URL)
|
||||
url := &clientURL{}
|
||||
// Copy hosts.
|
||||
for host, hostCfgV6 := range brokenMcCfgV6.Data().(*configV6).Hosts {
|
||||
// Already fixed - Copy and move on.
|
||||
|
||||
+12
-12
@@ -24,7 +24,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -58,11 +58,11 @@ FLAGS:
|
||||
EXAMPLES:
|
||||
1. Add Amazon S3 storage service under "myphotos" alias. For security reasons turn off bash history momentarily.
|
||||
$ set +o history
|
||||
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ mc config {{.Name}} add myphotos https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ set -o history
|
||||
|
||||
2. Add Google Cloud Storage service under "goodisk" alias.
|
||||
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
|
||||
$ mc config {{.Name}} add goodisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2
|
||||
|
||||
3. List all hosts.
|
||||
$ mc config {{.Name}} list
|
||||
@@ -217,7 +217,7 @@ func mainConfigHost(ctx *cli.Context) {
|
||||
if strings.TrimSpace(api) == "" {
|
||||
api = "S3v4"
|
||||
}
|
||||
hostCfg := hostConfigV7{
|
||||
hostCfg := hostConfigV8{
|
||||
URL: url,
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
@@ -233,23 +233,23 @@ func mainConfigHost(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
// addHost - add a host config.
|
||||
func addHost(alias string, hostCfgV7 hostConfigV7) {
|
||||
mcCfgV7, err := loadMcConfig()
|
||||
func addHost(alias string, hostCfgV8 hostConfigV8) {
|
||||
mcCfgV8, err := loadMcConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Unable to load config ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
// Add new host.
|
||||
mcCfgV7.Hosts[alias] = hostCfgV7
|
||||
mcCfgV8.Hosts[alias] = hostCfgV8
|
||||
|
||||
err = saveMcConfig(mcCfgV7)
|
||||
err = saveMcConfig(mcCfgV8)
|
||||
fatalIf(err.Trace(alias), "Unable to update hosts in config version ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
printMsg(hostMessage{
|
||||
op: "add",
|
||||
Alias: alias,
|
||||
URL: hostCfgV7.URL,
|
||||
AccessKey: hostCfgV7.AccessKey,
|
||||
SecretKey: hostCfgV7.SecretKey,
|
||||
API: hostCfgV7.API,
|
||||
URL: hostCfgV8.URL,
|
||||
AccessKey: hostCfgV8.AccessKey,
|
||||
SecretKey: hostCfgV8.SecretKey,
|
||||
API: hostCfgV8.API,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+58
-1
@@ -21,7 +21,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
// migrate config files from the any older version to the latest.
|
||||
@@ -40,6 +40,8 @@ func migrateConfig() {
|
||||
migrateConfigV5ToV6()
|
||||
// Migrate config V6 to V7
|
||||
migrateConfigV6ToV7()
|
||||
// Migrate config V7 to V8
|
||||
migrateConfigV7ToV8()
|
||||
}
|
||||
|
||||
// Migrate from config version 1.0 to 1.0.1. Populate example entries and save it back.
|
||||
@@ -332,8 +334,24 @@ func migrateConfigV6ToV7() {
|
||||
|
||||
cfgV7 := newConfigV7()
|
||||
aliasIndex := 0
|
||||
|
||||
// old Aliases.
|
||||
oldAliases := mcCfgV6.Data().(*configV6).Aliases
|
||||
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV6 := range mcCfgV6.Data().(*configV6).Hosts {
|
||||
// Look through old aliases, if found any matching save those entries.
|
||||
for aliasName, aliasedHost := range oldAliases {
|
||||
if aliasedHost == host {
|
||||
cfgV7.Hosts[aliasName] = hostConfigV7{
|
||||
URL: host,
|
||||
AccessKey: hostCfgV6.AccessKeyID,
|
||||
SecretKey: hostCfgV6.SecretAccessKey,
|
||||
API: hostCfgV6.API,
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if hostCfgV6.AccessKeyID == "YOUR-ACCESS-KEY-ID-HERE" ||
|
||||
hostCfgV6.SecretAccessKey == "YOUR-SECRET-ACCESS-KEY-HERE" ||
|
||||
hostCfgV6.AccessKeyID == "" ||
|
||||
@@ -378,3 +396,42 @@ func migrateConfigV6ToV7() {
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘6’ to version ‘7’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
// Migrate config version ‘7’ to ‘8'. Remove hosts
|
||||
// 'play.minio.io:9002' and 'dl.minio.io:9000'.
|
||||
func migrateConfigV7ToV8() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
|
||||
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V7.")
|
||||
|
||||
if mcCfgV7.Version() != "7" {
|
||||
return
|
||||
}
|
||||
|
||||
cfgV8 := newConfigV8()
|
||||
// We dropped alias support in v7. We only need to migrate host configs.
|
||||
for host, hostCfgV7 := range mcCfgV7.Data().(*configV7).Hosts {
|
||||
// Ignore 'player', 'play' and 'dl' aliases.
|
||||
if host == "player" || host == "dl" || host == "play" {
|
||||
continue
|
||||
}
|
||||
hostCfgV8 := hostConfigV8{}
|
||||
hostCfgV8.URL = hostCfgV7.URL
|
||||
hostCfgV8.AccessKey = hostCfgV7.AccessKey
|
||||
hostCfgV8.SecretKey = hostCfgV7.SecretKey
|
||||
hostCfgV8.API = hostCfgV7.API
|
||||
cfgV8.Hosts[host] = hostCfgV8
|
||||
}
|
||||
// Load default settings.
|
||||
cfgV8.loadDefaults()
|
||||
mcNewCfgV8, err := quick.New(cfgV8)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘8’.")
|
||||
|
||||
err = mcNewCfgV8.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘8’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘7’ to version ‘8’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
+81
-1
@@ -160,5 +160,85 @@ func newConfigV6() *configV6 {
|
||||
return conf
|
||||
}
|
||||
|
||||
/////////////////// Config V7 ///////////////////
|
||||
/////////////////// Config V6 ///////////////////
|
||||
// hostConfig configuration of a host - version '7'.
|
||||
type hostConfigV7 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version '7'.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
cfg.Version = "7"
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
return cfg
|
||||
}
|
||||
|
||||
func (c *configV7) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
API: "S3v2",
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////// Config V8 ///////////////////
|
||||
// RESERVED FOR FUTURE
|
||||
|
||||
+17
-3
@@ -1,10 +1,24 @@
|
||||
/*
|
||||
* Minio Client (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
)
|
||||
|
||||
// isValidSecretKey - validate secret key.
|
||||
@@ -30,7 +44,7 @@ func isValidHostURL(hostURL string) bool {
|
||||
if strings.TrimSpace(hostURL) == "" {
|
||||
return false
|
||||
}
|
||||
url := client.NewURL(hostURL)
|
||||
url := newURL(hostURL)
|
||||
if url.Scheme != "https" && url.Scheme != "http" {
|
||||
return false
|
||||
}
|
||||
|
||||
+29
-45
@@ -19,8 +19,8 @@ package main
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -30,44 +30,44 @@ const (
|
||||
|
||||
var (
|
||||
// set once during first load.
|
||||
cacheCfgV7 *configV7
|
||||
cacheCfgV8 *configV8
|
||||
// All access to mc config file should be synchronized.
|
||||
cfgMutex = &sync.RWMutex{}
|
||||
)
|
||||
|
||||
// hostConfig configuration of a host.
|
||||
type hostConfigV7 struct {
|
||||
type hostConfigV8 struct {
|
||||
URL string `json:"url"`
|
||||
AccessKey string `json:"accessKey"`
|
||||
SecretKey string `json:"secretKey"`
|
||||
API string `json:"api"`
|
||||
}
|
||||
|
||||
// configV7 config version.
|
||||
type configV7 struct {
|
||||
// configV8 config version.
|
||||
type configV8 struct {
|
||||
Version string `json:"version"`
|
||||
Hosts map[string]hostConfigV7 `json:"hosts"`
|
||||
Hosts map[string]hostConfigV8 `json:"hosts"`
|
||||
}
|
||||
|
||||
// newConfigV7 - new config version.
|
||||
func newConfigV7() *configV7 {
|
||||
cfg := new(configV7)
|
||||
// newConfigV8 - new config version.
|
||||
func newConfigV8() *configV8 {
|
||||
cfg := new(configV8)
|
||||
cfg.Version = globalMCConfigVersion
|
||||
cfg.Hosts = make(map[string]hostConfigV7)
|
||||
cfg.Hosts = make(map[string]hostConfigV8)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// SetHost sets host config if not empty.
|
||||
func (c *configV7) setHost(alias string, cfg hostConfigV7) {
|
||||
func (c *configV8) setHost(alias string, cfg hostConfigV8) {
|
||||
if _, ok := c.Hosts[alias]; !ok {
|
||||
c.Hosts[alias] = cfg
|
||||
}
|
||||
}
|
||||
|
||||
// load default values for missing entries.
|
||||
func (c *configV7) loadDefaults() {
|
||||
func (c *configV8) loadDefaults() {
|
||||
// Minio server running locally.
|
||||
c.setHost("local", hostConfigV7{
|
||||
c.setHost("local", hostConfigV8{
|
||||
URL: "http://localhost:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
@@ -75,7 +75,7 @@ func (c *configV7) loadDefaults() {
|
||||
})
|
||||
|
||||
// Amazon S3 cloud storage service.
|
||||
c.setHost("s3", hostConfigV7{
|
||||
c.setHost("s3", hostConfigV8{
|
||||
URL: "https://s3.amazonaws.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
@@ -83,7 +83,7 @@ func (c *configV7) loadDefaults() {
|
||||
})
|
||||
|
||||
// Google cloud storage service.
|
||||
c.setHost("gcs", hostConfigV7{
|
||||
c.setHost("gcs", hostConfigV8{
|
||||
URL: "https://storage.googleapis.com",
|
||||
AccessKey: defaultAccessKey,
|
||||
SecretKey: defaultSecretKey,
|
||||
@@ -91,67 +91,51 @@ func (c *configV7) loadDefaults() {
|
||||
})
|
||||
|
||||
// Minio anonymous server for demo.
|
||||
c.setHost("play", hostConfigV7{
|
||||
c.setHost("play", hostConfigV8{
|
||||
URL: "https://play.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio demo server with public secret and access keys.
|
||||
c.setHost("player", hostConfigV7{
|
||||
URL: "https://play.minio.io:9002",
|
||||
AccessKey: "Q3AM3UQ867SPQQA43P2F",
|
||||
SecretKey: "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
|
||||
API: "S3v4",
|
||||
})
|
||||
|
||||
// Minio public download service.
|
||||
c.setHost("dl", hostConfigV7{
|
||||
URL: "https://dl.minio.io:9000",
|
||||
AccessKey: "",
|
||||
SecretKey: "",
|
||||
API: "S3v4",
|
||||
})
|
||||
}
|
||||
|
||||
// loadConfigV7 - loads a new config.
|
||||
func loadConfigV7() (*configV7, *probe.Error) {
|
||||
// loadConfigV8 - loads a new config.
|
||||
func loadConfigV8() (*configV8, *probe.Error) {
|
||||
cfgMutex.RLock()
|
||||
defer cfgMutex.RUnlock()
|
||||
|
||||
// Cached in private global variable.
|
||||
if cacheCfgV7 != nil {
|
||||
return cacheCfgV7, nil
|
||||
if cacheCfgV8 != nil {
|
||||
return cacheCfgV8, nil
|
||||
}
|
||||
|
||||
if !isMcConfigExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
|
||||
mcCfgV7, err := quick.Load(mustGetMcConfigPath(), newConfigV7())
|
||||
mcCfgV8, err := quick.Load(mustGetMcConfigPath(), newConfigV8())
|
||||
fatalIf(err.Trace(), "Unable to load mc config file ‘"+mustGetMcConfigPath()+"’.")
|
||||
|
||||
cfgV7 := mcCfgV7.Data().(*configV7)
|
||||
cfgV8 := mcCfgV8.Data().(*configV8)
|
||||
|
||||
// cache it.
|
||||
cacheCfgV7 = cfgV7
|
||||
cacheCfgV8 = cfgV8
|
||||
|
||||
return cfgV7, nil
|
||||
return cfgV8, nil
|
||||
}
|
||||
|
||||
// saveConfigV7 - saves an updated config.
|
||||
func saveConfigV7(cfgV7 *configV7) *probe.Error {
|
||||
// saveConfigV8 - saves an updated config.
|
||||
func saveConfigV8(cfgV8 *configV8) *probe.Error {
|
||||
cfgMutex.Lock()
|
||||
defer cfgMutex.Unlock()
|
||||
|
||||
qs, err := quick.New(cfgV7)
|
||||
qs, err := quick.New(cfgV8)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
// update the cache.
|
||||
cacheCfgV7 = cfgV7
|
||||
cacheCfgV8 = cfgV8
|
||||
|
||||
return qs.Save(mustGetMcConfigPath()).Trace(mustGetMcConfigPath())
|
||||
}
|
||||
@@ -22,16 +22,13 @@ import (
|
||||
"regexp"
|
||||
"runtime"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/user"
|
||||
"github.com/minio/go-homedir"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// mcCustomConfigDir contains the whole path to config dir. Only access via get/set functions.
|
||||
var mcCustomConfigDir string
|
||||
|
||||
// mcCustomConfigPath contains the whole path to config file. Only access via get/set functions.
|
||||
var mcCustomConfigPath string
|
||||
|
||||
// setMcConfigDir - set a custom minio client config folder.
|
||||
func setMcConfigDir(configDir string) {
|
||||
mcCustomConfigDir = configDir
|
||||
@@ -42,17 +39,18 @@ func getMcConfigDir() (string, *probe.Error) {
|
||||
if mcCustomConfigDir != "" {
|
||||
return mcCustomConfigDir, nil
|
||||
}
|
||||
homeDir, e := user.HomeDir()
|
||||
homeDir, e := homedir.Dir()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
var configDir string
|
||||
// For windows the path is slightly different
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return filepath.Join(homeDir, globalMCConfigWindowsDir), nil
|
||||
default:
|
||||
return filepath.Join(homeDir, globalMCConfigDir), nil
|
||||
if runtime.GOOS == "windows" {
|
||||
configDir = filepath.Join(homeDir, globalMCConfigWindowsDir)
|
||||
} else {
|
||||
configDir = filepath.Join(homeDir, globalMCConfigDir)
|
||||
}
|
||||
return configDir, nil
|
||||
}
|
||||
|
||||
// mustGetMcConfigDir - construct minio client config folder or fail
|
||||
@@ -77,8 +75,8 @@ func createMcConfigDir() *probe.Error {
|
||||
|
||||
// getMcConfigPath - construct minio client configuration path
|
||||
func getMcConfigPath() (string, *probe.Error) {
|
||||
if mcCustomConfigPath != "" {
|
||||
return mcCustomConfigPath, nil
|
||||
if mcCustomConfigDir != "" {
|
||||
return filepath.Join(mcCustomConfigDir, globalMCConfigFile), nil
|
||||
}
|
||||
dir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
@@ -96,19 +94,19 @@ func mustGetMcConfigPath() string {
|
||||
}
|
||||
|
||||
// newMcConfig - initializes a new version '6' config.
|
||||
func newMcConfig() *configV7 {
|
||||
cfg := newConfigV7()
|
||||
func newMcConfig() *configV8 {
|
||||
cfg := newConfigV8()
|
||||
cfg.loadDefaults()
|
||||
return cfg
|
||||
}
|
||||
|
||||
// loadMcConfigCached - returns loadMcConfig with a closure for config cache.
|
||||
func loadMcConfigFactory() func() (*configV7, *probe.Error) {
|
||||
func loadMcConfigFactory() func() (*configV8, *probe.Error) {
|
||||
// Load once and cache in a closure.
|
||||
cfgCache, err := loadConfigV7()
|
||||
cfgCache, err := loadConfigV8()
|
||||
|
||||
// loadMcConfig - reads configuration file and returns config.
|
||||
return func() (*configV7, *probe.Error) {
|
||||
return func() (*configV8, *probe.Error) {
|
||||
return cfgCache, err
|
||||
}
|
||||
}
|
||||
@@ -116,7 +114,7 @@ func loadMcConfigFactory() func() (*configV7, *probe.Error) {
|
||||
var loadMcConfig = loadMcConfigFactory()
|
||||
|
||||
// saveMcConfig - saves configuration file and returns error if any.
|
||||
func saveMcConfig(config *configV7) *probe.Error {
|
||||
func saveMcConfig(config *configV8) *probe.Error {
|
||||
if config == nil {
|
||||
return errInvalidArgument().Trace()
|
||||
}
|
||||
@@ -127,7 +125,7 @@ func saveMcConfig(config *configV7) *probe.Error {
|
||||
}
|
||||
|
||||
// Save the config.
|
||||
if err := saveConfigV7(config); err != nil {
|
||||
if err := saveConfigV8(config); err != nil {
|
||||
return err.Trace(mustGetMcConfigPath())
|
||||
}
|
||||
|
||||
@@ -154,7 +152,7 @@ func isValidAlias(alias string) bool {
|
||||
}
|
||||
|
||||
// getHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
func getHostConfig(alias string) (*hostConfigV8, *probe.Error) {
|
||||
mcCfg, err := loadMcConfig()
|
||||
if err != nil {
|
||||
return nil, err.Trace(alias)
|
||||
@@ -171,13 +169,13 @@ func getHostConfig(alias string) (*hostConfigV7, *probe.Error) {
|
||||
}
|
||||
|
||||
// mustGetHostConfig retrieves host specific configuration such as access keys, signature type.
|
||||
func mustGetHostConfig(alias string) *hostConfigV7 {
|
||||
func mustGetHostConfig(alias string) *hostConfigV8 {
|
||||
hostCfg, _ := getHostConfig(alias)
|
||||
return hostCfg
|
||||
}
|
||||
|
||||
// expandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7, err *probe.Error) {
|
||||
func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8, err *probe.Error) {
|
||||
// Extract alias from the URL.
|
||||
alias, path := url2Alias(aliasedURL)
|
||||
|
||||
@@ -189,7 +187,7 @@ func expandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostC
|
||||
}
|
||||
|
||||
// mustExpandAlias expands aliased URL if any match is found, returns as is otherwise.
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV7) {
|
||||
func mustExpandAlias(aliasedURL string) (alias string, urlStr string, hostCfg *hostConfigV8) {
|
||||
alias, urlStr, hostCfg, _ = expandAlias(aliasedURL)
|
||||
return alias, urlStr, hostCfg
|
||||
}
|
||||
|
||||
+11
-12
@@ -29,9 +29,8 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
)
|
||||
|
||||
@@ -115,14 +114,14 @@ type copyStatMessage struct {
|
||||
|
||||
// copyStatMessage copy accounting message
|
||||
func (c copyStatMessage) String() string {
|
||||
speedBox := pb.FormatBytes(int64(c.Speed))
|
||||
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.FormatBytes(c.Total),
|
||||
pb.FormatBytes(c.Transferred), speedBox)
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
|
||||
return message
|
||||
}
|
||||
|
||||
@@ -313,17 +312,17 @@ func doCopySession(session *sessionV6) {
|
||||
switch cpURLs.Error.ToGoError().(type) {
|
||||
// Handle this specifically for filesystem related
|
||||
// errors.
|
||||
case client.BrokenSymlink:
|
||||
case BrokenSymlink:
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
case TooManyLevelsSymlink:
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
case PathNotFound:
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
case PathInsufficientPermission:
|
||||
continue
|
||||
case client.ObjectAlreadyExists:
|
||||
case ObjectAlreadyExists:
|
||||
continue
|
||||
case client.BucketDoesNotExist:
|
||||
case BucketDoesNotExist:
|
||||
continue
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
@@ -356,7 +355,7 @@ func doCopySession(session *sessionV6) {
|
||||
wg.Wait()
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
if progressReader.ProgressBar.Total > 0 {
|
||||
if progressReader.ProgressBar.Get() > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
|
||||
+1
-2
@@ -20,7 +20,6 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
)
|
||||
|
||||
func checkCopySyntax(ctx *cli.Context) {
|
||||
@@ -40,7 +39,7 @@ func checkCopySyntax(ctx *cli.Context) {
|
||||
|
||||
/****** Generic Invalid Rules *******/
|
||||
// Check if bucket name is passed for URL type arguments.
|
||||
url := client.NewURL(tgtURL)
|
||||
url := newURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
// This check is for type URL.
|
||||
if !isURLVirtualHostStyle(url.Host) {
|
||||
|
||||
@@ -20,15 +20,14 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type copyURLs struct {
|
||||
SourceAlias string
|
||||
SourceContent *client.Content
|
||||
SourceContent *clientContent
|
||||
TargetAlias string
|
||||
TargetContent *client.Content
|
||||
TargetContent *clientContent
|
||||
Error *probe.Error `json:"-"`
|
||||
}
|
||||
|
||||
@@ -57,7 +56,7 @@ const (
|
||||
copyURLsTypeD
|
||||
)
|
||||
|
||||
// guessCopyURLType guesses the type of URL. This approach all allows prepareURL
|
||||
// guessCopyURLType guesses the type of clientURL. This approach all allows prepareURL
|
||||
// functions to accurately report failure causes.
|
||||
func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (copyURLsType, *probe.Error) {
|
||||
if len(sourceURLs) == 1 { // 1 Source, 1 Target
|
||||
@@ -90,11 +89,11 @@ func guessCopyURLType(sourceURLs []string, targetURL string, isRecursive bool) (
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type A: copy(f, f) -> copy(f, f)
|
||||
// prepareCopyURLsTypeA - prepares target and source URLs for copying.
|
||||
// prepareCopyURLsTypeA - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
@@ -116,21 +115,21 @@ func prepareCopyURLsTypeA(sourceURL string, targetURL string) copyURLs {
|
||||
}
|
||||
|
||||
// prepareCopyContentTypeA - makes CopyURLs content for copying.
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
func makeCopyContentTypeA(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
|
||||
return copyURLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
TargetAlias: targetAlias,
|
||||
TargetContent: &client.Content{URL: *client.NewURL(targetURL)},
|
||||
TargetContent: &clientContent{URL: *newURL(targetURL)},
|
||||
}
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type B: copy(f, d) -> copy(f, d/f) -> A
|
||||
// prepareCopyURLsTypeB - prepares target and source URLs for copying.
|
||||
// prepareCopyURLsTypeB - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
_, sourceContent, err := url2Stat(sourceURL)
|
||||
@@ -152,19 +151,19 @@ func prepareCopyURLsTypeB(sourceURL string, targetURL string) copyURLs {
|
||||
}
|
||||
|
||||
// makeCopyContentTypeB - CopyURLs content for copying.
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
func makeCopyContentTypeB(sourceAlias string, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
|
||||
// All OK.. We can proceed. Type B: source is a file, target is a folder and exists.
|
||||
targetURLParse := client.NewURL(targetURL)
|
||||
targetURLParse := newURL(targetURL)
|
||||
targetURLParse.Path = filepath.ToSlash(filepath.Join(targetURLParse.Path, filepath.Base(sourceContent.URL.Path)))
|
||||
return makeCopyContentTypeA(sourceAlias, sourceContent, targetAlias, targetURLParse.String())
|
||||
}
|
||||
|
||||
// SINGLE SOURCE - Type C: copy(d1..., d2) -> []copy(d1/f, d1/d2/f) -> []A
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source URLs for copying.
|
||||
// prepareCopyRecursiveURLTypeC - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
// Extract alias before fiddling with the URL.
|
||||
// Extract alias before fiddling with the clientURL.
|
||||
sourceAlias, _, _ := mustExpandAlias(sourceURL)
|
||||
// Find alias and expanded URL.
|
||||
// Find alias and expanded clientURL.
|
||||
targetAlias, targetURL, _ := mustExpandAlias(targetURL)
|
||||
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
@@ -197,7 +196,7 @@ func prepareCopyURLsTypeC(sourceURL, targetURL string, isRecursive bool) <-chan
|
||||
}
|
||||
|
||||
// makeCopyContentTypeC - CopyURLs content for copying.
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceContent *client.Content, targetAlias string, targetURL string) copyURLs {
|
||||
func makeCopyContentTypeC(sourceAlias string, sourceURL clientURL, sourceContent *clientContent, targetAlias string, targetURL string) copyURLs {
|
||||
newSourceURL := sourceContent.URL
|
||||
pathSeparatorIndex := strings.LastIndex(sourceURL.Path, string(sourceURL.Separator))
|
||||
newSourceSuffix := filepath.ToSlash(newSourceURL.Path)
|
||||
@@ -210,7 +209,7 @@ func makeCopyContentTypeC(sourceAlias string, sourceURL client.URL, sourceConten
|
||||
}
|
||||
|
||||
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B
|
||||
// prepareCopyURLsTypeE - prepares target and source URLs for copying.
|
||||
// prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
@@ -224,7 +223,7 @@ func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive boo
|
||||
return copyURLsCh
|
||||
}
|
||||
|
||||
// prepareCopyURLs - prepares target and source URLs for copying.
|
||||
// prepareCopyURLs - prepares target and source clientURLs for copying.
|
||||
func prepareCopyURLs(sourceURLs []string, targetURL string, isRecursive bool) <-chan copyURLs {
|
||||
copyURLsCh := make(chan copyURLs)
|
||||
go func(sourceURLs []string, targetURL string, copyURLsCh chan copyURLs) {
|
||||
|
||||
+40
-26
@@ -23,9 +23,8 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// diff specific flags.
|
||||
@@ -71,7 +70,7 @@ type diffMessage struct {
|
||||
Status string `json:"status"`
|
||||
FirstURL string `json:"first"`
|
||||
SecondURL string `json:"second"`
|
||||
Diff string `json:"diff"`
|
||||
Diff differType `json:"diff"`
|
||||
Error *probe.Error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
@@ -79,15 +78,18 @@ type diffMessage struct {
|
||||
func (d diffMessage) String() string {
|
||||
msg := ""
|
||||
switch d.Diff {
|
||||
case "only-in-first":
|
||||
case differInFirst:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffOnlyInFirst", " - only in first.")
|
||||
case "type":
|
||||
case differInType:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffType", " - differ in type.")
|
||||
case "size":
|
||||
case differInSize:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffSize", " - differ in size.")
|
||||
case differInTime:
|
||||
msg = console.Colorize("DiffMessage",
|
||||
"‘"+d.FirstURL+"’"+" and "+"‘"+d.SecondURL+"’") + console.Colorize("DiffTime", " - differ in modified time.")
|
||||
default:
|
||||
fatalIf(errDummy().Trace(d.FirstURL, d.SecondURL),
|
||||
"Unhandled difference between ‘"+d.FirstURL+"’ and ‘"+d.SecondURL+"’.")
|
||||
@@ -101,7 +103,7 @@ func (d diffMessage) JSON() string {
|
||||
d.Status = "success"
|
||||
diffJSONBytes, e := json.Marshal(d)
|
||||
fatalIf(probe.NewError(e),
|
||||
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+d.Diff+"’.")
|
||||
"Unable to marshal diff message ‘"+d.FirstURL+"’, ‘"+d.SecondURL+"’ and ‘"+string(d.Diff)+"’.")
|
||||
return string(diffJSONBytes)
|
||||
}
|
||||
|
||||
@@ -125,6 +127,7 @@ func checkDiffSyntax(ctx *cli.Context) {
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstURL), fmt.Sprintf("Unable to stat '%s'.", firstURL))
|
||||
}
|
||||
|
||||
// Verify if its a directory.
|
||||
if !firstContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(firstURL), fmt.Sprintf("‘%s’ is not a folder.", firstURL))
|
||||
@@ -135,6 +138,7 @@ func checkDiffSyntax(ctx *cli.Context) {
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(secondURL), fmt.Sprintf("Unable to stat '%s'.", secondURL))
|
||||
}
|
||||
|
||||
// Verify if its a directory.
|
||||
if !secondContent.Type.IsDir() {
|
||||
fatalIf(errInvalidArgument().Trace(secondURL), fmt.Sprintf("‘%s’ is not a folder.", secondURL))
|
||||
@@ -144,11 +148,11 @@ func checkDiffSyntax(ctx *cli.Context) {
|
||||
// doDiffMain runs the diff.
|
||||
func doDiffMain(firstURL, secondURL string) {
|
||||
// Source and targets are always directories
|
||||
sourceSeparator := string(client.NewURL(firstURL).Separator)
|
||||
sourceSeparator := string(newURL(firstURL).Separator)
|
||||
if !strings.HasSuffix(firstURL, sourceSeparator) {
|
||||
firstURL = firstURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(client.NewURL(secondURL).Separator)
|
||||
targetSeparator := string(newURL(secondURL).Separator)
|
||||
if !strings.HasSuffix(secondURL, targetSeparator) {
|
||||
secondURL = secondURL + targetSeparator
|
||||
}
|
||||
@@ -162,40 +166,49 @@ func doDiffMain(firstURL, secondURL string) {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
difference, err := objectDifferenceFactory(secondAlias, secondURL)
|
||||
|
||||
secondClient, err := newClientFromAlias(secondAlias, secondURL)
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(firstAlias, firstURL, secondAlias, secondURL),
|
||||
fmt.Sprintf("Failed to diff '%s' and '%s'", firstURL, secondURL))
|
||||
}
|
||||
isRecursive := true
|
||||
isIncomplete := false
|
||||
for sourceContent := range firstClient.List(isRecursive, isIncomplete) {
|
||||
if sourceContent.Err != nil {
|
||||
switch sourceContent.Err.ToGoError().(type) {
|
||||
|
||||
// Setup object difference function.
|
||||
difference := objectDifferenceFactory(secondClient)
|
||||
|
||||
// Set default values for listing.
|
||||
isRecursive := true // recursive is always true for diff.
|
||||
isIncomplete := false // we will not compare any incomplete objects.
|
||||
|
||||
// List all the elements on first URL and compare with
|
||||
// 'difference' function.
|
||||
for firstContent := range firstClient.List(isRecursive, isIncomplete) {
|
||||
if firstContent.Err != nil {
|
||||
switch firstContent.Err.ToGoError().(type) {
|
||||
// Handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission:
|
||||
errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
|
||||
errorIf(firstContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
default:
|
||||
fatalIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
fatalIf(firstContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if sourceContent.Type.IsDir() {
|
||||
if firstContent.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
suffix := strings.TrimPrefix(sourceContent.URL.String(), firstURL)
|
||||
differ, err := difference(suffix, sourceContent.Type, sourceContent.Size)
|
||||
firstSuffix := strings.TrimPrefix(firstContent.URL.String(), firstURL)
|
||||
differ, err := difference(secondURL, firstSuffix, firstContent.Type, firstContent.Size, firstContent.Time)
|
||||
if err != nil {
|
||||
errorIf(sourceContent.Err.Trace(secondURL, suffix),
|
||||
fmt.Sprintf("Failed on '%s'", urlJoinPath(secondURL, suffix)))
|
||||
errorIf(firstContent.Err.Trace(secondURL, firstSuffix),
|
||||
fmt.Sprintf("Failed on '%s'", urlJoinPath(secondURL, firstSuffix)))
|
||||
continue
|
||||
}
|
||||
if differ == differNone {
|
||||
if differ == differInNone {
|
||||
continue
|
||||
}
|
||||
printMsg(diffMessage{
|
||||
FirstURL: sourceContent.URL.String(),
|
||||
SecondURL: urlJoinPath(secondURL, suffix),
|
||||
FirstURL: firstContent.URL.String(),
|
||||
SecondURL: urlJoinPath(secondURL, firstSuffix),
|
||||
Diff: differ,
|
||||
})
|
||||
}
|
||||
@@ -214,6 +227,7 @@ func mainDiff(ctx *cli.Context) {
|
||||
console.SetColor("DiffOnlyInFirst", color.New(color.FgRed, color.Bold))
|
||||
console.SetColor("DiffType", color.New(color.FgYellow, color.Bold))
|
||||
console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold))
|
||||
console.SetColor("DiffTime", color.New(color.FgYellow, color.Bold))
|
||||
|
||||
URLs := ctx.Args()
|
||||
firstURL := URLs[0]
|
||||
|
||||
+35
-32
@@ -18,66 +18,70 @@ package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// objectDifference function finds the difference between object on source and target
|
||||
// it takes suffix string, type and size on the source
|
||||
// objectDifferenceFactory returns objectDifference function
|
||||
type objectDifference func(string, os.FileMode, int64) (string, *probe.Error)
|
||||
// objectDifference function finds the difference between object on
|
||||
// source and target it takes suffix string, type and size on the
|
||||
// source objectDifferenceFactory returns objectDifference function
|
||||
type objectDifference func(string, string, os.FileMode, int64, time.Time) (differType, *probe.Error)
|
||||
|
||||
// differType difference in type.
|
||||
type differType string
|
||||
|
||||
const (
|
||||
differSize string = "size" // differs in size
|
||||
differOnlyFirst string = "only-in-first" // only on source
|
||||
differType string = "type" // differs in type, ex file/directory
|
||||
differNone string = "" // does not differ
|
||||
differInSize differType = "size" // differs in size
|
||||
differInTime = "time" // differs in time
|
||||
differInFirst = "only-in-first" // only on first source
|
||||
differInType = "type" // differs in type, exfile/directory
|
||||
differInNone = "" // does not differ
|
||||
)
|
||||
|
||||
// objectDifferenceFactory returns objectDifference function to check for difference
|
||||
// between sourceURL and targetURL
|
||||
// for usage reference check diff and mirror commands
|
||||
func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, *probe.Error) {
|
||||
clnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
return nil, err.Trace(targetAlias, targetURL)
|
||||
}
|
||||
// between sourceURL and targetURL, for usage reference check diff and mirror commands.
|
||||
func objectDifferenceFactory(targetClnt Client) objectDifference {
|
||||
isIncomplete := false
|
||||
isRecursive := true
|
||||
ch := clnt.List(isRecursive, isIncomplete)
|
||||
current := targetURL
|
||||
ch := targetClnt.List(isRecursive, isIncomplete)
|
||||
reachedEOF := false
|
||||
ok := false
|
||||
var content *client.Content
|
||||
var content *clientContent
|
||||
|
||||
difference := func(suffix string, srcType os.FileMode, srcSize int64) (string, *probe.Error) {
|
||||
return func(targetURL string, srcSuffix string, srcType os.FileMode, srcSize int64, srcTime time.Time) (differType, *probe.Error) {
|
||||
if reachedEOF {
|
||||
// would mean the suffix is not on target
|
||||
return differOnlyFirst, nil
|
||||
// Would mean the suffix is not on target.
|
||||
return differInFirst, nil
|
||||
}
|
||||
expected := urlJoinPath(targetURL, suffix)
|
||||
current := targetURL
|
||||
expected := urlJoinPath(targetURL, srcSuffix)
|
||||
for {
|
||||
if expected < current {
|
||||
return differOnlyFirst, nil // not available in the target
|
||||
return differInFirst, nil // Not available in the target.
|
||||
}
|
||||
if expected == current {
|
||||
tgtType := content.Type
|
||||
tgtSize := content.Size
|
||||
tgtTime := content.Time
|
||||
if srcType.IsRegular() && !tgtType.IsRegular() {
|
||||
// Type differes. Source is never a directory
|
||||
return differType, nil
|
||||
// Type differes. Source is never a directory.
|
||||
return differInType, nil
|
||||
}
|
||||
if (srcType.IsRegular() && tgtType.IsRegular()) && srcSize != tgtSize {
|
||||
// regular files differing in size
|
||||
return differSize, nil
|
||||
// Regular files differing in size.
|
||||
return differInSize, nil
|
||||
}
|
||||
return differNone, nil // available in the target
|
||||
if (srcType.IsRegular() && tgtType.IsRegular()) && srcTime.After(tgtTime) {
|
||||
// Regular files differing in time.
|
||||
return differInTime, nil
|
||||
}
|
||||
return differInNone, nil // Available in the target.
|
||||
}
|
||||
content, ok = <-ch
|
||||
if !ok {
|
||||
reachedEOF = true
|
||||
return differOnlyFirst, nil
|
||||
return differInFirst, nil
|
||||
}
|
||||
if content.Err != nil {
|
||||
return "", content.Err.Trace()
|
||||
@@ -85,5 +89,4 @@ func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, *
|
||||
current = content.URL.String()
|
||||
}
|
||||
}
|
||||
return difference, nil
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// causeMessage container for golang error messages
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
package main
|
||||
|
||||
func normalizePath(path string) string {
|
||||
return path
|
||||
@@ -16,7 +16,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
+1
-1
@@ -24,7 +24,7 @@ import (
|
||||
|
||||
// mc configuration related constants.
|
||||
const (
|
||||
globalMCConfigVersion = "7"
|
||||
globalMCConfigVersion = "8"
|
||||
|
||||
globalMCConfigDir = ".mc/"
|
||||
globalMCConfigWindowsDir = "mc\\"
|
||||
|
||||
+1
-2
@@ -21,7 +21,6 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
@@ -127,7 +126,7 @@ func mainList(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
for _, targetURL := range args {
|
||||
var clnt client.Client
|
||||
var clnt Client
|
||||
clnt, err := newClient(targetURL)
|
||||
fatalIf(err.Trace(targetURL), "Unable to initialize target ‘"+targetURL+"’.")
|
||||
|
||||
|
||||
@@ -25,9 +25,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// printDate - human friendly formatted date.
|
||||
@@ -67,7 +66,7 @@ func (c contentMessage) JSON() string {
|
||||
}
|
||||
|
||||
// parseContent parse client Content container into printer struct.
|
||||
func parseContent(c *client.Content) contentMessage {
|
||||
func parseContent(c *clientContent) contentMessage {
|
||||
content := contentMessage{}
|
||||
content.Time = c.Time.Local()
|
||||
|
||||
@@ -105,7 +104,7 @@ func parseContent(c *client.Content) contentMessage {
|
||||
}
|
||||
|
||||
// doList - list all entities inside a folder.
|
||||
func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
func doList(clnt Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
prefixPath := clnt.GetURL().Path
|
||||
separator := string(clnt.GetURL().Separator)
|
||||
if !strings.HasSuffix(prefixPath, separator) {
|
||||
@@ -115,16 +114,16 @@ func doList(clnt client.Client, isRecursive, isIncomplete bool) *probe.Error {
|
||||
if content.Err != nil {
|
||||
switch content.Err.ToGoError().(type) {
|
||||
// handle this specifically for filesystem related errors.
|
||||
case client.BrokenSymlink:
|
||||
case BrokenSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.")
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
case TooManyLevelsSymlink:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.")
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
case PathNotFound:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
case PathInsufficientPermission:
|
||||
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -24,10 +24,8 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/contentdb"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
"github.com/olekukonko/ts"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -80,6 +78,8 @@ func commandNotFound(ctx *cli.Context, command string) {
|
||||
|
||||
// Check for sane config environment early on and gracefully report.
|
||||
func checkConfig() {
|
||||
// Refresh the config once.
|
||||
loadMcConfig = loadMcConfigFactory()
|
||||
// Ensures config file is sane.
|
||||
_, err := loadMcConfig()
|
||||
fatalIf(err.Trace(mustGetMcConfigPath()), "Unable to access configuration file.")
|
||||
@@ -108,10 +108,10 @@ func getSystemData() map[string]string {
|
||||
memstats := &runtime.MemStats{}
|
||||
runtime.ReadMemStats(memstats)
|
||||
mem := fmt.Sprintf("Used: %s | Allocated: %s | UsedHeap: %s | AllocatedHeap: %s",
|
||||
pb.FormatBytes(int64(memstats.Alloc)),
|
||||
pb.FormatBytes(int64(memstats.TotalAlloc)),
|
||||
pb.FormatBytes(int64(memstats.HeapAlloc)),
|
||||
pb.FormatBytes(int64(memstats.HeapSys)))
|
||||
pb.Format(int64(memstats.Alloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.TotalAlloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.HeapAlloc)).To(pb.U_BYTES),
|
||||
pb.Format(int64(memstats.HeapSys)).To(pb.U_BYTES))
|
||||
platform := fmt.Sprintf("Host: %s | OS: %s | Arch: %s", host, runtime.GOOS, runtime.GOARCH)
|
||||
goruntime := fmt.Sprintf("Version: %s | CPUs: %s", runtime.Version(), strconv.Itoa(runtime.NumCPU()))
|
||||
return map[string]string{
|
||||
@@ -191,12 +191,11 @@ func main() {
|
||||
probe.SetAppInfo("Release-Tag", mcReleaseTag)
|
||||
probe.SetAppInfo("Commit", mcShortCommitID)
|
||||
|
||||
contentdb.Init() // Load contentdb into memory.
|
||||
app := registerApp()
|
||||
app.Before = registerBefore
|
||||
|
||||
app.ExtraInfo = func() map[string]string {
|
||||
if _, e := ts.GetSize(); e != nil {
|
||||
if _, e := pb.GetTerminalWidth(); e != nil {
|
||||
globalQuiet = true
|
||||
}
|
||||
if globalDebug {
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
+9
-13
@@ -46,18 +46,18 @@ func (s *TestSuite) TearDownSuite(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestValidPERMS(c *C) {
|
||||
perms := accessPerms("private")
|
||||
perms := accessPerms("none")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "private")
|
||||
perms = accessPerms("public")
|
||||
c.Assert(string(perms), Equals, "none")
|
||||
perms = accessPerms("readwrite")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read-write")
|
||||
c.Assert(string(perms), Equals, "readwrite")
|
||||
perms = accessPerms("readonly")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "public-read")
|
||||
perms = accessPerms("authorized")
|
||||
c.Assert(string(perms), Equals, "readonly")
|
||||
perms = accessPerms("writeonly")
|
||||
c.Assert(perms.isValidAccessPERM(), Equals, true)
|
||||
c.Assert(perms.String(), Equals, "authenticated-read")
|
||||
c.Assert(string(perms), Equals, "writeonly")
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestInvalidPERMS(c *C) {
|
||||
@@ -76,11 +76,7 @@ func (s *TestSuite) TestGetMcConfigPath(c *C) {
|
||||
dir, err := getMcConfigPath()
|
||||
c.Assert(err, IsNil)
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
fallthrough
|
||||
case "freebsd":
|
||||
fallthrough
|
||||
case "darwin":
|
||||
case "linux", "freebsd", "darwin", "solaris":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
case "windows":
|
||||
c.Assert(dir, Equals, filepath.Join(mustGetMcConfigDir(), "config.json"))
|
||||
@@ -125,7 +121,7 @@ func (s *TestSuite) TestCommonPrefix(c *C) {
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestVersions(c *C) {
|
||||
v1 := newVersion("1.5.1")
|
||||
v1 := newVersion("1.6")
|
||||
v2 := newVersion("1.5.0")
|
||||
c.Assert(v2.LessThan(v1), Equals, true)
|
||||
c.Assert(v1.LessThan(v2), Equals, false)
|
||||
|
||||
+37
-25
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Client, (C) 2015 Minio, Inc.
|
||||
* Minio Client, (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -28,9 +28,8 @@ import (
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
)
|
||||
|
||||
@@ -45,6 +44,10 @@ var (
|
||||
Name: "force",
|
||||
Usage: "Force overwrite of an existing target(s).",
|
||||
},
|
||||
cli.BoolFlag{
|
||||
Name: "fake",
|
||||
Usage: "Perform a fake mirror operation.",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -72,6 +75,13 @@ EXAMPLES:
|
||||
|
||||
3. Mirror a bucket from aliased Amazon S3 cloud storage to a folder on Windows.
|
||||
$ mc {{.Name}} s3\documents\2014\ C:\backup\2014
|
||||
|
||||
4. Mirror a bucket from aliased Amazon S3 cloud storage to a local folder use '--force' to overwrite destination.
|
||||
$ mc {{.Name}} --force s3/miniocloud miniocloud-backup
|
||||
|
||||
5. Fake mirror a bucket from Minio cloud storage to a bucket on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} --fake play/photos/2014 s3/backup-photos/2014
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -105,14 +115,14 @@ type mirrorStatMessage struct {
|
||||
|
||||
// mirrorStatMessage mirror accounting message
|
||||
func (c mirrorStatMessage) String() string {
|
||||
speedBox := pb.FormatBytes(int64(c.Speed))
|
||||
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
|
||||
if speedBox == "" {
|
||||
speedBox = "0 MB"
|
||||
} else {
|
||||
speedBox = speedBox + "/s"
|
||||
}
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.FormatBytes(c.Total),
|
||||
pb.FormatBytes(c.Transferred), speedBox)
|
||||
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
|
||||
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
|
||||
return message
|
||||
}
|
||||
|
||||
@@ -173,7 +183,7 @@ func doMirrorFake(sURLs mirrorURLs, progressReader *progressBar) mirrorURLs {
|
||||
}
|
||||
|
||||
// doPrepareMirrorURLs scans the source URL and prepares a list of objects for mirroring.
|
||||
func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
|
||||
func doPrepareMirrorURLs(session *sessionV6, isForce bool, isFake bool, trapCh <-chan bool) {
|
||||
sourceURL := session.Header.CommandArgs[0] // first one is source.
|
||||
targetURL := session.Header.CommandArgs[1]
|
||||
var totalBytes int64
|
||||
@@ -187,7 +197,7 @@ func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
|
||||
scanBar = scanBarFactory()
|
||||
}
|
||||
|
||||
URLsCh := prepareMirrorURLs(sourceURL, targetURL, isForce)
|
||||
URLsCh := prepareMirrorURLs(sourceURL, targetURL, isForce, isFake)
|
||||
done := false
|
||||
for done == false {
|
||||
select {
|
||||
@@ -236,10 +246,13 @@ func doPrepareMirrorURLs(session *sessionV6, isForce bool, trapCh <-chan bool) {
|
||||
// Session'fied mirror command.
|
||||
func doMirrorSession(session *sessionV6) {
|
||||
isForce := session.Header.CommandBoolFlags["force"]
|
||||
isFake := session.Header.CommandBoolFlags["fake"]
|
||||
|
||||
// Initialize signal trap.
|
||||
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
if !session.HasData() {
|
||||
doPrepareMirrorURLs(session, isForce, trapCh)
|
||||
doPrepareMirrorURLs(session, isForce, isFake, trapCh)
|
||||
}
|
||||
|
||||
// Enable accounting reader by default.
|
||||
@@ -295,31 +308,22 @@ func doMirrorSession(session *sessionV6) {
|
||||
// For all non critical errors we can continue for the
|
||||
// remaining files.
|
||||
switch sURLs.Error.ToGoError().(type) {
|
||||
// Handle this specifically for filesystem related
|
||||
// errors.
|
||||
case client.BrokenSymlink:
|
||||
// Handle this specifically for filesystem related errors.
|
||||
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
|
||||
continue
|
||||
case client.TooManyLevelsSymlink:
|
||||
continue
|
||||
case client.PathNotFound:
|
||||
continue
|
||||
case client.PathInsufficientPermission:
|
||||
continue
|
||||
case client.ObjectAlreadyExists:
|
||||
continue
|
||||
case client.BucketDoesNotExist:
|
||||
case BucketNameEmpty, ObjectMissing, ObjectAlreadyExists, BucketDoesNotExist, BucketInvalid:
|
||||
continue
|
||||
}
|
||||
// For critical errors we should exit. Session
|
||||
// can be resumed after the user figures out
|
||||
// the problem.
|
||||
// the problem.
|
||||
session.CloseAndDie()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Loop through all urls.
|
||||
// Loop through all urls and mirror.
|
||||
for urlScanner.Scan() {
|
||||
var sURLs mirrorURLs
|
||||
// Unmarshal copyURLs from each line.
|
||||
@@ -328,7 +332,13 @@ func doMirrorSession(session *sessionV6) {
|
||||
if isCopied(sURLs.SourceContent.URL.String()) {
|
||||
statusCh <- doMirrorFake(sURLs, progressReader)
|
||||
} else {
|
||||
statusCh <- doMirror(sURLs, progressReader, accntReader)
|
||||
// Mirror is initiated if its not a fake run.
|
||||
if !isFake {
|
||||
statusCh <- doMirror(sURLs, progressReader, accntReader)
|
||||
} else {
|
||||
// fake Mirror is initiated if its a fake run.
|
||||
statusCh <- doMirrorFake(sURLs, progressReader)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,7 +349,7 @@ func doMirrorSession(session *sessionV6) {
|
||||
wg.Wait()
|
||||
|
||||
if !globalQuiet && !globalJSON {
|
||||
if progressReader.ProgressBar.Total > 0 {
|
||||
if progressReader.ProgressBar.Get() > 0 {
|
||||
progressReader.ProgressBar.Finish()
|
||||
}
|
||||
} else {
|
||||
@@ -375,7 +385,9 @@ func mainMirror(ctx *cli.Context) {
|
||||
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
isFake := ctx.Bool("fake")
|
||||
session.Header.CommandBoolFlags["force"] = isForce
|
||||
session.Header.CommandBoolFlags["fake"] = isFake
|
||||
|
||||
// extract URLs.
|
||||
session.Header.CommandArgs = ctx.Args()
|
||||
|
||||
+38
-31
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
* Minio Client (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,15 +21,14 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type mirrorURLs struct {
|
||||
SourceAlias string
|
||||
SourceContent *client.Content
|
||||
SourceContent *clientContent
|
||||
TargetAlias string
|
||||
TargetContent *client.Content
|
||||
TargetContent *clientContent
|
||||
Error *probe.Error `json:"-"`
|
||||
}
|
||||
|
||||
@@ -75,7 +74,7 @@ func checkMirrorSyntax(ctx *cli.Context) {
|
||||
fatalIf(errInvalidArgument().Trace(), "Invalid target arguments to mirror command.")
|
||||
}
|
||||
|
||||
url := client.NewURL(tgtURL)
|
||||
url := newURL(tgtURL)
|
||||
if url.Host != "" {
|
||||
if !isURLVirtualHostStyle(url.Host) {
|
||||
if url.Path == string(url.Separator) {
|
||||
@@ -85,19 +84,19 @@ func checkMirrorSyntax(ctx *cli.Context) {
|
||||
}
|
||||
}
|
||||
_, _, err = url2Stat(tgtURL)
|
||||
// we die on any error other than client.PathNotFound - destination directory need not exist.
|
||||
if _, ok := err.ToGoError().(client.PathNotFound); !ok {
|
||||
fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat %s", tgtURL))
|
||||
// we die on any error other than PathNotFound - destination directory need not exist.
|
||||
if _, ok := err.ToGoError().(PathNotFound); !ok {
|
||||
fatalIf(err.Trace(tgtURL), fmt.Sprintf("Unable to stat target ‘%s’.", tgtURL))
|
||||
}
|
||||
}
|
||||
|
||||
func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirrorURLsCh chan<- mirrorURLs) {
|
||||
func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, isFake bool, mirrorURLsCh chan<- mirrorURLs) {
|
||||
// source and targets are always directories
|
||||
sourceSeparator := string(client.NewURL(sourceURL).Separator)
|
||||
sourceSeparator := string(newURL(sourceURL).Separator)
|
||||
if !strings.HasSuffix(sourceURL, sourceSeparator) {
|
||||
sourceURL = sourceURL + sourceSeparator
|
||||
}
|
||||
targetSeparator := string(client.NewURL(targetURL).Separator)
|
||||
targetSeparator := string(newURL(targetURL).Separator)
|
||||
if !strings.HasSuffix(targetURL, targetSeparator) {
|
||||
targetURL = targetURL + targetSeparator
|
||||
}
|
||||
@@ -108,19 +107,27 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
|
||||
|
||||
defer close(mirrorURLsCh)
|
||||
|
||||
objectDifferenceTarget, err := objectDifferenceFactory(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetAlias, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
sourceClient, err := newClientFromAlias(sourceAlias, sourceURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceAlias, sourceURL)}
|
||||
return
|
||||
}
|
||||
|
||||
for sourceContent := range sourceClient.List(true, false) {
|
||||
targetClnt, err := newClientFromAlias(targetAlias, targetURL)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(targetAlias, targetURL)}
|
||||
return
|
||||
}
|
||||
|
||||
// Setup object difference.
|
||||
objectDifferenceTarget := objectDifferenceFactory(targetClnt)
|
||||
|
||||
// Set default values for listing.
|
||||
isRecursive := true // recursive is always true for diff.
|
||||
isIncomplete := false // we will not compare any incomplete objects.
|
||||
|
||||
// List all the sources, compare using 'objectDifference' function.
|
||||
for sourceContent := range sourceClient.List(isRecursive, isIncomplete) {
|
||||
if sourceContent.Err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
Error: sourceContent.Err.Trace(sourceClient.GetURL().String()),
|
||||
@@ -130,28 +137,28 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
|
||||
if sourceContent.Type.IsDir() {
|
||||
continue
|
||||
}
|
||||
suffix := strings.TrimPrefix(sourceContent.URL.String(), sourceURL)
|
||||
differ, err := objectDifferenceTarget(suffix, sourceContent.Type, sourceContent.Size)
|
||||
sourceSuffix := strings.TrimPrefix(sourceContent.URL.String(), sourceURL)
|
||||
differ, err := objectDifferenceTarget(targetURL, sourceSuffix, sourceContent.Type, sourceContent.Size, sourceContent.Time)
|
||||
if err != nil {
|
||||
mirrorURLsCh <- mirrorURLs{Error: err.Trace(sourceContent.URL.String())}
|
||||
continue
|
||||
}
|
||||
if differ == differNone {
|
||||
// no difference, continue
|
||||
if differ == differInNone {
|
||||
// No difference, continue.
|
||||
continue
|
||||
}
|
||||
if differ == differType {
|
||||
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(suffix)}
|
||||
if differ == differInType {
|
||||
mirrorURLsCh <- mirrorURLs{Error: errInvalidTarget(sourceSuffix)}
|
||||
continue
|
||||
}
|
||||
if differ == differSize && !isForce {
|
||||
// size differs and force not set
|
||||
if differ == differInSize && !isForce && !isFake {
|
||||
// Size differs and force not set
|
||||
mirrorURLsCh <- mirrorURLs{Error: errOverWriteNotAllowed(sourceContent.URL.String())}
|
||||
continue
|
||||
}
|
||||
// either available only in source or size differs and force is set
|
||||
targetPath := urlJoinPath(targetURL, suffix)
|
||||
targetContent := &client.Content{URL: *client.NewURL(targetPath)}
|
||||
targetPath := urlJoinPath(targetURL, sourceSuffix)
|
||||
targetContent := &clientContent{URL: *newURL(targetPath)}
|
||||
mirrorURLsCh <- mirrorURLs{
|
||||
SourceAlias: sourceAlias,
|
||||
SourceContent: sourceContent,
|
||||
@@ -161,8 +168,8 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
|
||||
}
|
||||
}
|
||||
|
||||
func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool) <-chan mirrorURLs {
|
||||
func prepareMirrorURLs(sourceURL string, targetURL string, isForce bool, isFake bool) <-chan mirrorURLs {
|
||||
mirrorURLsCh := make(chan mirrorURLs)
|
||||
go deltaSourceTargets(sourceURL, targetURL, isForce, mirrorURLsCh)
|
||||
go deltaSourceTargets(sourceURL, targetURL, isForce, isFake, mirrorURLsCh)
|
||||
return mirrorURLsCh
|
||||
}
|
||||
|
||||
+4
-6
@@ -23,8 +23,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
)
|
||||
|
||||
// colorizeUpdateMessage - inspired from Yeoman project npm package https://github.com/yeoman/update-notifier.
|
||||
@@ -49,15 +49,13 @@ func colorizeUpdateMessage(updateString string) (string, *probe.Error) {
|
||||
line1Rest := maxContentWidth - line1Length
|
||||
line2Rest := maxContentWidth - line2Length
|
||||
|
||||
// Fetch terminal size to calculate optimal box size.
|
||||
terminal, e := ts.GetSize()
|
||||
termWidth, e := pb.GetTerminalWidth()
|
||||
if e != nil {
|
||||
return "", probe.NewError(e)
|
||||
}
|
||||
|
||||
var message string
|
||||
switch {
|
||||
case len(line2Str) > terminal.Col():
|
||||
case len(line2Str) > termWidth:
|
||||
message = "\n" + line1InColor + "\n" + line2InColor + "\n"
|
||||
default:
|
||||
// on windows terminal turn off unicode characters.
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@ import (
|
||||
"syscall"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -55,7 +55,7 @@ EXAMPLES:
|
||||
2. Write contents of stdin to an object on Amazon S3 cloud storage.
|
||||
$ mc {{.Name}} s3/personalbuck/meeting-notes.txt
|
||||
|
||||
3. Copy an ISO image to an object on Amazon S3 cloud storage and Google Cloud Storage simultaneously.
|
||||
3. Copy an ISO image to an object on Amazon S3 cloud storage.
|
||||
$ cat debian-8.2.iso | mc {{.Name}} s3/ferenginar/gnuos.iso
|
||||
|
||||
4. Stream MySQL database dump to Amazon S3 directly.
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
func (s *MySuite) TestURLParse(c *C) {
|
||||
u := NewURL("http://s3.example.com")
|
||||
c.Assert(u.Scheme, Equals, "http")
|
||||
c.Assert(u.Host, Equals, "s3.example.com")
|
||||
c.Assert(u.Path, Equals, "/")
|
||||
c.Assert(u.SchemeSeparator, Equals, "://")
|
||||
|
||||
u = NewURL("http://s3.example.com/path/new")
|
||||
c.Assert(u.Scheme, Equals, "http")
|
||||
c.Assert(u.Host, Equals, "s3.example.com")
|
||||
c.Assert(u.Path, Equals, "/path/new")
|
||||
c.Assert(u.SchemeSeparator, Equals, "://")
|
||||
|
||||
u = NewURL(":::://s3.example.com/path/new")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, ":::://s3.example.com/path/new")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
|
||||
u = NewURL("localhost:9000")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, "localhost:9000")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
}
|
||||
|
||||
func (s *MySuite) TestPathParse(c *C) {
|
||||
u := NewURL("path/test")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, "path/test")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
|
||||
u = NewURL("/path/test")
|
||||
c.Assert(u.Scheme, Equals, "")
|
||||
c.Assert(u.Host, Equals, "")
|
||||
c.Assert(u.Path, Equals, "/path/test")
|
||||
c.Assert(u.SchemeSeparator, Equals, "")
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
*#
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
)
|
||||
|
||||
// toClientError error constructs a typed client error for known filesystem errors.
|
||||
func (f *fsClient) toClientError(e error, fpath string) *probe.Error {
|
||||
if os.IsPermission(e) {
|
||||
return probe.NewError(client.PathInsufficientPermission{Path: fpath})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return probe.NewError(client.PathNotFound{Path: fpath})
|
||||
}
|
||||
return probe.NewError(e)
|
||||
}
|
||||
|
||||
// handle windows symlinks - eg: junction files.
|
||||
func (f *fsClient) handleWindowsSymlinks(fpath string) (os.FileInfo, *probe.Error) {
|
||||
// On windows there are directory symlinks which are called junction files.
|
||||
// These files carry special meaning on windows they cannot be,
|
||||
// accessed with regular operations.
|
||||
file, e := os.Lstat(fpath)
|
||||
if e != nil {
|
||||
err := f.toClientError(e, fpath)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// fsStat - wrapper function to get file stat.
|
||||
func (f *fsClient) fsStat() (os.FileInfo, *probe.Error) {
|
||||
fpath := f.PathURL.Path
|
||||
// Golang strips trailing / if you clean(..) or
|
||||
// EvalSymlinks(..). Adding '.' prevents it from doing so.
|
||||
if strings.HasSuffix(fpath, string(f.PathURL.Separator)) {
|
||||
fpath = fpath + "."
|
||||
}
|
||||
fpath, e := filepath.EvalSymlinks(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(f.PathURL.Path)
|
||||
}
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
err := f.toClientError(e, f.PathURL.Path)
|
||||
return nil, err.Trace(fpath)
|
||||
}
|
||||
st, e := os.Stat(fpath)
|
||||
if e != nil {
|
||||
if os.IsPermission(e) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return f.handleWindowsSymlinks(fpath)
|
||||
}
|
||||
return nil, probe.NewError(client.PathInsufficientPermission{Path: f.PathURL.Path})
|
||||
}
|
||||
if os.IsNotExist(e) {
|
||||
return nil, probe.NewError(client.PathNotFound{Path: f.PathURL.Path})
|
||||
}
|
||||
return nil, probe.NewError(e)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this fs except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package fs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// byDirName implements sort.Interface.
|
||||
type byDirName []os.FileInfo
|
||||
|
||||
func (f byDirName) Len() int { return len(f) }
|
||||
func (f byDirName) Less(i, j int) bool {
|
||||
// For directory add an ending separator fortrue lexical order.
|
||||
if f[i].Mode().IsDir() {
|
||||
return f[i].Name()+string(filepath.Separator) < f[j].Name()
|
||||
}
|
||||
// For directory add an ending separator for true lexical order.
|
||||
if f[j].Mode().IsDir() {
|
||||
return f[i].Name() < f[j].Name()+string(filepath.Separator)
|
||||
}
|
||||
return f[i].Name() < f[j].Name()
|
||||
}
|
||||
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
|
||||
|
||||
// readDir reads the directory named by dirname and returns
|
||||
// a list of sorted directory entries.
|
||||
func readDir(dirname string) ([]os.FileInfo, error) {
|
||||
f, e := os.Open(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
list, e := f.Readdir(-1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Sort(byDirName(list))
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// readDirNames reads the directory named by dirname and returns
|
||||
// a sorted list of directory entries.
|
||||
func readDirNames(dirname string) ([]string, error) {
|
||||
names, e := readDirUnsortedNames(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// getRealName - gets the proper filename for sorting purposes
|
||||
// Readdir() filters out directory names without separators, add
|
||||
// them back for proper sorting results.
|
||||
func getRealName(info os.FileInfo) string {
|
||||
if info.IsDir() {
|
||||
// Make sure directory has its end separator.
|
||||
return info.Name() + string(filepath.Separator)
|
||||
}
|
||||
return info.Name()
|
||||
}
|
||||
|
||||
// readDirUnsortedNames reads the directory named by dirname and
|
||||
// return a unsorted list of directory entries.
|
||||
func readDirUnsortedNames(dirname string) ([]string, error) {
|
||||
f, e := os.Open(dirname)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
nameInfos, e := f.Readdir(-1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = f.Close(); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var names []string
|
||||
for _, nameInfo := range nameInfos {
|
||||
names = append(names, getRealName(nameInfo))
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// walk walks the file tree rooted at root, calling walkFn for each file or
|
||||
// directory in the tree, including root.
|
||||
func walk(root string, walkFn walkFunc) error {
|
||||
info, e := os.Lstat(root)
|
||||
if e != nil {
|
||||
return walkFn(root, nil, e)
|
||||
}
|
||||
return walkInternal(root, info, walkFn)
|
||||
}
|
||||
|
||||
// WalkFunc is the type of the function called for each file or directory
|
||||
// visited by Walk. The path argument contains the argument to Walk as a
|
||||
// prefix; that is, if Walk is called with "dir", which is a directory
|
||||
// containing the file "a", the walk function will be called with argument
|
||||
// "dir/a". The info argument is the os.FileInfo for the named path.
|
||||
type walkFunc func(path string, info os.FileInfo, e error) error
|
||||
|
||||
// ErrSkipDir is used as a return value from WalkFuncs to indicate that
|
||||
// the directory named in the call is to be skipped. It is not returned
|
||||
// as an error by any function.
|
||||
var errSkipDir = errors.New("skip this directory")
|
||||
|
||||
// ErrSkipFile is used as a return value from WalkFuncs to indicate that
|
||||
// the file named in the call is to be skipped. It is not returned
|
||||
// as an error by any function.
|
||||
var errSkipFile = errors.New("skip this file")
|
||||
|
||||
// walkInternal recursively descends path, calling w.
|
||||
func walkInternal(path string, info os.FileInfo, walkFn walkFunc) error {
|
||||
e := walkFn(path, info, nil)
|
||||
if e != nil {
|
||||
if info.Mode().IsDir() && e == errSkipDir {
|
||||
return nil
|
||||
}
|
||||
if info.Mode().IsRegular() && e == errSkipFile {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
names, e := readDirNames(path)
|
||||
if e != nil {
|
||||
return walkFn(path, info, e)
|
||||
}
|
||||
for _, name := range names {
|
||||
filename := filepath.Join(path, name)
|
||||
fileInfo, e := os.Lstat(filename)
|
||||
if e != nil {
|
||||
if e = walkFn(filename, fileInfo, e); e != nil && e != errSkipDir && e != errSkipFile {
|
||||
return e
|
||||
}
|
||||
} else {
|
||||
e = walkInternal(filename, fileInfo, walkFn)
|
||||
if e != nil {
|
||||
if e == errSkipDir || e == errSkipFile {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
/*
|
||||
* Minio Client (C) 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// URL client url structure
|
||||
type URL struct {
|
||||
Type URLType
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
SchemeSeparator string
|
||||
Separator rune
|
||||
}
|
||||
|
||||
// URLType - enum of different url types
|
||||
type URLType int
|
||||
|
||||
// enum types
|
||||
const (
|
||||
Object = iota // Minio and S3 compatible cloud storage
|
||||
Filesystem // POSIX compatible file systems
|
||||
)
|
||||
|
||||
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
|
||||
// If so, return scheme, path; else return "", rawurl.
|
||||
func getScheme(rawurl string) (scheme, path string) {
|
||||
urlSplits := strings.Split(rawurl, "://")
|
||||
if len(urlSplits) == 2 {
|
||||
scheme, uri := urlSplits[0], "//"+urlSplits[1]
|
||||
// ignore numbers in scheme
|
||||
validScheme := regexp.MustCompile("^[a-zA-Z]+$")
|
||||
if uri != "" {
|
||||
if validScheme.MatchString(scheme) {
|
||||
return scheme, uri
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", rawurl
|
||||
}
|
||||
|
||||
// Assuming s is of the form [s delimiter s].
|
||||
// If so, return s, [delimiter]s or return s, s if cutdelimiter == true
|
||||
// If no delimiter found return s, "".
|
||||
func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) {
|
||||
i := strings.Index(s, delimiter)
|
||||
if i < 0 {
|
||||
// if delimiter not found return as is.
|
||||
return s, ""
|
||||
}
|
||||
// if delimiter should be removed, remove it.
|
||||
if cutdelimiter {
|
||||
return s[0:i], s[i+len(delimiter):]
|
||||
}
|
||||
// return split strings with delimiter
|
||||
return s[0:i], s[i:]
|
||||
}
|
||||
|
||||
// getHost - extract host from authority string, we do not support ftp style username@ yet.
|
||||
func getHost(authority string) (host string) {
|
||||
i := strings.LastIndex(authority, "@")
|
||||
if i >= 0 {
|
||||
// TODO support, username@password style userinfo, useful for ftp support.
|
||||
return
|
||||
}
|
||||
return authority
|
||||
}
|
||||
|
||||
// NewURL returns an abstracted URL for filesystems and object storage.
|
||||
func NewURL(urlStr string) *URL {
|
||||
scheme, rest := getScheme(urlStr)
|
||||
rest, _ = splitSpecial(rest, "?", true)
|
||||
if strings.HasPrefix(rest, "//") {
|
||||
// if rest has '//' prefix, skip them
|
||||
var authority string
|
||||
authority, rest = splitSpecial(rest[2:], "/", false)
|
||||
if rest == "" {
|
||||
rest = "/"
|
||||
}
|
||||
host := getHost(authority)
|
||||
if host != "" && (scheme == "http" || scheme == "https") {
|
||||
return &URL{
|
||||
Scheme: scheme,
|
||||
Type: Object,
|
||||
Host: host,
|
||||
Path: rest,
|
||||
SchemeSeparator: "://",
|
||||
Separator: '/',
|
||||
}
|
||||
}
|
||||
}
|
||||
return &URL{
|
||||
Type: Filesystem,
|
||||
Path: rest,
|
||||
Separator: filepath.Separator,
|
||||
}
|
||||
}
|
||||
|
||||
// JoinURLs join two input urls and returns a url
|
||||
func JoinURLs(url1, url2 *URL) *URL {
|
||||
var url1Path, url2Path string
|
||||
url1Path = filepath.ToSlash(url1.Path)
|
||||
url2Path = filepath.ToSlash(url2.Path)
|
||||
if strings.HasSuffix(url1Path, "/") {
|
||||
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
|
||||
} else {
|
||||
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
|
||||
}
|
||||
return url1
|
||||
}
|
||||
|
||||
// String convert URL into its canonical form.
|
||||
func (u URL) String() string {
|
||||
var buf bytes.Buffer
|
||||
// if fileystem no translation needed, return as is.
|
||||
if u.Type == Filesystem {
|
||||
return u.Path
|
||||
}
|
||||
// if Object convert from any non standard paths to a supported URL path style.
|
||||
if u.Type == Object {
|
||||
buf.WriteString(u.Scheme)
|
||||
buf.WriteByte(':')
|
||||
buf.WriteString("//")
|
||||
if h := u.Host; h != "" {
|
||||
buf.WriteString(h)
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' {
|
||||
buf.WriteByte('/')
|
||||
}
|
||||
buf.WriteString(strings.Replace(u.Path, "\\", "/", -1))
|
||||
default:
|
||||
if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
|
||||
buf.WriteByte('/')
|
||||
}
|
||||
buf.WriteString(u.Path)
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
@@ -24,8 +24,8 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/mattn/go-colorable"
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/shiena/ansicolor"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -37,7 +37,7 @@ var (
|
||||
// Used internally by console.
|
||||
privateMutex = &sync.Mutex{}
|
||||
|
||||
stderrColoredOutput = ansicolor.NewAnsiColorWriter(os.Stderr)
|
||||
stderrColoredOutput = colorable.NewColorableStderr()
|
||||
|
||||
// Print prints a message.
|
||||
Print = func(data ...interface{}) {
|
||||
|
||||
@@ -36,6 +36,14 @@ type RoundTripTrace struct {
|
||||
Transport http.RoundTripper // HTTP transport that needs to be intercepted
|
||||
}
|
||||
|
||||
// CancelRequest implements functinality to cancel an underlying request.
|
||||
func (t RoundTripTrace) CancelRequest(req *http.Request) {
|
||||
transport, ok := t.Transport.(*http.Transport)
|
||||
if ok {
|
||||
transport.CancelRequest(req)
|
||||
}
|
||||
}
|
||||
|
||||
// RoundTrip executes user provided request and response hooks for each HTTP call.
|
||||
func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) {
|
||||
timeStamp := time.Now()
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
SET MC_RELEASE=OFFICIAL
|
||||
SET GO15VENDOREXPERIMENT=1
|
||||
go run buildscripts/gen-ldflags.go > temp.txt
|
||||
SET /p LDFLAGS=<temp.txt
|
||||
go build -ldflags="%LDFLAGS%" -o %GOPATH%\bin\mc.exe
|
||||
@@ -1,6 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo -n "Making official release binaries.. "
|
||||
export MC_RELEASE=OFFICIAL
|
||||
make 1>/dev/null
|
||||
echo "Binaries built at ${GOPATH}/bin/mc"
|
||||
+4
-3
@@ -25,7 +25,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// rm specific flags.
|
||||
@@ -113,6 +113,7 @@ func checkRmSyntax(ctx *cli.Context) {
|
||||
// Set command flags from context.
|
||||
isForce := ctx.Bool("force")
|
||||
isRecursive := ctx.Bool("recursive")
|
||||
isFake := ctx.Bool("fake")
|
||||
|
||||
if !ctx.Args().Present() {
|
||||
exitCode := 1
|
||||
@@ -120,7 +121,7 @@ func checkRmSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
// For all recursive operations make sure to check for 'force' flag.
|
||||
if isRecursive && !isForce {
|
||||
if isRecursive && !isForce && !isFake {
|
||||
fatalIf(errDummy().Trace(),
|
||||
"Recursive removal requires --force option. Please review carefully before performing this *DANGEROUS* operation.")
|
||||
}
|
||||
@@ -202,7 +203,7 @@ func mainRm(ctx *cli.Context) {
|
||||
// Support multiple targets.
|
||||
for _, url := range ctx.Args() {
|
||||
targetAlias, targetURL, _ := mustExpandAlias(url)
|
||||
if isRecursive && isForce {
|
||||
if isRecursive && isForce || isFake {
|
||||
rmAll(targetAlias, targetURL, isRecursive, isIncomplete, isFake)
|
||||
} else {
|
||||
if err := rm(targetAlias, targetURL, isIncomplete, isFake); err != nil {
|
||||
|
||||
+6
-8
@@ -22,8 +22,8 @@ import (
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/olekukonko/ts"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/pb"
|
||||
)
|
||||
|
||||
/******************************** Scan Bar ************************************/
|
||||
@@ -47,13 +47,11 @@ func scanBarFactory() scanBarFunc {
|
||||
prevLineSize := 0
|
||||
prevSource := ""
|
||||
fileCount := 0
|
||||
termSize, e := ts.GetSize()
|
||||
if e != nil {
|
||||
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
|
||||
}
|
||||
termWidth := termSize.Col()
|
||||
cursorCh := cursorAnimate()
|
||||
termWidth, e := pb.GetTerminalWidth()
|
||||
fatalIf(probe.NewError(e), "Unable to get terminal size. Please use --quiet option.")
|
||||
|
||||
// Cursor animate channel.
|
||||
cursorCh := cursorAnimate()
|
||||
return func(source string) {
|
||||
scanPrefix := fmt.Sprintf("[%s] %s ", humanize.Comma(int64(fileCount)), string(<-cursorCh))
|
||||
cmnPrefix := commonPrefix(source, prevSource)
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
+8
-2
@@ -28,8 +28,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
func migrateSessionV5ToV6() {
|
||||
@@ -300,20 +300,26 @@ func (s *sessionV6) Delete() *probe.Error {
|
||||
// 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
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// migrateSession migrates all previous migration to latest.
|
||||
|
||||
+2
-2
@@ -21,8 +21,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio-xl/pkg/quick"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
// shareEntryV1 - container for each download/upload entries.
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import (
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -22,8 +22,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -101,7 +100,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
|
||||
}
|
||||
|
||||
for _, targetURL := range ctx.Args() {
|
||||
url := client.NewURL(targetURL)
|
||||
url := newURL(targetURL)
|
||||
if strings.HasSuffix(targetURL, string(url.Separator)) && !isRecursive {
|
||||
fatalIf(errInvalidArgument().Trace(targetURL),
|
||||
"Use --recursive option to generate curl command for prefixes.")
|
||||
@@ -111,7 +110,7 @@ func checkShareUploadSyntax(ctx *cli.Context) {
|
||||
|
||||
// makeCurlCmd constructs curl command-line.
|
||||
func makeCurlCmd(key string, isRecursive bool, uploadInfo map[string]string) string {
|
||||
URL := client.NewURL(key)
|
||||
URL := newURL(key)
|
||||
postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator)
|
||||
if !isBucketVirtualStyle(URL.Host) {
|
||||
postURL = postURL + uploadInfo["bucket"]
|
||||
|
||||
@@ -28,7 +28,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
|
||||
|
||||
# Testing mc cat
|
||||
# 1. Pass a variable as stdin
|
||||
# 2. Assert result returned by mc cat is the same
|
||||
# 3. Repeat the same for mc pipe with no arguments
|
||||
# 4. Take a random string to test for non existant files
|
||||
|
||||
dummy_string="asdasd"
|
||||
|
||||
cat_result=`mc cat <<< $dummy_string`
|
||||
if [ "$cat_result" == "$dummy_string" ]; then
|
||||
echo "mc cat STDIN Test Passed"
|
||||
else
|
||||
echo "mc cat STDIN Test Failed"
|
||||
fi
|
||||
|
||||
pipe_result=`mc pipe <<< $dummy_string`
|
||||
if [ "$pipe_result" == "$dummy_string" ]; then
|
||||
echo "mc pipe STDIN Test Passed"
|
||||
else
|
||||
echo "mc pipe STDIN Test Failed"
|
||||
fi
|
||||
|
||||
random_string="asd.jasd"
|
||||
|
||||
cat_json_result=`mc cat --json $random_string`
|
||||
if [[ "$cat_json_result" == *"\"status\":\"error\""* ]]
|
||||
then
|
||||
echo "mc cat Non-Existent File Test Passed"
|
||||
else
|
||||
echo "mc cat Non-Existent File Test Failed"
|
||||
fi
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
|
||||
|
||||
# Testing mc config hosts
|
||||
# 1. Get number of previous hosts
|
||||
# 2. Add a host
|
||||
# 3. Assert the increase in number of hosts by one.
|
||||
# 4. Delete the new host
|
||||
|
||||
|
||||
initial_count=`mc config host list | wc -l`
|
||||
add_test_result=`mc config --json host add testdisk https://storage.googleapis.com BKIKJAA5BMMU2RHO6IBB V8f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 S3v2`
|
||||
final_count=`mc config host list | wc -l`
|
||||
remove_test_result=`mc config host remove testdisk`
|
||||
|
||||
if [ "$add_test_result" == "Added ‘testdisk’ successfully." ]; then
|
||||
echo "mc config host add Test Passed";
|
||||
else
|
||||
echo "mc config host add Test Failed";
|
||||
fi
|
||||
|
||||
if [ $((initial_count + 1)) -ne $final_count ]; then
|
||||
echo "mc config host list Test Failed";
|
||||
else
|
||||
echo "mc config host list Test Passed";
|
||||
fi
|
||||
|
||||
if [ "$remove_test_result" == "Removed ‘testdisk’ successfully." ]; then
|
||||
echo "mc config host remove Test Passed";
|
||||
else
|
||||
echo "mc config host remove Test Failed";
|
||||
fi
|
||||
+1
-1
@@ -19,7 +19,7 @@ package main
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
+26
-12
@@ -28,7 +28,7 @@ import (
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// command specific flags.
|
||||
@@ -121,8 +121,9 @@ func parseReleaseData(data string) (time.Time, *probe.Error) {
|
||||
if releaseDateSplits[0] != "mc" {
|
||||
return time.Time{}, probe.NewError(errors.New("Update data malformed, missing mc tag"))
|
||||
}
|
||||
if releaseDateSplits[1] != "OFFICIAL" {
|
||||
return time.Time{}, probe.NewError(errors.New("Update data malformed, missing OFFICIAL tag"))
|
||||
// "OFFICIAL" tag is still kept for backward compatibility, we should remove this for the next release.
|
||||
if releaseDateSplits[1] != "RELEASE" && releaseDateSplits[1] != "OFFICIAL" {
|
||||
return time.Time{}, probe.NewError(errors.New("Update data malformed, missing RELEASE tag"))
|
||||
}
|
||||
dateSplits := strings.SplitN(releaseDateSplits[2], "T", 2)
|
||||
if len(dateSplits) < 2 {
|
||||
@@ -140,11 +141,30 @@ func parseReleaseData(data string) (time.Time, *probe.Error) {
|
||||
|
||||
// verify updates for releases.
|
||||
func getReleaseUpdate(updateURL string) {
|
||||
newUpdateURL := updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc.shasum"
|
||||
data, e := http.Get(newUpdateURL)
|
||||
// Construct a new update url.
|
||||
newUpdateURLPrefix := updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH
|
||||
newUpdateURL := newUpdateURLPrefix + "/mc.shasum"
|
||||
|
||||
// Instantiate a new client with 1 sec timeout.
|
||||
client := &http.Client{
|
||||
Timeout: 500 * time.Millisecond,
|
||||
}
|
||||
|
||||
// Get the downloadURL.
|
||||
var downloadURL string
|
||||
switch runtime.GOOS {
|
||||
case "windows", "darwin":
|
||||
// For windows and darwin.
|
||||
downloadURL = newUpdateURLPrefix + "/mc.zip"
|
||||
default:
|
||||
// For all other operating systems.
|
||||
downloadURL = newUpdateURLPrefix + "/mc.tar.gz"
|
||||
}
|
||||
|
||||
data, e := client.Get(newUpdateURL)
|
||||
fatalIf(probe.NewError(e), "Unable to read from update URL ‘"+newUpdateURL+"’.")
|
||||
|
||||
if mcVersion == "UNOFFICIAL.GOGET" {
|
||||
if strings.HasPrefix(mcVersion, "DEVELOPMENT.GOGET") {
|
||||
fatalIf(errDummy().Trace(newUpdateURL),
|
||||
"Update mechanism is not supported for ‘go get’ based binary builds. Please download official releases from https://minio.io/#minio")
|
||||
}
|
||||
@@ -168,12 +188,6 @@ func getReleaseUpdate(updateURL string) {
|
||||
"Unable to validate any update available at this time. Please open an issue at https://github.com/minio/mc/issues")
|
||||
}
|
||||
|
||||
var downloadURL string
|
||||
if runtime.GOOS == "windows" {
|
||||
downloadURL = updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc.exe"
|
||||
} else {
|
||||
downloadURL = updateURL + "/" + runtime.GOOS + "-" + runtime.GOARCH + "/mc"
|
||||
}
|
||||
updateMsg := updateMessage{
|
||||
Download: downloadURL,
|
||||
Version: mcVersion,
|
||||
|
||||
@@ -17,14 +17,153 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"mime"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-xl/pkg/probe"
|
||||
"github.com/minio/minio/pkg/contentdb"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// url client url structure
|
||||
type clientURL struct {
|
||||
Type clientURLType
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
SchemeSeparator string
|
||||
Separator rune
|
||||
}
|
||||
|
||||
// clientURLType - enum of different url types
|
||||
type clientURLType int
|
||||
|
||||
// enum types
|
||||
const (
|
||||
objectStorage = iota // Minio and S3 compatible cloud storage
|
||||
fileSystem // POSIX compatible file systems
|
||||
)
|
||||
|
||||
// Maybe rawurl is of the form scheme:path. (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
|
||||
// If so, return scheme, path; else return "", rawurl.
|
||||
func getScheme(rawurl string) (scheme, path string) {
|
||||
urlSplits := strings.Split(rawurl, "://")
|
||||
if len(urlSplits) == 2 {
|
||||
scheme, uri := urlSplits[0], "//"+urlSplits[1]
|
||||
// ignore numbers in scheme
|
||||
validScheme := regexp.MustCompile("^[a-zA-Z]+$")
|
||||
if uri != "" {
|
||||
if validScheme.MatchString(scheme) {
|
||||
return scheme, uri
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", rawurl
|
||||
}
|
||||
|
||||
// Assuming s is of the form [s delimiter s].
|
||||
// If so, return s, [delimiter]s or return s, s if cutdelimiter == true
|
||||
// If no delimiter found return s, "".
|
||||
func splitSpecial(s string, delimiter string, cutdelimiter bool) (string, string) {
|
||||
i := strings.Index(s, delimiter)
|
||||
if i < 0 {
|
||||
// if delimiter not found return as is.
|
||||
return s, ""
|
||||
}
|
||||
// if delimiter should be removed, remove it.
|
||||
if cutdelimiter {
|
||||
return s[0:i], s[i+len(delimiter):]
|
||||
}
|
||||
// return split strings with delimiter
|
||||
return s[0:i], s[i:]
|
||||
}
|
||||
|
||||
// getHost - extract host from authority string, we do not support ftp style username@ yet.
|
||||
func getHost(authority string) (host string) {
|
||||
i := strings.LastIndex(authority, "@")
|
||||
if i >= 0 {
|
||||
// TODO support, username@password style userinfo, useful for ftp support.
|
||||
return
|
||||
}
|
||||
return authority
|
||||
}
|
||||
|
||||
// newURL returns an abstracted URL for filesystems and object storage.
|
||||
func newURL(urlStr string) *clientURL {
|
||||
scheme, rest := getScheme(urlStr)
|
||||
rest, _ = splitSpecial(rest, "?", true)
|
||||
if strings.HasPrefix(rest, "//") {
|
||||
// if rest has '//' prefix, skip them
|
||||
var authority string
|
||||
authority, rest = splitSpecial(rest[2:], "/", false)
|
||||
if rest == "" {
|
||||
rest = "/"
|
||||
}
|
||||
host := getHost(authority)
|
||||
if host != "" && (scheme == "http" || scheme == "https") {
|
||||
return &clientURL{
|
||||
Scheme: scheme,
|
||||
Type: objectStorage,
|
||||
Host: host,
|
||||
Path: rest,
|
||||
SchemeSeparator: "://",
|
||||
Separator: '/',
|
||||
}
|
||||
}
|
||||
}
|
||||
return &clientURL{
|
||||
Type: fileSystem,
|
||||
Path: rest,
|
||||
Separator: filepath.Separator,
|
||||
}
|
||||
}
|
||||
|
||||
// joinURLs join two input urls and returns a url
|
||||
func joinURLs(url1, url2 *clientURL) *clientURL {
|
||||
var url1Path, url2Path string
|
||||
url1Path = filepath.ToSlash(url1.Path)
|
||||
url2Path = filepath.ToSlash(url2.Path)
|
||||
if strings.HasSuffix(url1Path, "/") {
|
||||
url1.Path = url1Path + strings.TrimPrefix(url2Path, "/")
|
||||
} else {
|
||||
url1.Path = url1Path + "/" + strings.TrimPrefix(url2Path, "/")
|
||||
}
|
||||
return url1
|
||||
}
|
||||
|
||||
// String convert URL into its canonical form.
|
||||
func (u clientURL) String() string {
|
||||
var buf bytes.Buffer
|
||||
// if fileSystem no translation needed, return as is.
|
||||
if u.Type == fileSystem {
|
||||
return u.Path
|
||||
}
|
||||
// if objectStorage convert from any non standard paths to a supported URL path style.
|
||||
if u.Type == objectStorage {
|
||||
buf.WriteString(u.Scheme)
|
||||
buf.WriteByte(':')
|
||||
buf.WriteString("//")
|
||||
if h := u.Host; h != "" {
|
||||
buf.WriteString(h)
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if u.Path != "" && u.Path[0] != '\\' && u.Host != "" && u.Path[0] != '/' {
|
||||
buf.WriteByte('/')
|
||||
}
|
||||
buf.WriteString(strings.Replace(u.Path, "\\", "/", -1))
|
||||
default:
|
||||
if u.Path != "" && u.Path[0] != '/' && u.Host != "" {
|
||||
buf.WriteByte('/')
|
||||
}
|
||||
buf.WriteString(u.Path)
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func isURLVirtualHostStyle(hostURL string) bool {
|
||||
matchS3, _ := filepath.Match("*.s3*.amazonaws.com", hostURL)
|
||||
matchGoogle, _ := filepath.Match("*.storage.googleapis.com", hostURL)
|
||||
@@ -33,13 +172,13 @@ func isURLVirtualHostStyle(hostURL string) bool {
|
||||
|
||||
// urlJoinPath Join a path to existing URL.
|
||||
func urlJoinPath(url1, url2 string) string {
|
||||
u1 := client.NewURL(url1)
|
||||
u2 := client.NewURL(url2)
|
||||
return client.JoinURLs(u1, u2).String()
|
||||
u1 := newURL(url1)
|
||||
u2 := newURL(url2)
|
||||
return joinURLs(u1, u2).String()
|
||||
}
|
||||
|
||||
// url2Stat returns stat info for URL.
|
||||
func url2Stat(urlStr string) (client client.Client, content *client.Content, err *probe.Error) {
|
||||
func url2Stat(urlStr string) (client Client, content *clientContent, err *probe.Error) {
|
||||
client, err = newClient(urlStr)
|
||||
if err != nil {
|
||||
return nil, nil, err.Trace(urlStr)
|
||||
@@ -92,11 +231,10 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
|
||||
// guessURLContentType - guess content-type of the URL.
|
||||
// on failure just return 'application/octet-stream'.
|
||||
func guessURLContentType(urlStr string) string {
|
||||
url := client.NewURL(urlStr)
|
||||
extension := strings.TrimPrefix(filepath.Ext(url.Path), ".")
|
||||
contentType, e := contentdb.Lookup(extension)
|
||||
if e != nil {
|
||||
return "application/octet-stream"
|
||||
url := newURL(urlStr)
|
||||
contentType := mime.TypeByExtension(filepath.Ext(url.Path))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
return contentType
|
||||
}
|
||||
|
||||
+1
-1
@@ -143,7 +143,7 @@ c.Println("This prints again cyan...")
|
||||
## Credits
|
||||
|
||||
* [Fatih Arslan](https://github.com/fatih)
|
||||
* Windows support via @shiena: [ansicolor](https://github.com/shiena/ansicolor)
|
||||
* Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable)
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+51
-2
@@ -6,8 +6,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/mattn/go-colorable"
|
||||
"github.com/mattn/go-isatty"
|
||||
"github.com/shiena/ansicolor"
|
||||
)
|
||||
|
||||
// NoColor defines if the output is colorized or not. It's dynamically set to
|
||||
@@ -53,6 +53,18 @@ const (
|
||||
FgWhite
|
||||
)
|
||||
|
||||
// Foreground Hi-Intensity text colors
|
||||
const (
|
||||
FgHiBlack Attribute = iota + 90
|
||||
FgHiRed
|
||||
FgHiGreen
|
||||
FgHiYellow
|
||||
FgHiBlue
|
||||
FgHiMagenta
|
||||
FgHiCyan
|
||||
FgHiWhite
|
||||
)
|
||||
|
||||
// Background text colors
|
||||
const (
|
||||
BgBlack Attribute = iota + 40
|
||||
@@ -65,6 +77,18 @@ const (
|
||||
BgWhite
|
||||
)
|
||||
|
||||
// Background Hi-Intensity text colors
|
||||
const (
|
||||
BgHiBlack Attribute = iota + 100
|
||||
BgHiRed
|
||||
BgHiGreen
|
||||
BgHiYellow
|
||||
BgHiBlue
|
||||
BgHiMagenta
|
||||
BgHiCyan
|
||||
BgHiWhite
|
||||
)
|
||||
|
||||
// New returns a newly created color object.
|
||||
func New(value ...Attribute) *Color {
|
||||
c := &Color{params: make([]Attribute, 0)}
|
||||
@@ -123,7 +147,7 @@ func (c *Color) prepend(value Attribute) {
|
||||
|
||||
// Output defines the standard output of the print functions. By default
|
||||
// os.Stdout is used.
|
||||
var Output = ansicolor.NewAnsiColorWriter(os.Stdout)
|
||||
var Output = colorable.NewColorableStdout()
|
||||
|
||||
// Print formats using the default formats for its operands and writes to
|
||||
// standard output. Spaces are added between operands when neither is a
|
||||
@@ -259,6 +283,31 @@ func (c *Color) isNoColorSet() bool {
|
||||
return NoColor
|
||||
}
|
||||
|
||||
// Equals returns a boolean value indicating whether two colors are equal.
|
||||
func (c *Color) Equals(c2 *Color) bool {
|
||||
if len(c.params) != len(c2.params) {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, attr := range c.params {
|
||||
if !c2.attrExists(attr) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Color) attrExists(a Attribute) bool {
|
||||
for _, attr := range c.params {
|
||||
if attr == a {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func boolPtr(v bool) *bool {
|
||||
return &v
|
||||
}
|
||||
|
||||
+54
-4
@@ -3,10 +3,9 @@ package color
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/shiena/ansicolor"
|
||||
"github.com/mattn/go-colorable"
|
||||
)
|
||||
|
||||
// Testing colors is kinda different. First we test for given colors and their
|
||||
@@ -16,6 +15,8 @@ func TestColor(t *testing.T) {
|
||||
rb := new(bytes.Buffer)
|
||||
Output = rb
|
||||
|
||||
NoColor = false
|
||||
|
||||
testColors := []struct {
|
||||
text string
|
||||
code Attribute
|
||||
@@ -28,6 +29,14 @@ func TestColor(t *testing.T) {
|
||||
{text: "magent", code: FgMagenta},
|
||||
{text: "cyan", code: FgCyan},
|
||||
{text: "white", code: FgWhite},
|
||||
{text: "hblack", code: FgHiBlack},
|
||||
{text: "hred", code: FgHiRed},
|
||||
{text: "hgreen", code: FgHiGreen},
|
||||
{text: "hyellow", code: FgHiYellow},
|
||||
{text: "hblue", code: FgHiBlue},
|
||||
{text: "hmagent", code: FgHiMagenta},
|
||||
{text: "hcyan", code: FgHiCyan},
|
||||
{text: "hwhite", code: FgHiWhite},
|
||||
}
|
||||
|
||||
for _, c := range testColors {
|
||||
@@ -46,6 +55,40 @@ func TestColor(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestColorEquals(t *testing.T) {
|
||||
fgblack1 := New(FgBlack)
|
||||
fgblack2 := New(FgBlack)
|
||||
bgblack := New(BgBlack)
|
||||
fgbgblack := New(FgBlack, BgBlack)
|
||||
fgblackbgred := New(FgBlack, BgRed)
|
||||
fgred := New(FgRed)
|
||||
bgred := New(BgRed)
|
||||
|
||||
if !fgblack1.Equals(fgblack2) {
|
||||
t.Error("Two black colors are not equal")
|
||||
}
|
||||
|
||||
if fgblack1.Equals(bgblack) {
|
||||
t.Error("Fg and bg black colors are equal")
|
||||
}
|
||||
|
||||
if fgblack1.Equals(fgbgblack) {
|
||||
t.Error("Fg black equals fg/bg black color")
|
||||
}
|
||||
|
||||
if fgblack1.Equals(fgred) {
|
||||
t.Error("Fg black equals Fg red")
|
||||
}
|
||||
|
||||
if fgblack1.Equals(bgred) {
|
||||
t.Error("Fg black equals Bg red")
|
||||
}
|
||||
|
||||
if fgblack1.Equals(fgblackbgred) {
|
||||
t.Error("Fg black equals fg black bg red")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoColor(t *testing.T) {
|
||||
rb := new(bytes.Buffer)
|
||||
Output = rb
|
||||
@@ -62,6 +105,14 @@ func TestNoColor(t *testing.T) {
|
||||
{text: "magent", code: FgMagenta},
|
||||
{text: "cyan", code: FgCyan},
|
||||
{text: "white", code: FgWhite},
|
||||
{text: "hblack", code: FgHiBlack},
|
||||
{text: "hred", code: FgHiRed},
|
||||
{text: "hgreen", code: FgHiGreen},
|
||||
{text: "hyellow", code: FgHiYellow},
|
||||
{text: "hblue", code: FgHiBlue},
|
||||
{text: "hmagent", code: FgHiMagenta},
|
||||
{text: "hcyan", code: FgHiCyan},
|
||||
{text: "hwhite", code: FgHiWhite},
|
||||
}
|
||||
|
||||
for _, c := range testColors {
|
||||
@@ -94,8 +145,7 @@ func TestNoColor(t *testing.T) {
|
||||
|
||||
func TestColorVisual(t *testing.T) {
|
||||
// First Visual Test
|
||||
fmt.Println("")
|
||||
Output = ansicolor.NewAnsiColorWriter(os.Stdout)
|
||||
Output = colorable.NewColorableStdout()
|
||||
|
||||
New(FgRed).Printf("red\t")
|
||||
New(BgRed).Print(" ")
|
||||
|
||||
Generated
Vendored
+1
-1
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) [2014] [shiena]
|
||||
Copyright (c) 2016 Yasuhiro Matsumoto
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# go-colorable
|
||||
|
||||
Colorable writer for windows.
|
||||
|
||||
For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.)
|
||||
This package is possible to handle escape sequence for ansi color on windows.
|
||||
|
||||
## Too Bad!
|
||||
|
||||

|
||||
|
||||
|
||||
## So Good!
|
||||
|
||||

|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true})
|
||||
logrus.SetOutput(colorable.NewColorableStdout())
|
||||
|
||||
logrus.Info("succeeded")
|
||||
logrus.Warn("not correct")
|
||||
logrus.Error("something error")
|
||||
logrus.Fatal("panic")
|
||||
```
|
||||
|
||||
You can compile above code on non-windows OSs.
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
$ go get github.com/mattn/go-colorable
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
MIT
|
||||
|
||||
# Author
|
||||
|
||||
Yasuhiro Matsumoto (a.k.a mattn)
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// +build !windows
|
||||
|
||||
package colorable
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func NewColorableStdout() io.Writer {
|
||||
return os.Stdout
|
||||
}
|
||||
|
||||
func NewColorableStderr() io.Writer {
|
||||
return os.Stderr
|
||||
}
|
||||
+782
@@ -0,0 +1,782 @@
|
||||
package colorable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/mattn/go-isatty"
|
||||
)
|
||||
|
||||
const (
|
||||
foregroundBlue = 0x1
|
||||
foregroundGreen = 0x2
|
||||
foregroundRed = 0x4
|
||||
foregroundIntensity = 0x8
|
||||
foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity)
|
||||
backgroundBlue = 0x10
|
||||
backgroundGreen = 0x20
|
||||
backgroundRed = 0x40
|
||||
backgroundIntensity = 0x80
|
||||
backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity)
|
||||
)
|
||||
|
||||
type wchar uint16
|
||||
type short int16
|
||||
type dword uint32
|
||||
type word uint16
|
||||
|
||||
type coord struct {
|
||||
x short
|
||||
y short
|
||||
}
|
||||
|
||||
type smallRect struct {
|
||||
left short
|
||||
top short
|
||||
right short
|
||||
bottom short
|
||||
}
|
||||
|
||||
type consoleScreenBufferInfo struct {
|
||||
size coord
|
||||
cursorPosition coord
|
||||
attributes word
|
||||
window smallRect
|
||||
maximumWindowSize coord
|
||||
}
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
|
||||
procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute")
|
||||
procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition")
|
||||
procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW")
|
||||
procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute")
|
||||
)
|
||||
|
||||
type Writer struct {
|
||||
out io.Writer
|
||||
handle syscall.Handle
|
||||
lastbuf bytes.Buffer
|
||||
oldattr word
|
||||
}
|
||||
|
||||
func NewColorableStdout() io.Writer {
|
||||
var csbi consoleScreenBufferInfo
|
||||
out := os.Stdout
|
||||
if !isatty.IsTerminal(out.Fd()) {
|
||||
return out
|
||||
}
|
||||
handle := syscall.Handle(out.Fd())
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
return &Writer{out: out, handle: handle, oldattr: csbi.attributes}
|
||||
}
|
||||
|
||||
func NewColorableStderr() io.Writer {
|
||||
var csbi consoleScreenBufferInfo
|
||||
out := os.Stderr
|
||||
if !isatty.IsTerminal(out.Fd()) {
|
||||
return out
|
||||
}
|
||||
handle := syscall.Handle(out.Fd())
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
return &Writer{out: out, handle: handle, oldattr: csbi.attributes}
|
||||
}
|
||||
|
||||
var color256 = map[int]int{
|
||||
0: 0x000000,
|
||||
1: 0x800000,
|
||||
2: 0x008000,
|
||||
3: 0x808000,
|
||||
4: 0x000080,
|
||||
5: 0x800080,
|
||||
6: 0x008080,
|
||||
7: 0xc0c0c0,
|
||||
8: 0x808080,
|
||||
9: 0xff0000,
|
||||
10: 0x00ff00,
|
||||
11: 0xffff00,
|
||||
12: 0x0000ff,
|
||||
13: 0xff00ff,
|
||||
14: 0x00ffff,
|
||||
15: 0xffffff,
|
||||
16: 0x000000,
|
||||
17: 0x00005f,
|
||||
18: 0x000087,
|
||||
19: 0x0000af,
|
||||
20: 0x0000d7,
|
||||
21: 0x0000ff,
|
||||
22: 0x005f00,
|
||||
23: 0x005f5f,
|
||||
24: 0x005f87,
|
||||
25: 0x005faf,
|
||||
26: 0x005fd7,
|
||||
27: 0x005fff,
|
||||
28: 0x008700,
|
||||
29: 0x00875f,
|
||||
30: 0x008787,
|
||||
31: 0x0087af,
|
||||
32: 0x0087d7,
|
||||
33: 0x0087ff,
|
||||
34: 0x00af00,
|
||||
35: 0x00af5f,
|
||||
36: 0x00af87,
|
||||
37: 0x00afaf,
|
||||
38: 0x00afd7,
|
||||
39: 0x00afff,
|
||||
40: 0x00d700,
|
||||
41: 0x00d75f,
|
||||
42: 0x00d787,
|
||||
43: 0x00d7af,
|
||||
44: 0x00d7d7,
|
||||
45: 0x00d7ff,
|
||||
46: 0x00ff00,
|
||||
47: 0x00ff5f,
|
||||
48: 0x00ff87,
|
||||
49: 0x00ffaf,
|
||||
50: 0x00ffd7,
|
||||
51: 0x00ffff,
|
||||
52: 0x5f0000,
|
||||
53: 0x5f005f,
|
||||
54: 0x5f0087,
|
||||
55: 0x5f00af,
|
||||
56: 0x5f00d7,
|
||||
57: 0x5f00ff,
|
||||
58: 0x5f5f00,
|
||||
59: 0x5f5f5f,
|
||||
60: 0x5f5f87,
|
||||
61: 0x5f5faf,
|
||||
62: 0x5f5fd7,
|
||||
63: 0x5f5fff,
|
||||
64: 0x5f8700,
|
||||
65: 0x5f875f,
|
||||
66: 0x5f8787,
|
||||
67: 0x5f87af,
|
||||
68: 0x5f87d7,
|
||||
69: 0x5f87ff,
|
||||
70: 0x5faf00,
|
||||
71: 0x5faf5f,
|
||||
72: 0x5faf87,
|
||||
73: 0x5fafaf,
|
||||
74: 0x5fafd7,
|
||||
75: 0x5fafff,
|
||||
76: 0x5fd700,
|
||||
77: 0x5fd75f,
|
||||
78: 0x5fd787,
|
||||
79: 0x5fd7af,
|
||||
80: 0x5fd7d7,
|
||||
81: 0x5fd7ff,
|
||||
82: 0x5fff00,
|
||||
83: 0x5fff5f,
|
||||
84: 0x5fff87,
|
||||
85: 0x5fffaf,
|
||||
86: 0x5fffd7,
|
||||
87: 0x5fffff,
|
||||
88: 0x870000,
|
||||
89: 0x87005f,
|
||||
90: 0x870087,
|
||||
91: 0x8700af,
|
||||
92: 0x8700d7,
|
||||
93: 0x8700ff,
|
||||
94: 0x875f00,
|
||||
95: 0x875f5f,
|
||||
96: 0x875f87,
|
||||
97: 0x875faf,
|
||||
98: 0x875fd7,
|
||||
99: 0x875fff,
|
||||
100: 0x878700,
|
||||
101: 0x87875f,
|
||||
102: 0x878787,
|
||||
103: 0x8787af,
|
||||
104: 0x8787d7,
|
||||
105: 0x8787ff,
|
||||
106: 0x87af00,
|
||||
107: 0x87af5f,
|
||||
108: 0x87af87,
|
||||
109: 0x87afaf,
|
||||
110: 0x87afd7,
|
||||
111: 0x87afff,
|
||||
112: 0x87d700,
|
||||
113: 0x87d75f,
|
||||
114: 0x87d787,
|
||||
115: 0x87d7af,
|
||||
116: 0x87d7d7,
|
||||
117: 0x87d7ff,
|
||||
118: 0x87ff00,
|
||||
119: 0x87ff5f,
|
||||
120: 0x87ff87,
|
||||
121: 0x87ffaf,
|
||||
122: 0x87ffd7,
|
||||
123: 0x87ffff,
|
||||
124: 0xaf0000,
|
||||
125: 0xaf005f,
|
||||
126: 0xaf0087,
|
||||
127: 0xaf00af,
|
||||
128: 0xaf00d7,
|
||||
129: 0xaf00ff,
|
||||
130: 0xaf5f00,
|
||||
131: 0xaf5f5f,
|
||||
132: 0xaf5f87,
|
||||
133: 0xaf5faf,
|
||||
134: 0xaf5fd7,
|
||||
135: 0xaf5fff,
|
||||
136: 0xaf8700,
|
||||
137: 0xaf875f,
|
||||
138: 0xaf8787,
|
||||
139: 0xaf87af,
|
||||
140: 0xaf87d7,
|
||||
141: 0xaf87ff,
|
||||
142: 0xafaf00,
|
||||
143: 0xafaf5f,
|
||||
144: 0xafaf87,
|
||||
145: 0xafafaf,
|
||||
146: 0xafafd7,
|
||||
147: 0xafafff,
|
||||
148: 0xafd700,
|
||||
149: 0xafd75f,
|
||||
150: 0xafd787,
|
||||
151: 0xafd7af,
|
||||
152: 0xafd7d7,
|
||||
153: 0xafd7ff,
|
||||
154: 0xafff00,
|
||||
155: 0xafff5f,
|
||||
156: 0xafff87,
|
||||
157: 0xafffaf,
|
||||
158: 0xafffd7,
|
||||
159: 0xafffff,
|
||||
160: 0xd70000,
|
||||
161: 0xd7005f,
|
||||
162: 0xd70087,
|
||||
163: 0xd700af,
|
||||
164: 0xd700d7,
|
||||
165: 0xd700ff,
|
||||
166: 0xd75f00,
|
||||
167: 0xd75f5f,
|
||||
168: 0xd75f87,
|
||||
169: 0xd75faf,
|
||||
170: 0xd75fd7,
|
||||
171: 0xd75fff,
|
||||
172: 0xd78700,
|
||||
173: 0xd7875f,
|
||||
174: 0xd78787,
|
||||
175: 0xd787af,
|
||||
176: 0xd787d7,
|
||||
177: 0xd787ff,
|
||||
178: 0xd7af00,
|
||||
179: 0xd7af5f,
|
||||
180: 0xd7af87,
|
||||
181: 0xd7afaf,
|
||||
182: 0xd7afd7,
|
||||
183: 0xd7afff,
|
||||
184: 0xd7d700,
|
||||
185: 0xd7d75f,
|
||||
186: 0xd7d787,
|
||||
187: 0xd7d7af,
|
||||
188: 0xd7d7d7,
|
||||
189: 0xd7d7ff,
|
||||
190: 0xd7ff00,
|
||||
191: 0xd7ff5f,
|
||||
192: 0xd7ff87,
|
||||
193: 0xd7ffaf,
|
||||
194: 0xd7ffd7,
|
||||
195: 0xd7ffff,
|
||||
196: 0xff0000,
|
||||
197: 0xff005f,
|
||||
198: 0xff0087,
|
||||
199: 0xff00af,
|
||||
200: 0xff00d7,
|
||||
201: 0xff00ff,
|
||||
202: 0xff5f00,
|
||||
203: 0xff5f5f,
|
||||
204: 0xff5f87,
|
||||
205: 0xff5faf,
|
||||
206: 0xff5fd7,
|
||||
207: 0xff5fff,
|
||||
208: 0xff8700,
|
||||
209: 0xff875f,
|
||||
210: 0xff8787,
|
||||
211: 0xff87af,
|
||||
212: 0xff87d7,
|
||||
213: 0xff87ff,
|
||||
214: 0xffaf00,
|
||||
215: 0xffaf5f,
|
||||
216: 0xffaf87,
|
||||
217: 0xffafaf,
|
||||
218: 0xffafd7,
|
||||
219: 0xffafff,
|
||||
220: 0xffd700,
|
||||
221: 0xffd75f,
|
||||
222: 0xffd787,
|
||||
223: 0xffd7af,
|
||||
224: 0xffd7d7,
|
||||
225: 0xffd7ff,
|
||||
226: 0xffff00,
|
||||
227: 0xffff5f,
|
||||
228: 0xffff87,
|
||||
229: 0xffffaf,
|
||||
230: 0xffffd7,
|
||||
231: 0xffffff,
|
||||
232: 0x080808,
|
||||
233: 0x121212,
|
||||
234: 0x1c1c1c,
|
||||
235: 0x262626,
|
||||
236: 0x303030,
|
||||
237: 0x3a3a3a,
|
||||
238: 0x444444,
|
||||
239: 0x4e4e4e,
|
||||
240: 0x585858,
|
||||
241: 0x626262,
|
||||
242: 0x6c6c6c,
|
||||
243: 0x767676,
|
||||
244: 0x808080,
|
||||
245: 0x8a8a8a,
|
||||
246: 0x949494,
|
||||
247: 0x9e9e9e,
|
||||
248: 0xa8a8a8,
|
||||
249: 0xb2b2b2,
|
||||
250: 0xbcbcbc,
|
||||
251: 0xc6c6c6,
|
||||
252: 0xd0d0d0,
|
||||
253: 0xdadada,
|
||||
254: 0xe4e4e4,
|
||||
255: 0xeeeeee,
|
||||
}
|
||||
|
||||
func (w *Writer) Write(data []byte) (n int, err error) {
|
||||
var csbi consoleScreenBufferInfo
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
|
||||
er := bytes.NewBuffer(data)
|
||||
loop:
|
||||
for {
|
||||
r1, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
if r1 == 0 {
|
||||
break loop
|
||||
}
|
||||
|
||||
c1, _, err := er.ReadRune()
|
||||
if err != nil {
|
||||
break loop
|
||||
}
|
||||
if c1 != 0x1b {
|
||||
fmt.Fprint(w.out, string(c1))
|
||||
continue
|
||||
}
|
||||
c2, _, err := er.ReadRune()
|
||||
if err != nil {
|
||||
w.lastbuf.WriteRune(c1)
|
||||
break loop
|
||||
}
|
||||
if c2 != 0x5b {
|
||||
w.lastbuf.WriteRune(c1)
|
||||
w.lastbuf.WriteRune(c2)
|
||||
continue
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
var m rune
|
||||
for {
|
||||
c, _, err := er.ReadRune()
|
||||
if err != nil {
|
||||
w.lastbuf.WriteRune(c1)
|
||||
w.lastbuf.WriteRune(c2)
|
||||
w.lastbuf.Write(buf.Bytes())
|
||||
break loop
|
||||
}
|
||||
if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' {
|
||||
m = c
|
||||
break
|
||||
}
|
||||
buf.Write([]byte(string(c)))
|
||||
}
|
||||
|
||||
var csbi consoleScreenBufferInfo
|
||||
switch m {
|
||||
case 'A':
|
||||
n, err = strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
csbi.cursorPosition.y -= short(n)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
case 'B':
|
||||
n, err = strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
csbi.cursorPosition.y += short(n)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
case 'C':
|
||||
n, err = strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
csbi.cursorPosition.x -= short(n)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
case 'D':
|
||||
n, err = strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if n, err = strconv.Atoi(buf.String()); err == nil {
|
||||
var csbi consoleScreenBufferInfo
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
csbi.cursorPosition.x += short(n)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
}
|
||||
case 'E':
|
||||
n, err = strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
csbi.cursorPosition.x = 0
|
||||
csbi.cursorPosition.y += short(n)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
case 'F':
|
||||
n, err = strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
csbi.cursorPosition.x = 0
|
||||
csbi.cursorPosition.y -= short(n)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
case 'G':
|
||||
n, err = strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi)))
|
||||
csbi.cursorPosition.x = short(n)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
case 'H':
|
||||
token := strings.Split(buf.String(), ";")
|
||||
if len(token) != 2 {
|
||||
continue
|
||||
}
|
||||
n1, err := strconv.Atoi(token[0])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
n2, err := strconv.Atoi(token[1])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
csbi.cursorPosition.x = short(n2)
|
||||
csbi.cursorPosition.x = short(n1)
|
||||
procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition)))
|
||||
case 'J':
|
||||
n, err := strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var cursor coord
|
||||
switch n {
|
||||
case 0:
|
||||
cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y}
|
||||
case 1:
|
||||
cursor = coord{x: csbi.window.left, y: csbi.window.top}
|
||||
case 2:
|
||||
cursor = coord{x: csbi.window.left, y: csbi.window.top}
|
||||
}
|
||||
var count, written dword
|
||||
count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x)
|
||||
procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
|
||||
procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
|
||||
case 'K':
|
||||
n, err := strconv.Atoi(buf.String())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var cursor coord
|
||||
switch n {
|
||||
case 0:
|
||||
cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y}
|
||||
case 1:
|
||||
cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y}
|
||||
case 2:
|
||||
cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y}
|
||||
}
|
||||
var count, written dword
|
||||
count = dword(csbi.size.x - csbi.cursorPosition.x)
|
||||
procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
|
||||
procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written)))
|
||||
case 'm':
|
||||
attr := csbi.attributes
|
||||
cs := buf.String()
|
||||
if cs == "" {
|
||||
procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr))
|
||||
continue
|
||||
}
|
||||
token := strings.Split(cs, ";")
|
||||
for i := 0; i < len(token); i += 1 {
|
||||
ns := token[i]
|
||||
if n, err = strconv.Atoi(ns); err == nil {
|
||||
switch {
|
||||
case n == 0 || n == 100:
|
||||
attr = w.oldattr
|
||||
case 1 <= n && n <= 5:
|
||||
attr |= foregroundIntensity
|
||||
case n == 7:
|
||||
attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4)
|
||||
case 22 == n || n == 25 || n == 25:
|
||||
attr |= foregroundIntensity
|
||||
case n == 27:
|
||||
attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4)
|
||||
case 30 <= n && n <= 37:
|
||||
attr = (attr & backgroundMask)
|
||||
if (n-30)&1 != 0 {
|
||||
attr |= foregroundRed
|
||||
}
|
||||
if (n-30)&2 != 0 {
|
||||
attr |= foregroundGreen
|
||||
}
|
||||
if (n-30)&4 != 0 {
|
||||
attr |= foregroundBlue
|
||||
}
|
||||
case n == 38: // set foreground color.
|
||||
if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") {
|
||||
if n256, err := strconv.Atoi(token[i+2]); err == nil {
|
||||
if n256foreAttr == nil {
|
||||
n256setup()
|
||||
}
|
||||
attr &= backgroundMask
|
||||
attr |= n256foreAttr[n256]
|
||||
i += 2
|
||||
}
|
||||
} else {
|
||||
attr = attr & (w.oldattr & backgroundMask)
|
||||
}
|
||||
case n == 39: // reset foreground color.
|
||||
attr &= backgroundMask
|
||||
attr |= w.oldattr & foregroundMask
|
||||
case 40 <= n && n <= 47:
|
||||
attr = (attr & foregroundMask)
|
||||
if (n-40)&1 != 0 {
|
||||
attr |= backgroundRed
|
||||
}
|
||||
if (n-40)&2 != 0 {
|
||||
attr |= backgroundGreen
|
||||
}
|
||||
if (n-40)&4 != 0 {
|
||||
attr |= backgroundBlue
|
||||
}
|
||||
case n == 48: // set background color.
|
||||
if i < len(token)-2 && token[i+1] == "5" {
|
||||
if n256, err := strconv.Atoi(token[i+2]); err == nil {
|
||||
if n256backAttr == nil {
|
||||
n256setup()
|
||||
}
|
||||
attr &= foregroundMask
|
||||
attr |= n256backAttr[n256]
|
||||
i += 2
|
||||
}
|
||||
} else {
|
||||
attr = attr & (w.oldattr & foregroundMask)
|
||||
}
|
||||
case n == 49: // reset foreground color.
|
||||
attr &= foregroundMask
|
||||
attr |= w.oldattr & backgroundMask
|
||||
case 90 <= n && n <= 97:
|
||||
attr = (attr & backgroundMask)
|
||||
attr |= foregroundIntensity
|
||||
if (n-90)&1 != 0 {
|
||||
attr |= foregroundRed
|
||||
}
|
||||
if (n-90)&2 != 0 {
|
||||
attr |= foregroundGreen
|
||||
}
|
||||
if (n-90)&4 != 0 {
|
||||
attr |= foregroundBlue
|
||||
}
|
||||
case 100 <= n && n <= 107:
|
||||
attr = (attr & foregroundMask)
|
||||
attr |= backgroundIntensity
|
||||
if (n-100)&1 != 0 {
|
||||
attr |= backgroundRed
|
||||
}
|
||||
if (n-100)&2 != 0 {
|
||||
attr |= backgroundGreen
|
||||
}
|
||||
if (n-100)&4 != 0 {
|
||||
attr |= backgroundBlue
|
||||
}
|
||||
}
|
||||
procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return len(data) - w.lastbuf.Len(), nil
|
||||
}
|
||||
|
||||
type consoleColor struct {
|
||||
rgb int
|
||||
red bool
|
||||
green bool
|
||||
blue bool
|
||||
intensity bool
|
||||
}
|
||||
|
||||
func (c consoleColor) foregroundAttr() (attr word) {
|
||||
if c.red {
|
||||
attr |= foregroundRed
|
||||
}
|
||||
if c.green {
|
||||
attr |= foregroundGreen
|
||||
}
|
||||
if c.blue {
|
||||
attr |= foregroundBlue
|
||||
}
|
||||
if c.intensity {
|
||||
attr |= foregroundIntensity
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c consoleColor) backgroundAttr() (attr word) {
|
||||
if c.red {
|
||||
attr |= backgroundRed
|
||||
}
|
||||
if c.green {
|
||||
attr |= backgroundGreen
|
||||
}
|
||||
if c.blue {
|
||||
attr |= backgroundBlue
|
||||
}
|
||||
if c.intensity {
|
||||
attr |= backgroundIntensity
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var color16 = []consoleColor{
|
||||
consoleColor{0x000000, false, false, false, false},
|
||||
consoleColor{0x000080, false, false, true, false},
|
||||
consoleColor{0x008000, false, true, false, false},
|
||||
consoleColor{0x008080, false, true, true, false},
|
||||
consoleColor{0x800000, true, false, false, false},
|
||||
consoleColor{0x800080, true, false, true, false},
|
||||
consoleColor{0x808000, true, true, false, false},
|
||||
consoleColor{0xc0c0c0, true, true, true, false},
|
||||
consoleColor{0x808080, false, false, false, true},
|
||||
consoleColor{0x0000ff, false, false, true, true},
|
||||
consoleColor{0x00ff00, false, true, false, true},
|
||||
consoleColor{0x00ffff, false, true, true, true},
|
||||
consoleColor{0xff0000, true, false, false, true},
|
||||
consoleColor{0xff00ff, true, false, true, true},
|
||||
consoleColor{0xffff00, true, true, false, true},
|
||||
consoleColor{0xffffff, true, true, true, true},
|
||||
}
|
||||
|
||||
type hsv struct {
|
||||
h, s, v float32
|
||||
}
|
||||
|
||||
func (a hsv) dist(b hsv) float32 {
|
||||
dh := a.h - b.h
|
||||
switch {
|
||||
case dh > 0.5:
|
||||
dh = 1 - dh
|
||||
case dh < -0.5:
|
||||
dh = -1 - dh
|
||||
}
|
||||
ds := a.s - b.s
|
||||
dv := a.v - b.v
|
||||
return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv)))
|
||||
}
|
||||
|
||||
func toHSV(rgb int) hsv {
|
||||
r, g, b := float32((rgb&0xFF0000)>>16)/256.0,
|
||||
float32((rgb&0x00FF00)>>8)/256.0,
|
||||
float32(rgb&0x0000FF)/256.0
|
||||
min, max := minmax3f(r, g, b)
|
||||
h := max - min
|
||||
if h > 0 {
|
||||
if max == r {
|
||||
h = (g - b) / h
|
||||
if h < 0 {
|
||||
h += 6
|
||||
}
|
||||
} else if max == g {
|
||||
h = 2 + (b-r)/h
|
||||
} else {
|
||||
h = 4 + (r-g)/h
|
||||
}
|
||||
}
|
||||
h /= 6.0
|
||||
s := max - min
|
||||
if max != 0 {
|
||||
s /= max
|
||||
}
|
||||
v := max
|
||||
return hsv{h: h, s: s, v: v}
|
||||
}
|
||||
|
||||
type hsvTable []hsv
|
||||
|
||||
func toHSVTable(rgbTable []consoleColor) hsvTable {
|
||||
t := make(hsvTable, len(rgbTable))
|
||||
for i, c := range rgbTable {
|
||||
t[i] = toHSV(c.rgb)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (t hsvTable) find(rgb int) consoleColor {
|
||||
hsv := toHSV(rgb)
|
||||
n := 7
|
||||
l := float32(5.0)
|
||||
for i, p := range t {
|
||||
d := hsv.dist(p)
|
||||
if d < l {
|
||||
l, n = d, i
|
||||
}
|
||||
}
|
||||
return color16[n]
|
||||
}
|
||||
|
||||
func minmax3f(a, b, c float32) (min, max float32) {
|
||||
if a < b {
|
||||
if b < c {
|
||||
return a, c
|
||||
} else if a < c {
|
||||
return a, b
|
||||
} else {
|
||||
return c, b
|
||||
}
|
||||
} else {
|
||||
if a < c {
|
||||
return b, c
|
||||
} else if b < c {
|
||||
return b, a
|
||||
} else {
|
||||
return c, a
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var n256foreAttr []word
|
||||
var n256backAttr []word
|
||||
|
||||
func n256setup() {
|
||||
n256foreAttr = make([]word, 256)
|
||||
n256backAttr = make([]word, 256)
|
||||
t := toHSVTable(color16)
|
||||
for i, rgb := range color256 {
|
||||
c := t.find(rgb)
|
||||
n256foreAttr[i] = c.foregroundAttr()
|
||||
n256backAttr[i] = c.backgroundAttr()
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// +build appengine
|
||||
|
||||
package isatty
|
||||
|
||||
// IsTerminal returns true if the file descriptor is terminal which
|
||||
// is always false on on appengine classic which is a sandboxed PaaS.
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
return false
|
||||
}
|
||||
+1
@@ -1,4 +1,5 @@
|
||||
// +build darwin freebsd openbsd netbsd
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
|
||||
+1
@@ -1,4 +1,5 @@
|
||||
// +build linux
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// +build solaris
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// IsTerminal returns true if the given file descriptor is a terminal.
|
||||
// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
var termio unix.Termio
|
||||
err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio)
|
||||
return err == nil
|
||||
}
|
||||
+1
@@ -1,4 +1,5 @@
|
||||
// +build windows
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 Mitchell Hashimoto
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
# go-homedir
|
||||
|
||||
This is a Go library for detecting the user's home directory without
|
||||
the use of cgo, so the library can be used in cross-compilation environments.
|
||||
|
||||
Usage is incredibly simple, just call `homedir.Dir()` to get the home directory
|
||||
for a user, and `homedir.Expand()` to expand the `~` in a path to the home
|
||||
directory.
|
||||
|
||||
**Why not just use `os/user`?** The built-in `os/user` package requires
|
||||
cgo on Darwin systems. This means that any Go code that uses that package
|
||||
cannot cross compile. But 99% of the time the use for `os/user` is just to
|
||||
retrieve the home directory, which we can do for the current user without
|
||||
cgo. This library does that, enabling cross-compilation.
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package homedir
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// DisableCache will disable caching of the home directory. Caching is enabled
|
||||
// by default.
|
||||
var DisableCache bool
|
||||
|
||||
var homedirCache string
|
||||
var cacheLock sync.RWMutex
|
||||
|
||||
// Dir returns the home directory for the executing user.
|
||||
//
|
||||
// This uses an OS-specific method for discovering the home directory.
|
||||
// An error is returned if a home directory cannot be detected.
|
||||
func Dir() (string, error) {
|
||||
if !DisableCache {
|
||||
cacheLock.RLock()
|
||||
cached := homedirCache
|
||||
cacheLock.RUnlock()
|
||||
if cached != "" {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
|
||||
cacheLock.Lock()
|
||||
defer cacheLock.Unlock()
|
||||
|
||||
var result string
|
||||
var err error
|
||||
if runtime.GOOS == "windows" {
|
||||
result, err = dirWindows()
|
||||
} else {
|
||||
// Unix-like system, so just assume Unix
|
||||
result, err = dirUnix()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
homedirCache = result
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Expand expands the path to include the home directory if the path
|
||||
// is prefixed with `~`. If it isn't prefixed with `~`, the path is
|
||||
// returned as-is.
|
||||
func Expand(path string) (string, error) {
|
||||
if len(path) == 0 {
|
||||
return path, nil
|
||||
}
|
||||
|
||||
if path[0] != '~' {
|
||||
return path, nil
|
||||
}
|
||||
|
||||
if len(path) > 1 && path[1] != '/' && path[1] != '\\' {
|
||||
return "", errors.New("cannot expand user-specific home dir")
|
||||
}
|
||||
|
||||
dir, err := Dir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filepath.Join(dir, path[1:]), nil
|
||||
}
|
||||
|
||||
func dirUnix() (string, error) {
|
||||
// First prefer the HOME environmental variable
|
||||
if home := os.Getenv("HOME"); home != "" {
|
||||
return home, nil
|
||||
}
|
||||
|
||||
// If that fails, try getent
|
||||
var stdout bytes.Buffer
|
||||
cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
|
||||
cmd.Stdout = &stdout
|
||||
if err := cmd.Run(); err != nil {
|
||||
// If "getent" is missing, ignore it
|
||||
if err != exec.ErrNotFound {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
if passwd := strings.TrimSpace(stdout.String()); passwd != "" {
|
||||
// username:password:uid:gid:gecos:home:shell
|
||||
passwdParts := strings.SplitN(passwd, ":", 7)
|
||||
if len(passwdParts) > 5 {
|
||||
return passwdParts[5], nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If all else fails, try the shell
|
||||
stdout.Reset()
|
||||
cmd = exec.Command("sh", "-c", "cd && pwd")
|
||||
cmd.Stdout = &stdout
|
||||
if err := cmd.Run(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
result := strings.TrimSpace(stdout.String())
|
||||
if result == "" {
|
||||
return "", errors.New("blank output when reading home directory")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func dirWindows() (string, error) {
|
||||
drive := os.Getenv("HOMEDRIVE")
|
||||
path := os.Getenv("HOMEPATH")
|
||||
home := drive + path
|
||||
if drive == "" || path == "" {
|
||||
home = os.Getenv("USERPROFILE")
|
||||
}
|
||||
if home == "" {
|
||||
return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
|
||||
}
|
||||
|
||||
return home, nil
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package homedir
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func patchEnv(key, value string) func() {
|
||||
bck := os.Getenv(key)
|
||||
deferFunc := func() {
|
||||
os.Setenv(key, bck)
|
||||
}
|
||||
|
||||
os.Setenv(key, value)
|
||||
return deferFunc
|
||||
}
|
||||
|
||||
func BenchmarkDir(b *testing.B) {
|
||||
// We do this for any "warmups"
|
||||
for i := 0; i < 10; i++ {
|
||||
Dir()
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Dir()
|
||||
}
|
||||
}
|
||||
|
||||
func TestDir(t *testing.T) {
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
dir, err := Dir()
|
||||
if err != nil {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
if u.HomeDir != dir {
|
||||
t.Fatalf("%#v != %#v", u.HomeDir, dir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpand(t *testing.T) {
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
Input string
|
||||
Output string
|
||||
Err bool
|
||||
}{
|
||||
{
|
||||
"/foo",
|
||||
"/foo",
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
"~/foo",
|
||||
fmt.Sprintf("%s/foo", u.HomeDir),
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
"",
|
||||
"",
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
"~",
|
||||
u.HomeDir,
|
||||
false,
|
||||
},
|
||||
|
||||
{
|
||||
"~foo/foo",
|
||||
"",
|
||||
true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
actual, err := Expand(tc.Input)
|
||||
if (err != nil) != tc.Err {
|
||||
t.Fatalf("Input: %#v\n\nErr: %s", tc.Input, err)
|
||||
}
|
||||
|
||||
if actual != tc.Output {
|
||||
t.Fatalf("Input: %#v\n\nOutput: %#v", tc.Input, actual)
|
||||
}
|
||||
}
|
||||
|
||||
DisableCache = true
|
||||
defer func() { DisableCache = false }()
|
||||
defer patchEnv("HOME", "/custom/path/")()
|
||||
expected := "/custom/path/foo/bar"
|
||||
actual, err := Expand("~/foo/bar")
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("No error is expected, got: %v", err)
|
||||
} else if actual != "/custom/path/foo/bar" {
|
||||
t.Errorf("Expected: %v; actual: %v", expected, actual)
|
||||
}
|
||||
}
|
||||
+499
@@ -0,0 +1,499 @@
|
||||
## API Documentation
|
||||
|
||||
### Minio client object creation
|
||||
Minio client object is created using minio-go:
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/minio-go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
s3Client, err := minio.New("s3.amazonaws.com", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", false)
|
||||
if err !!= nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
s3Client can be used to perform operations on S3 storage. APIs are described below.
|
||||
|
||||
### Bucket operations
|
||||
|
||||
* [`MakeBucket`](#MakeBucket)
|
||||
* [`ListBuckets`](#ListBuckets)
|
||||
* [`BucketExists`](#BucketExists)
|
||||
* [`RemoveBucket`](#RemoveBucket)
|
||||
* [`ListObjects`](#ListObjects)
|
||||
* [`ListIncompleteUploads`](#ListIncompleteUploads)
|
||||
|
||||
### Object operations
|
||||
|
||||
* [`GetObject`](#GetObject)
|
||||
* [`PutObject`](#PutObject)
|
||||
* [`StatObject`](#StatObject)
|
||||
* [`RemoveObject`](#RemoveObject)
|
||||
* [`RemoveIncompleteUpload`](#RemoveIncompleteUpload)
|
||||
|
||||
### File operations.
|
||||
|
||||
* [`FPutObject`](#FPutObject)
|
||||
* [`FGetObject`](#FPutObject)
|
||||
|
||||
### Bucket policy operations.
|
||||
|
||||
* [`SetBucketPolicy`](#SetBucketPolicy)
|
||||
* [`GetBucketPolicy`](#GetBucketPolicy)
|
||||
* [`RemoveBucketPolicy`](#RemoveBucketPolicy)
|
||||
|
||||
### Presigned operations
|
||||
|
||||
* [`PresignedGetObject`](#PresignedGetObject)
|
||||
* [`PresignedPutObject`](#PresignedPutObject)
|
||||
* [`PresignedPostPolicy`](#PresignedPostPolicy)
|
||||
|
||||
### Bucket operations
|
||||
---------------------------------------
|
||||
<a name="MakeBucket">
|
||||
#### MakeBucket(bucketName, location)
|
||||
Create a new bucket.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_ - Name of the bucket.
|
||||
* `location` _string_ - region valid values are _us-west-1_, _us-west-2_, _eu-west-1_, _eu-central-1_, _ap-southeast-1_, _ap-northeast-1_, _ap-southeast-2_, _sa-east-1_
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.MakeBucket("mybucket", "us-west-1")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Println("Successfully created mybucket.")
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="ListBuckets">
|
||||
#### ListBuckets()
|
||||
List all buckets.
|
||||
|
||||
`bucketList` emits bucket with the format:
|
||||
* `bucket.Name` _string_: bucket name
|
||||
* `bucket.CreationDate` time.Time : date when bucket was created
|
||||
|
||||
__Example__
|
||||
```go
|
||||
buckets, err := s3Client.ListBuckets()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
for _, bucket := range buckets {
|
||||
fmt.Println(bucket)
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="BucketExists">
|
||||
#### BucketExists(bucketName)
|
||||
Check if bucket exists.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_ : name of the bucket
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.BucketExists("mybucket")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="RemoveBucket">
|
||||
#### RemoveBucket(bucketName)
|
||||
Remove a bucket.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_ : name of the bucket
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.RemoveBucket("mybucket")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="GetBucketPolicy">
|
||||
#### GetBucketPolicy(bucketName, objectPrefix)
|
||||
Get access permissions on a bucket or a prefix.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_ : name of the bucket
|
||||
* `objectPrefix` _string_ : name of the object prefix
|
||||
|
||||
__Example__
|
||||
```go
|
||||
bucketPolicy, err := s3Client.GetBucketPolicy("mybucket")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Println("Access permissions for mybucket is", bucketPolicy)
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="SetBucketPolicy">
|
||||
#### SetBucketPolicy(bucketname, objectPrefix, policy)
|
||||
Set access permissions on bucket or an object prefix.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectPrefix` _string_ : name of the object prefix
|
||||
* `policy` _BucketPolicy_: policy can be _non_, _readonly_, _readwrite_, _writeonly_
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.SetBucketPolicy("mybucket", "myprefix", BucketPolicyReadWrite)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="RemoveBucketPolicy">
|
||||
#### RemoveBucketPolicy(bucketname, objectPrefix)
|
||||
Remove existing permissions on bucket or an object prefix.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectPrefix` _string_ : name of the object prefix
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.RemoveBucketPolicy("mybucket", "myprefix")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
---------------------------------------
|
||||
<a name="ListObjects">
|
||||
#### ListObjects(bucketName, prefix, recursive, doneCh)
|
||||
List objects in a bucket.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectPrefix` _string_: the prefix of the objects that should be listed
|
||||
* `recursive` _bool_: `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'
|
||||
* `doneCh` chan struct{} : channel for pro-actively closing the internal go routine
|
||||
|
||||
__Return Value__
|
||||
* `<-chan ObjectInfo` _chan ObjectInfo_: Read channel for all the objects in the bucket, the object is of the format:
|
||||
* `objectInfo.Key` _string_: name of the object
|
||||
* `objectInfo.Size` _int64_: size of the object
|
||||
* `objectInfo.ETag` _string_: etag of the object
|
||||
* `objectInfo.LastModified` _time.Time_: modified time stamp
|
||||
|
||||
__Example__
|
||||
```go
|
||||
// Create a done channel to control 'ListObjects' go routine.
|
||||
doneCh := make(chan struct{})
|
||||
|
||||
// Indicate to our routine to exit cleanly upon return.
|
||||
defer close(doneCh)
|
||||
|
||||
isRecursive := true
|
||||
objectCh := s3Client.ListObjects("mybucket", "myprefix", isRecursive, doneCh)
|
||||
for object := range objectCh {
|
||||
if object.Err != nil {
|
||||
fmt.Println(object.Err)
|
||||
return
|
||||
}
|
||||
fmt.Println(object)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---------------------------------------
|
||||
<a name="ListIncompleteUploads">
|
||||
#### ListIncompleteUploads(bucketName, prefix, recursive)
|
||||
List partially uploaded objects in a bucket.
|
||||
|
||||
__Arguments__
|
||||
* `bucketname` _string_: name of the bucket
|
||||
* `prefix` _string_: prefix of the object names that are partially uploaded
|
||||
* `recursive` bool: directory style listing when false, recursive listing when true
|
||||
* `doneCh` chan struct{} : channel for pro-actively closing the internal go routine
|
||||
|
||||
__Return Value__
|
||||
* `<-chan ObjectMultipartInfo` _chan ObjectMultipartInfo_ : emits multipart objects of the format:
|
||||
* `multiPartObjInfo.Key` _string_: name of the incomplete object
|
||||
* `multiPartObjInfo.UploadID` _string_: upload ID of the incomplete object
|
||||
* `multiPartObjInfo.Size` _int64_: size of the incompletely uploaded object
|
||||
|
||||
__Example__
|
||||
```go
|
||||
// Create a done channel to control 'ListObjects' go routine.
|
||||
doneCh := make(chan struct{})
|
||||
|
||||
// Indicate to our routine to exit cleanly upon return.
|
||||
defer close(doneCh)
|
||||
|
||||
isRecursive := true
|
||||
multiPartObjectCh := s3Client.ListIncompleteUploads("mybucket", "myprefix", isRecursive, doneCh)
|
||||
for multiPartObject := range multiPartObjectCh {
|
||||
if multiPartObject.Err != nil {
|
||||
fmt.Println(multiPartObject.Err)
|
||||
return
|
||||
}
|
||||
fmt.Println(multiPartObject)
|
||||
}
|
||||
```
|
||||
|
||||
---------------------------------------
|
||||
### Object operations
|
||||
<a name="GetObject">
|
||||
#### GetObject(bucketName, objectName)
|
||||
Download an object.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
|
||||
__Return Value__
|
||||
* `object` _*minio.Object_ : _minio.Object_ represents object reader.
|
||||
|
||||
__Example__
|
||||
```go
|
||||
object, err := s3Client.GetObject("mybucket", "photo.jpg")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
localFile _ := os.Open("/tmp/local-file")
|
||||
if _, err := io.Copy(localFile, object); err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
---------------------------------------
|
||||
<a name="FGetObject">
|
||||
#### FGetObject(bucketName, objectName, filePath)
|
||||
Callback is called with `error` in case of error or `null` in case of success
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
* `filePath` _string_: path to which the object data will be written to
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.FGetObject("mybucket", "photo.jpg", "/tmp/photo.jpg")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="PutObject">
|
||||
#### PutObject(bucketName, objectName, reader, contentType)
|
||||
Upload an object.
|
||||
|
||||
Uploading a stream
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
* `reader` _io.Reader_: Any golang object implementing io.Reader
|
||||
* `contentType` _string_: content type of the object.
|
||||
|
||||
__Example__
|
||||
```go
|
||||
file, err := os.Open("my-testfile")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
n, err := s3Client.PutObject("my-bucketname", "my-objectname", object, "application/octet-stream")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
---------------------------------------
|
||||
<a name="FPutObject">
|
||||
#### FPutObject(bucketName, objectName, filePath, contentType)
|
||||
Uploads the object using contents from a file
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
* `filePath` _string_: file path of the file to be uploaded
|
||||
* `contentType` _string_: content type of the object
|
||||
|
||||
__Example__
|
||||
```go
|
||||
n, err := s3Client.FPutObject("my-bucketname", "my-objectname", "/tmp/my-filename.csv", "application/csv")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="StatObject">
|
||||
#### StatObject(bucketName, objectName)
|
||||
Get metadata of an object.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
|
||||
__Return Value__
|
||||
`objInfo` _ObjectInfo_ : object stat info for following format:
|
||||
* `objInfo.Size` _int64_: size of the object
|
||||
* `objInfo.ETag` _string_: etag of the object
|
||||
* `objInfo.ContentType` _string_: Content-Type of the object
|
||||
* `objInfo.LastModified` _string_: modified time stamp
|
||||
|
||||
__Example__
|
||||
```go
|
||||
objInfo, err := s3Client.StatObject("mybucket", "photo.jpg")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Println(objInfo)
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="RemoveObject">
|
||||
#### RemoveObject(bucketName, objectName)
|
||||
Remove an object.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.RemoveObject("mybucket", "photo.jpg")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
---------------------------------------
|
||||
<a name="RemoveIncompleteUpload">
|
||||
#### RemoveIncompleteUpload(bucketName, objectName)
|
||||
Remove an partially uploaded object.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
|
||||
__Example__
|
||||
```go
|
||||
err := s3Client.RemoveIncompleteUpload("mybucket", "photo.jpg")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
### Presigned operations
|
||||
---------------------------------------
|
||||
<a name="PresignedGetObject">
|
||||
#### PresignedGetObject(bucketName, objectName, expiry)
|
||||
Generate a presigned URL for GET.
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket.
|
||||
* `objectName` _string_: name of the object.
|
||||
* `expiry` _time.Duration_: expiry in seconds.
|
||||
`reqParams` _url.Values_ : additional response header overrides supports _response-expires_, _response-content-type_, _response-cache-control_, _response-content-disposition_
|
||||
|
||||
__Example__
|
||||
```go
|
||||
// Set request parameters for content-disposition.
|
||||
reqParams := make(url.Values)
|
||||
reqParams.Set("response-content-disposition", "attachment; filename=\"your-filename.txt\"")
|
||||
|
||||
// Generates a presigned url which expires in a day.
|
||||
presignedURL, err := s3Client.PresignedGetObject("mybucket", "photo.jpg", time.Second * 24 * 60 * 60, reqParams)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
---------------------------------------
|
||||
<a name="PresignedPutObject">
|
||||
#### PresignedPutObject(bucketName, objectName, expiry)
|
||||
Generate a presigned URL for PUT.
|
||||
<blockquote>
|
||||
NOTE: you can upload to S3 only with specified object name.
|
||||
</blockquote>
|
||||
|
||||
__Arguments__
|
||||
* `bucketName` _string_: name of the bucket
|
||||
* `objectName` _string_: name of the object
|
||||
* `expiry` _time.Duration_: expiry in seconds
|
||||
|
||||
__Example__
|
||||
```go
|
||||
// Generates a url which expires in a day.
|
||||
presignedURL, err := s3Client.PresignedPutObject("mybucket", "photo.jpg", time.Second * 24 * 60 * 60)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
---------------------------------------
|
||||
<a name="PresignedPostPolicy">
|
||||
#### PresignedPostPolicy
|
||||
PresignedPostPolicy we can provide policies specifying conditions restricting
|
||||
what you want to allow in a POST request, such as bucket name where objects can be
|
||||
uploaded, key name prefixes that you want to allow for the object being created and more.
|
||||
|
||||
We need to create our policy first:
|
||||
```go
|
||||
policy := minio.NewPostPolicy()
|
||||
```
|
||||
Apply upload policy restrictions:
|
||||
```go
|
||||
policy.SetBucket("my-bucketname")
|
||||
policy.SetKey("my-objectname")
|
||||
policy.SetExpires(time.Now().UTC().AddDate(0, 0, 10)) // expires in 10 days
|
||||
|
||||
// Only allow 'png' images.
|
||||
policy.SetContentType("image/png")
|
||||
|
||||
// Only allow content size in range 1KB to 1MB.
|
||||
policy.SetContentLengthRange(1024, 1024*1024)
|
||||
```
|
||||
Get the POST form key/value object:
|
||||
```go
|
||||
formData, err := s3Client.PresignedPostPolicy(policy)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
POST your content from the command line using `curl`:
|
||||
```go
|
||||
fmt.Printf("curl ")
|
||||
for k, v := range m {
|
||||
fmt.Printf("-F %s=%s ", k, v)
|
||||
}
|
||||
fmt.Printf("-F file=@/etc/bash.bashrc ")
|
||||
fmt.Printf("https://my-bucketname.s3.amazonaws.com\n")
|
||||
```
|
||||
+3
-1
@@ -14,7 +14,9 @@
|
||||
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
|
||||
- Run `go fmt`
|
||||
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
|
||||
- Make sure `go test -short -race ./...` and `go build` completes.
|
||||
- Make sure `go test -race ./...` and `go build` completes.
|
||||
NOTE: go test runs functional tests and requires you to have a AWS S3 account. Set them as environment variables
|
||||
``ACCESS_KEY`` and ``SECRET_KEY``. To run shorter version of the tests please use ``go test -short -race ./...``
|
||||
|
||||
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
|
||||
- `minio-go` project is strictly conformant with Golang style
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ export GOROOT=$(brew --prefix)/Cellar/go/${GOVERSION}/libexec
|
||||
export PATH=$PATH:${GOPATH}/bin
|
||||
```
|
||||
|
||||
##### Source the new enviornment
|
||||
##### Source the new environment
|
||||
|
||||
```sh
|
||||
$ source ~/.bash_profile
|
||||
|
||||
+11
-4
@@ -61,12 +61,14 @@ func main() {
|
||||
|
||||
## Documentation
|
||||
|
||||
[API documentation](./API.md)
|
||||
|
||||
## Examples
|
||||
|
||||
### Bucket Operations.
|
||||
* [MakeBucket(bucketName, BucketACL, location) error](examples/s3/makebucket.go)
|
||||
* [MakeBucket(bucketName, location) error](examples/s3/makebucket.go)
|
||||
* [BucketExists(bucketName) error](examples/s3/bucketexists.go)
|
||||
* [RemoveBucket(bucketName) error](examples/s3/removebucket.go)
|
||||
* [GetBucketACL(bucketName) (BucketACL, error)](examples/s3/getbucketacl.go)
|
||||
* [SetBucketACL(bucketName, BucketACL) error)](examples/s3/setbucketacl.go)
|
||||
* [ListBuckets() []BucketInfo](examples/s3/listbuckets.go)
|
||||
* [ListObjects(bucketName, objectPrefix, recursive, chan<- struct{}) <-chan ObjectInfo](examples/s3/listobjects.go)
|
||||
* [ListIncompleteUploads(bucketName, prefix, recursive, chan<- struct{}) <-chan ObjectMultipartInfo](examples/s3/listincompleteuploads.go)
|
||||
@@ -83,10 +85,15 @@ func main() {
|
||||
* [FGetObject(bucketName, objectName, filePath) error](examples/s3/fgetobject.go)
|
||||
|
||||
### Presigned Operations.
|
||||
* [PresignedGetObject(bucketName, objectName, time.Duration) (string, error)](examples/s3/presignedgetobject.go)
|
||||
* [PresignedGetObject(bucketName, objectName, time.Duration, url.Values) (string, error)](examples/s3/presignedgetobject.go)
|
||||
* [PresignedPutObject(bucketName, objectName, time.Duration) (string, error)](examples/s3/presignedputobject.go)
|
||||
* [PresignedPostPolicy(NewPostPolicy()) (map[string]string, error)](examples/s3/presignedpostpolicy.go)
|
||||
|
||||
### Bucket Policy Operations.
|
||||
* [SetBucketPolicy(bucketName, objectPrefix, BucketPolicy) error](examples/s3/setbucketpolicy.go)
|
||||
* [GetBucketPolicy(bucketName, objectPrefix) (BucketPolicy, error)](examples/s3/getbucketpolicy.go)
|
||||
* [RemoveBucketPolicy(bucketName, objectPrefix) error](examples/s3/removebucketpolicy.go)
|
||||
|
||||
### API Reference
|
||||
|
||||
[](http://godoc.org/github.com/minio/minio-go)
|
||||
|
||||
Generated
Vendored
+33
-44
@@ -47,7 +47,7 @@ type ErrorResponse struct {
|
||||
|
||||
// Region where the bucket is located. This header is returned
|
||||
// only in HEAD bucket and ListObjects response.
|
||||
AmzBucketRegion string
|
||||
Region string
|
||||
}
|
||||
|
||||
// ToErrorResponse - Returns parsed ErrorResponse struct from body and
|
||||
@@ -98,65 +98,54 @@ func httpRespToErrorResponse(resp *http.Response, bucketName, objectName string)
|
||||
case http.StatusNotFound:
|
||||
if objectName == "" {
|
||||
errResp = ErrorResponse{
|
||||
Code: "NoSuchBucket",
|
||||
Message: "The specified bucket does not exist.",
|
||||
BucketName: bucketName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
|
||||
Code: "NoSuchBucket",
|
||||
Message: "The specified bucket does not exist.",
|
||||
BucketName: bucketName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
Region: resp.Header.Get("x-amz-bucket-region"),
|
||||
}
|
||||
} else {
|
||||
errResp = ErrorResponse{
|
||||
Code: "NoSuchKey",
|
||||
Message: "The specified key does not exist.",
|
||||
BucketName: bucketName,
|
||||
Key: objectName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
|
||||
Code: "NoSuchKey",
|
||||
Message: "The specified key does not exist.",
|
||||
BucketName: bucketName,
|
||||
Key: objectName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
Region: resp.Header.Get("x-amz-bucket-region"),
|
||||
}
|
||||
}
|
||||
case http.StatusForbidden:
|
||||
errResp = ErrorResponse{
|
||||
Code: "AccessDenied",
|
||||
Message: "Access Denied.",
|
||||
BucketName: bucketName,
|
||||
Key: objectName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
|
||||
Code: "AccessDenied",
|
||||
Message: "Access Denied.",
|
||||
BucketName: bucketName,
|
||||
Key: objectName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
Region: resp.Header.Get("x-amz-bucket-region"),
|
||||
}
|
||||
case http.StatusConflict:
|
||||
errResp = ErrorResponse{
|
||||
Code: "Conflict",
|
||||
Message: "Bucket not empty.",
|
||||
BucketName: bucketName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
|
||||
Code: "Conflict",
|
||||
Message: "Bucket not empty.",
|
||||
BucketName: bucketName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
Region: resp.Header.Get("x-amz-bucket-region"),
|
||||
}
|
||||
default:
|
||||
errResp = ErrorResponse{
|
||||
Code: resp.Status,
|
||||
Message: resp.Status,
|
||||
BucketName: bucketName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
|
||||
Code: resp.Status,
|
||||
Message: resp.Status,
|
||||
BucketName: bucketName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
Region: resp.Header.Get("x-amz-bucket-region"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AccessDenied without a signature mismatch code, usually means
|
||||
// that the bucket policy has certain restrictions where some API
|
||||
// operations are not allowed. Handle this case so that top level
|
||||
// callers can interpret this easily and fall back if needed to a
|
||||
// lower functionality call. Read each individual API specific
|
||||
// code for such fallbacks.
|
||||
if errResp.Code == "AccessDenied" && errResp.Message == "Access Denied" {
|
||||
errResp.Code = "NotImplemented"
|
||||
errResp.Message = "Operation is not allowed according to your bucket policy."
|
||||
}
|
||||
return errResp
|
||||
}
|
||||
|
||||
|
||||
+133
-128
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,122 +20,89 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// GetBucketACL - Get the permissions on an existing bucket.
|
||||
//
|
||||
// Returned values are:
|
||||
//
|
||||
// private - Owner gets full access.
|
||||
// public-read - Owner gets full access, others get read access.
|
||||
// public-read-write - Owner gets full access, others get full access
|
||||
// too.
|
||||
// authenticated-read - Owner gets full access, authenticated users
|
||||
// get read access.
|
||||
func (c Client) GetBucketACL(bucketName string) (BucketACL, error) {
|
||||
// GetBucketPolicy - get bucket policy at a given path.
|
||||
func (c Client) GetBucketPolicy(bucketName, objectPrefix string) (bucketPolicy BucketPolicy, err error) {
|
||||
// Input validation.
|
||||
if err := isValidBucketName(bucketName); err != nil {
|
||||
return "", err
|
||||
return BucketPolicyNone, err
|
||||
}
|
||||
if err := isValidObjectPrefix(objectPrefix); err != nil {
|
||||
return BucketPolicyNone, err
|
||||
}
|
||||
policy, err := c.getBucketPolicy(bucketName, objectPrefix)
|
||||
if err != nil {
|
||||
return BucketPolicyNone, err
|
||||
}
|
||||
if policy.Statements == nil {
|
||||
return BucketPolicyNone, nil
|
||||
}
|
||||
if isBucketPolicyReadWrite(policy.Statements, bucketName, objectPrefix) {
|
||||
return BucketPolicyReadWrite, nil
|
||||
} else if isBucketPolicyWriteOnly(policy.Statements, bucketName, objectPrefix) {
|
||||
return BucketPolicyWriteOnly, nil
|
||||
} else if isBucketPolicyReadOnly(policy.Statements, bucketName, objectPrefix) {
|
||||
return BucketPolicyReadOnly, nil
|
||||
}
|
||||
return BucketPolicyNone, nil
|
||||
}
|
||||
|
||||
// Set acl query.
|
||||
func (c Client) getBucketPolicy(bucketName string, objectPrefix string) (BucketAccessPolicy, error) {
|
||||
// Input validation.
|
||||
if err := isValidBucketName(bucketName); err != nil {
|
||||
return BucketAccessPolicy{}, err
|
||||
}
|
||||
if err := isValidObjectPrefix(objectPrefix); err != nil {
|
||||
return BucketAccessPolicy{}, err
|
||||
}
|
||||
// Get resources properly escaped and lined up before
|
||||
// using them in http request.
|
||||
urlValues := make(url.Values)
|
||||
urlValues.Set("acl", "")
|
||||
urlValues.Set("policy", "")
|
||||
|
||||
// Instantiate a new request.
|
||||
req, err := c.newRequest("GET", requestMetadata{
|
||||
// Execute GET on bucket to list objects.
|
||||
resp, err := c.executeMethod("GET", requestMetadata{
|
||||
bucketName: bucketName,
|
||||
queryValues: urlValues,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Initiate the request.
|
||||
resp, err := c.do(req)
|
||||
defer closeResponse(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return BucketAccessPolicy{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", httpRespToErrorResponse(resp, bucketName, "")
|
||||
}
|
||||
}
|
||||
|
||||
// Decode access control policy.
|
||||
policy := accessControlPolicy{}
|
||||
err = xmlDecoder(resp.Body, &policy)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// We need to avoid following de-serialization check for Google
|
||||
// Cloud Storage. On Google Cloud Storage "private" canned ACL's
|
||||
// policy do not have grant list. Treat it as a valid case, check
|
||||
// for all other vendors.
|
||||
if !isGoogleEndpoint(c.endpointURL) {
|
||||
if policy.AccessControlList.Grant == nil {
|
||||
errorResponse := ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Access control Grant list is empty. " + reportIssue,
|
||||
BucketName: bucketName,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
|
||||
errResponse := httpRespToErrorResponse(resp, bucketName, "")
|
||||
if ToErrorResponse(errResponse).Code == "NoSuchBucketPolicy" {
|
||||
return BucketAccessPolicy{Version: "2012-10-17"}, nil
|
||||
}
|
||||
return "", errorResponse
|
||||
return BucketAccessPolicy{}, errResponse
|
||||
}
|
||||
}
|
||||
|
||||
// Boolean cues to indentify right canned acls.
|
||||
var publicRead, publicWrite, authenticatedRead bool
|
||||
|
||||
// Handle grants.
|
||||
grants := policy.AccessControlList.Grant
|
||||
for _, g := range grants {
|
||||
if g.Grantee.URI == "" && g.Permission == "FULL_CONTROL" {
|
||||
continue
|
||||
}
|
||||
if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AuthenticatedUsers" && g.Permission == "READ" {
|
||||
authenticatedRead = true
|
||||
break
|
||||
} else if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && g.Permission == "WRITE" {
|
||||
publicWrite = true
|
||||
} else if g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && g.Permission == "READ" {
|
||||
publicRead = true
|
||||
}
|
||||
// Read access policy up to maxAccessPolicySize.
|
||||
// http://docs.aws.amazon.com/AmazonS3/latest/dev/access-policy-language-overview.html
|
||||
// bucket policies are limited to 20KB in size, using a limit reader.
|
||||
bucketPolicyBuf, err := ioutil.ReadAll(io.LimitReader(resp.Body, maxAccessPolicySize))
|
||||
if err != nil {
|
||||
return BucketAccessPolicy{}, err
|
||||
}
|
||||
|
||||
// Verify if acl is authenticated read.
|
||||
if authenticatedRead {
|
||||
return BucketACL("authenticated-read"), nil
|
||||
policy, err := unMarshalBucketPolicy(bucketPolicyBuf)
|
||||
if err != nil {
|
||||
return BucketAccessPolicy{}, err
|
||||
}
|
||||
// Verify if acl is private.
|
||||
if !publicWrite && !publicRead {
|
||||
return BucketACL("private"), nil
|
||||
}
|
||||
// Verify if acl is public-read.
|
||||
if !publicWrite && publicRead {
|
||||
return BucketACL("public-read"), nil
|
||||
}
|
||||
// Verify if acl is public-read-write.
|
||||
if publicRead && publicWrite {
|
||||
return BucketACL("public-read-write"), nil
|
||||
}
|
||||
|
||||
return "", ErrorResponse{
|
||||
Code: "NoSuchBucketPolicy",
|
||||
Message: "The specified bucket does not have a bucket policy.",
|
||||
BucketName: bucketName,
|
||||
RequestID: "minio",
|
||||
// Sort the policy actions and resources for convenience.
|
||||
for _, statement := range policy.Statements {
|
||||
sort.Strings(statement.Actions)
|
||||
sort.Strings(statement.Resources)
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
// GetObject - returns an seekable, readable object.
|
||||
@@ -147,8 +114,9 @@ func (c Client) GetObject(bucketName, objectName string) (*Object, error) {
|
||||
if err := isValidObjectName(objectName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Send an explicit info to get the actual object size.
|
||||
objectInfo, err := c.StatObject(bucketName, objectName)
|
||||
|
||||
// Start the request as soon Get is initiated.
|
||||
httpReader, objectInfo, err := c.getObject(bucketName, objectName, 0, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -160,8 +128,7 @@ func (c Client) GetObject(bucketName, objectName string) (*Object, error) {
|
||||
// Create done channel.
|
||||
doneCh := make(chan struct{})
|
||||
|
||||
// This routine feeds partial object data as and when the caller
|
||||
// reads.
|
||||
// This routine feeds partial object data as and when the caller reads.
|
||||
go func() {
|
||||
defer close(reqCh)
|
||||
defer close(resCh)
|
||||
@@ -174,23 +141,27 @@ func (c Client) GetObject(bucketName, objectName string) (*Object, error) {
|
||||
return
|
||||
// Request message.
|
||||
case req := <-reqCh:
|
||||
// Get shortest length.
|
||||
// NOTE: Last remaining bytes are usually smaller than
|
||||
// req.Buffer size. Use that as the final length.
|
||||
length := math.Min(float64(len(req.Buffer)), float64(objectInfo.Size-req.Offset))
|
||||
httpReader, _, err := c.getObject(bucketName, objectName, req.Offset, int64(length))
|
||||
if err != nil {
|
||||
resCh <- readResponse{
|
||||
Error: err,
|
||||
// Offset changes fetch the new object at an Offset.
|
||||
if req.DidOffsetChange {
|
||||
// Read from offset.
|
||||
httpReader, _, err = c.getObject(bucketName, objectName, req.Offset, 0)
|
||||
if err != nil {
|
||||
resCh <- readResponse{
|
||||
Error: err,
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Read at least req.Buffer bytes, if not we have
|
||||
// reached our EOF.
|
||||
size, err := io.ReadFull(httpReader, req.Buffer)
|
||||
if err == io.ErrUnexpectedEOF {
|
||||
// If an EOF happens after reading some but not
|
||||
// all the bytes ReadFull returns ErrUnexpectedEOF
|
||||
err = io.EOF
|
||||
}
|
||||
// Reply back how much was read.
|
||||
resCh <- readResponse{
|
||||
Size: int(size),
|
||||
Error: err,
|
||||
@@ -211,8 +182,9 @@ type readResponse struct {
|
||||
// Read request message container to communicate with internal
|
||||
// go-routine.
|
||||
type readRequest struct {
|
||||
Buffer []byte
|
||||
Offset int64 // readAt offset.
|
||||
Buffer []byte
|
||||
Offset int64 // readAt offset.
|
||||
DidOffsetChange bool
|
||||
}
|
||||
|
||||
// Object represents an open object. It implements Read, ReadAt,
|
||||
@@ -225,6 +197,7 @@ type Object struct {
|
||||
reqCh chan<- readRequest
|
||||
resCh <-chan readResponse
|
||||
doneCh chan<- struct{}
|
||||
prevOffset int64
|
||||
currOffset int64
|
||||
objectInfo ObjectInfo
|
||||
|
||||
@@ -247,7 +220,7 @@ func (o *Object) Read(b []byte) (n int, err error) {
|
||||
o.mutex.Lock()
|
||||
defer o.mutex.Unlock()
|
||||
|
||||
// Previous prevErr is which was saved in previous operation.
|
||||
// prevErr is previous error saved from previous operation.
|
||||
if o.prevErr != nil || o.isClosed {
|
||||
return 0, o.prevErr
|
||||
}
|
||||
@@ -257,13 +230,27 @@ func (o *Object) Read(b []byte) (n int, err error) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
// Send current information over control channel to indicate we
|
||||
// are ready.
|
||||
// Send current information over control channel to indicate we are ready.
|
||||
reqMsg := readRequest{}
|
||||
|
||||
// Send the offset and pointer to the buffer over the channel.
|
||||
// Send the pointer to the buffer over the channel.
|
||||
reqMsg.Buffer = b
|
||||
reqMsg.Offset = o.currOffset
|
||||
|
||||
// Verify if offset has changed and currOffset is greater than
|
||||
// previous offset. Perhaps due to Seek().
|
||||
offsetChange := o.prevOffset - o.currOffset
|
||||
if offsetChange < 0 {
|
||||
offsetChange = -offsetChange
|
||||
}
|
||||
if offsetChange > 0 {
|
||||
// Fetch the new reader at the current offset again.
|
||||
reqMsg.Offset = o.currOffset
|
||||
reqMsg.DidOffsetChange = true
|
||||
} else {
|
||||
// No offset changes no need to fetch new reader, continue
|
||||
// reading.
|
||||
reqMsg.DidOffsetChange = false
|
||||
reqMsg.Offset = 0
|
||||
}
|
||||
|
||||
// Send read request over the control channel.
|
||||
o.reqCh <- reqMsg
|
||||
@@ -277,6 +264,9 @@ func (o *Object) Read(b []byte) (n int, err error) {
|
||||
// Update current offset.
|
||||
o.currOffset += bytesRead
|
||||
|
||||
// Save the current offset as previous offset.
|
||||
o.prevOffset = o.currOffset
|
||||
|
||||
if dataMsg.Error == nil {
|
||||
// If currOffset read is equal to objectSize
|
||||
// We have reached end of file, we return io.EOF.
|
||||
@@ -320,7 +310,7 @@ func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) {
|
||||
o.mutex.Lock()
|
||||
defer o.mutex.Unlock()
|
||||
|
||||
// prevErr is which was saved in previous operation.
|
||||
// prevErr is error which was saved in previous operation.
|
||||
if o.prevErr != nil || o.isClosed {
|
||||
return 0, o.prevErr
|
||||
}
|
||||
@@ -337,7 +327,16 @@ func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) {
|
||||
|
||||
// Send the offset and pointer to the buffer over the channel.
|
||||
reqMsg.Buffer = b
|
||||
reqMsg.Offset = offset
|
||||
|
||||
// For ReadAt offset always changes, minor optimization where
|
||||
// offset same as currOffset we don't change the offset.
|
||||
reqMsg.DidOffsetChange = offset != o.currOffset
|
||||
if reqMsg.DidOffsetChange {
|
||||
// Set new offset.
|
||||
reqMsg.Offset = offset
|
||||
// Save new offset as current offset.
|
||||
o.currOffset = offset
|
||||
}
|
||||
|
||||
// Send read request over the control channel.
|
||||
o.reqCh <- reqMsg
|
||||
@@ -348,10 +347,16 @@ func (o *Object) ReadAt(b []byte, offset int64) (n int, err error) {
|
||||
// Bytes read.
|
||||
bytesRead := int64(dataMsg.Size)
|
||||
|
||||
// Update current offset.
|
||||
o.currOffset += bytesRead
|
||||
|
||||
// Save current offset as previous offset before returning.
|
||||
o.prevOffset = o.currOffset
|
||||
|
||||
if dataMsg.Error == nil {
|
||||
// If offset+bytes read is equal to objectSize
|
||||
// If currentOffset is equal to objectSize
|
||||
// we have reached end of file, we return io.EOF.
|
||||
if offset+bytesRead == o.objectInfo.Size {
|
||||
if o.currOffset >= o.objectInfo.Size {
|
||||
return dataMsg.Size, io.EOF
|
||||
}
|
||||
return dataMsg.Size, nil
|
||||
@@ -381,7 +386,7 @@ func (o *Object) Seek(offset int64, whence int) (n int64, err error) {
|
||||
defer o.mutex.Unlock()
|
||||
|
||||
if o.prevErr != nil {
|
||||
// At EOF seeking is legal, for any other errors we return.
|
||||
// At EOF seeking is legal allow only io.EOF, for any other errors we return.
|
||||
if o.prevErr != io.EOF {
|
||||
return 0, o.prevErr
|
||||
}
|
||||
@@ -391,6 +396,11 @@ func (o *Object) Seek(offset int64, whence int) (n int64, err error) {
|
||||
if offset < 0 && whence != 2 {
|
||||
return 0, ErrInvalidArgument(fmt.Sprintf("Negative position not allowed for %d.", whence))
|
||||
}
|
||||
|
||||
// Save current offset as previous offset.
|
||||
o.prevOffset = o.currOffset
|
||||
|
||||
// Switch through whence.
|
||||
switch whence {
|
||||
default:
|
||||
return 0, ErrInvalidArgument(fmt.Sprintf("Invalid whence %d", whence))
|
||||
@@ -484,8 +494,8 @@ func (c Client) getObject(bucketName, objectName string, offset, length int64) (
|
||||
customHeader.Set("Range", fmt.Sprintf("bytes=%d", length))
|
||||
}
|
||||
|
||||
// Instantiate a new request.
|
||||
req, err := c.newRequest("GET", requestMetadata{
|
||||
// Execute GET on objectName.
|
||||
resp, err := c.executeMethod("GET", requestMetadata{
|
||||
bucketName: bucketName,
|
||||
objectName: objectName,
|
||||
customHeader: customHeader,
|
||||
@@ -493,11 +503,6 @@ func (c Client) getObject(bucketName, objectName string, offset, length int64) (
|
||||
if err != nil {
|
||||
return nil, ObjectInfo{}, err
|
||||
}
|
||||
// Execute the request.
|
||||
resp, err := c.do(req)
|
||||
if err != nil {
|
||||
return nil, ObjectInfo{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
|
||||
return nil, ObjectInfo{}, httpRespToErrorResponse(resp, bucketName, objectName)
|
||||
@@ -513,11 +518,11 @@ func (c Client) getObject(bucketName, objectName string, offset, length int64) (
|
||||
if err != nil {
|
||||
msg := "Last-Modified time format not recognized. " + reportIssue
|
||||
return nil, ObjectInfo{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: msg,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
AmzBucketRegion: resp.Header.Get("x-amz-bucket-region"),
|
||||
Code: "InternalError",
|
||||
Message: msg,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
Region: resp.Header.Get("x-amz-bucket-region"),
|
||||
}
|
||||
}
|
||||
// Get content-type.
|
||||
|
||||
+9
-28
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -34,13 +34,8 @@ import (
|
||||
// }
|
||||
//
|
||||
func (c Client) ListBuckets() ([]BucketInfo, error) {
|
||||
// Instantiate a new request.
|
||||
req, err := c.newRequest("GET", requestMetadata{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Initiate the request.
|
||||
resp, err := c.do(req)
|
||||
// Execute GET on service.
|
||||
resp, err := c.executeMethod("GET", requestMetadata{})
|
||||
defer closeResponse(resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -206,16 +201,11 @@ func (c Client) listObjectsQuery(bucketName, objectPrefix, objectMarker, delimit
|
||||
// Set max keys.
|
||||
urlValues.Set("max-keys", fmt.Sprintf("%d", maxkeys))
|
||||
|
||||
// Initialize a new request.
|
||||
req, err := c.newRequest("GET", requestMetadata{
|
||||
// Execute GET on bucket to list objects.
|
||||
resp, err := c.executeMethod("GET", requestMetadata{
|
||||
bucketName: bucketName,
|
||||
queryValues: urlValues,
|
||||
})
|
||||
if err != nil {
|
||||
return listBucketResult{}, err
|
||||
}
|
||||
// Execute list buckets.
|
||||
resp, err := c.do(req)
|
||||
defer closeResponse(resp)
|
||||
if err != nil {
|
||||
return listBucketResult{}, err
|
||||
@@ -388,16 +378,11 @@ func (c Client) listMultipartUploadsQuery(bucketName, keyMarker, uploadIDMarker,
|
||||
// Set max-uploads.
|
||||
urlValues.Set("max-uploads", fmt.Sprintf("%d", maxUploads))
|
||||
|
||||
// Instantiate a new request.
|
||||
req, err := c.newRequest("GET", requestMetadata{
|
||||
// Execute GET on bucketName to list multipart uploads.
|
||||
resp, err := c.executeMethod("GET", requestMetadata{
|
||||
bucketName: bucketName,
|
||||
queryValues: urlValues,
|
||||
})
|
||||
if err != nil {
|
||||
return listMultipartUploadsResult{}, err
|
||||
}
|
||||
// Execute list multipart uploads request.
|
||||
resp, err := c.do(req)
|
||||
defer closeResponse(resp)
|
||||
if err != nil {
|
||||
return listMultipartUploadsResult{}, err
|
||||
@@ -510,16 +495,12 @@ func (c Client) listObjectPartsQuery(bucketName, objectName, uploadID string, pa
|
||||
// Set max parts.
|
||||
urlValues.Set("max-parts", fmt.Sprintf("%d", maxParts))
|
||||
|
||||
req, err := c.newRequest("GET", requestMetadata{
|
||||
// Execute GET on objectName to get list of parts.
|
||||
resp, err := c.executeMethod("GET", requestMetadata{
|
||||
bucketName: bucketName,
|
||||
objectName: objectName,
|
||||
queryValues: urlValues,
|
||||
})
|
||||
if err != nil {
|
||||
return listObjectPartsResult{}, err
|
||||
}
|
||||
// Exectue list object parts.
|
||||
resp, err := c.do(req)
|
||||
defer closeResponse(resp)
|
||||
if err != nil {
|
||||
return listObjectPartsResult{}, err
|
||||
|
||||
+43
-15
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -18,13 +18,26 @@ package minio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
// supportedGetReqParams - supported request parameters for GET
|
||||
// presigned request.
|
||||
var supportedGetReqParams = map[string]struct{}{
|
||||
"response-expires": struct{}{},
|
||||
"response-content-type": struct{}{},
|
||||
"response-cache-control": struct{}{},
|
||||
"response-content-disposition": struct{}{},
|
||||
}
|
||||
|
||||
// presignURL - Returns a presigned URL for an input 'method'.
|
||||
// Expires maximum is 7days - ie. 604800 and minimum is 1.
|
||||
func (c Client) presignURL(method string, bucketName string, objectName string, expires time.Duration) (url string, err error) {
|
||||
func (c Client) presignURL(method string, bucketName string, objectName string, expires time.Duration, reqParams url.Values) (urlStr string, err error) {
|
||||
// Input validation.
|
||||
if method == "" {
|
||||
return "", ErrInvalidArgument("method cannot be empty.")
|
||||
}
|
||||
if err := isValidBucketName(bucketName); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -35,35 +48,50 @@ func (c Client) presignURL(method string, bucketName string, objectName string,
|
||||
return "", err
|
||||
}
|
||||
|
||||
if method == "" {
|
||||
return "", ErrInvalidArgument("method cannot be empty.")
|
||||
}
|
||||
|
||||
// Convert expires into seconds.
|
||||
expireSeconds := int64(expires / time.Second)
|
||||
// Instantiate a new request.
|
||||
// Since expires is set newRequest will presign the request.
|
||||
req, err := c.newRequest(method, requestMetadata{
|
||||
reqMetadata := requestMetadata{
|
||||
presignURL: true,
|
||||
bucketName: bucketName,
|
||||
objectName: objectName,
|
||||
expires: expireSeconds,
|
||||
})
|
||||
}
|
||||
|
||||
// For "GET" we are handling additional request parameters to
|
||||
// override its response headers.
|
||||
if method == "GET" {
|
||||
// Verify if input map has unsupported params, if yes exit.
|
||||
for k := range reqParams {
|
||||
if _, ok := supportedGetReqParams[k]; !ok {
|
||||
return "", ErrInvalidArgument(k + " unsupported request parameter for presigned GET.")
|
||||
}
|
||||
}
|
||||
// Save the request parameters to be used in presigning for
|
||||
// GET request.
|
||||
reqMetadata.queryValues = reqParams
|
||||
}
|
||||
|
||||
// Instantiate a new request.
|
||||
// Since expires is set newRequest will presign the request.
|
||||
req, err := c.newRequest(method, reqMetadata)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return req.URL.String(), nil
|
||||
}
|
||||
|
||||
// PresignedGetObject - Returns a presigned URL to access an object without credentials.
|
||||
// Expires maximum is 7days - ie. 604800 and minimum is 1.
|
||||
func (c Client) PresignedGetObject(bucketName string, objectName string, expires time.Duration) (url string, err error) {
|
||||
return c.presignURL("GET", bucketName, objectName, expires)
|
||||
// PresignedGetObject - Returns a presigned URL to access an object
|
||||
// without credentials. Expires maximum is 7days - ie. 604800 and
|
||||
// minimum is 1. Additionally you can override a set of response
|
||||
// headers using the query parameters.
|
||||
func (c Client) PresignedGetObject(bucketName string, objectName string, expires time.Duration, reqParams url.Values) (url string, err error) {
|
||||
return c.presignURL("GET", bucketName, objectName, expires, reqParams)
|
||||
}
|
||||
|
||||
// PresignedPutObject - Returns a presigned URL to upload an object without credentials.
|
||||
// Expires maximum is 7days - ie. 604800 and minimum is 1.
|
||||
func (c Client) PresignedPutObject(bucketName string, objectName string, expires time.Duration) (url string, err error) {
|
||||
return c.presignURL("PUT", bucketName, objectName, expires)
|
||||
return c.presignURL("PUT", bucketName, objectName, expires, nil)
|
||||
}
|
||||
|
||||
// PresignedPostPolicy - Returns POST form data to upload an object at a location.
|
||||
|
||||
+110
-61
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
|
||||
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -18,8 +18,11 @@ package minio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -27,28 +30,18 @@ import (
|
||||
|
||||
/// Bucket operations
|
||||
|
||||
// MakeBucket makes a new bucket.
|
||||
// MakeBucket creates a new bucket with bucketName.
|
||||
//
|
||||
// Optional arguments are acl and location - by default all buckets are created
|
||||
// with ``private`` acl and in US Standard region.
|
||||
//
|
||||
// ACL valid values - http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html
|
||||
//
|
||||
// private - owner gets full access [default].
|
||||
// public-read - owner gets full access, all others get read access.
|
||||
// public-read-write - owner gets full access, all others get full access too.
|
||||
// authenticated-read - owner gets full access, authenticated users get read access.
|
||||
// Location is an optional argument, by default all buckets are
|
||||
// created in US Standard Region.
|
||||
//
|
||||
// For Amazon S3 for more supported regions - http://docs.aws.amazon.com/general/latest/gr/rande.html
|
||||
// For Google Cloud Storage for more supported regions - https://cloud.google.com/storage/docs/bucket-locations
|
||||
func (c Client) MakeBucket(bucketName string, acl BucketACL, location string) error {
|
||||
func (c Client) MakeBucket(bucketName string, location string) error {
|
||||
// Validate the input arguments.
|
||||
if err := isValidBucketName(bucketName); err != nil {
|
||||
return err
|
||||
}
|
||||
if !acl.isValidBucketACL() {
|
||||
return ErrInvalidArgument("Unrecognized ACL " + acl.String())
|
||||
}
|
||||
|
||||
// If location is empty, treat is a default region 'us-east-1'.
|
||||
if location == "" {
|
||||
@@ -56,7 +49,7 @@ func (c Client) MakeBucket(bucketName string, acl BucketACL, location string) er
|
||||
}
|
||||
|
||||
// Instantiate the request.
|
||||
req, err := c.makeBucketRequest(bucketName, acl, location)
|
||||
req, err := c.makeBucketRequest(bucketName, location)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -74,7 +67,7 @@ func (c Client) MakeBucket(bucketName string, acl BucketACL, location string) er
|
||||
}
|
||||
}
|
||||
|
||||
// Save the location into cache on a successfull makeBucket response.
|
||||
// Save the location into cache on a successful makeBucket response.
|
||||
c.bucketLocCache.Set(bucketName, location)
|
||||
|
||||
// Return.
|
||||
@@ -82,14 +75,11 @@ func (c Client) MakeBucket(bucketName string, acl BucketACL, location string) er
|
||||
}
|
||||
|
||||
// makeBucketRequest constructs request for makeBucket.
|
||||
func (c Client) makeBucketRequest(bucketName string, acl BucketACL, location string) (*http.Request, error) {
|
||||
func (c Client) makeBucketRequest(bucketName string, location string) (*http.Request, error) {
|
||||
// Validate input arguments.
|
||||
if err := isValidBucketName(bucketName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !acl.isValidBucketACL() {
|
||||
return nil, ErrInvalidArgument("Unrecognized ACL " + acl.String())
|
||||
}
|
||||
|
||||
// In case of Amazon S3. The make bucket issued on already
|
||||
// existing bucket would fail with 'AuthorizationMalformed' error
|
||||
@@ -106,12 +96,6 @@ func (c Client) makeBucketRequest(bucketName string, acl BucketACL, location str
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// by default bucket acl is set to private.
|
||||
req.Header.Set("x-amz-acl", "private")
|
||||
if acl != "" {
|
||||
req.Header.Set("x-amz-acl", string(acl))
|
||||
}
|
||||
|
||||
// set UserAgent for the request.
|
||||
c.setUserAgent(req)
|
||||
|
||||
@@ -131,9 +115,12 @@ func (c Client) makeBucketRequest(bucketName string, acl BucketACL, location str
|
||||
}
|
||||
createBucketConfigBuffer := bytes.NewBuffer(createBucketConfigBytes)
|
||||
req.Body = ioutil.NopCloser(createBucketConfigBuffer)
|
||||
req.ContentLength = int64(createBucketConfigBuffer.Len())
|
||||
req.ContentLength = int64(len(createBucketConfigBytes))
|
||||
// Set content-md5.
|
||||
req.Header.Set("Content-Md5", base64.StdEncoding.EncodeToString(sumMD5(createBucketConfigBytes)))
|
||||
if c.signature.isV4() {
|
||||
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256(createBucketConfigBuffer.Bytes())))
|
||||
// Set sha256.
|
||||
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256(createBucketConfigBytes)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,60 +137,122 @@ func (c Client) makeBucketRequest(bucketName string, acl BucketACL, location str
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// SetBucketACL set the permissions on an existing bucket using access control lists (ACL).
|
||||
// SetBucketPolicy set the access permissions on an existing bucket.
|
||||
//
|
||||
// For example
|
||||
//
|
||||
// private - owner gets full access [default].
|
||||
// public-read - owner gets full access, all others get read access.
|
||||
// public-read-write - owner gets full access, all others get full access too.
|
||||
// authenticated-read - owner gets full access, authenticated users get read access.
|
||||
func (c Client) SetBucketACL(bucketName string, acl BucketACL) error {
|
||||
// none - owner gets full access [default].
|
||||
// readonly - anonymous get access for everyone at a given object prefix.
|
||||
// readwrite - anonymous list/put/delete access to a given object prefix.
|
||||
// writeonly - anonymous put/delete access to a given object prefix.
|
||||
func (c Client) SetBucketPolicy(bucketName string, objectPrefix string, bucketPolicy BucketPolicy) error {
|
||||
// Input validation.
|
||||
if err := isValidBucketName(bucketName); err != nil {
|
||||
return err
|
||||
}
|
||||
if !acl.isValidBucketACL() {
|
||||
return ErrInvalidArgument("Unrecognized ACL " + acl.String())
|
||||
if err := isValidObjectPrefix(objectPrefix); err != nil {
|
||||
return err
|
||||
}
|
||||
if !bucketPolicy.isValidBucketPolicy() {
|
||||
return ErrInvalidArgument(fmt.Sprintf("Invalid bucket policy provided. %s", bucketPolicy))
|
||||
}
|
||||
policy, err := c.getBucketPolicy(bucketName, objectPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// For bucket policy set to 'none' we need to remove the policy.
|
||||
if bucketPolicy == BucketPolicyNone && policy.Statements == nil {
|
||||
// No policies to set, return success.
|
||||
return nil
|
||||
}
|
||||
// Remove any previous policies at this path.
|
||||
policy.Statements = removeBucketPolicyStatement(policy.Statements, bucketName, objectPrefix)
|
||||
|
||||
bucketResourceStatement := &Statement{}
|
||||
objectResourceStatement := &Statement{}
|
||||
if bucketPolicy == BucketPolicyReadWrite {
|
||||
// Read write policy.
|
||||
bucketResourceStatement.Effect = "Allow"
|
||||
bucketResourceStatement.Principal.AWS = []string{"*"}
|
||||
bucketResourceStatement.Resources = []string{fmt.Sprintf("%s%s", awsResourcePrefix, bucketName)}
|
||||
bucketResourceStatement.Actions = readWriteBucketActions
|
||||
objectResourceStatement.Effect = "Allow"
|
||||
objectResourceStatement.Principal.AWS = []string{"*"}
|
||||
objectResourceStatement.Resources = []string{fmt.Sprintf("%s%s", awsResourcePrefix, bucketName+"/"+objectPrefix+"*")}
|
||||
objectResourceStatement.Actions = readWriteObjectActions
|
||||
// Save the read write policy.
|
||||
policy.Statements = append(policy.Statements, *bucketResourceStatement, *objectResourceStatement)
|
||||
} else if bucketPolicy == BucketPolicyReadOnly {
|
||||
// Read only policy.
|
||||
bucketResourceStatement.Effect = "Allow"
|
||||
bucketResourceStatement.Principal.AWS = []string{"*"}
|
||||
bucketResourceStatement.Resources = []string{fmt.Sprintf("%s%s", awsResourcePrefix, bucketName)}
|
||||
bucketResourceStatement.Actions = readOnlyBucketActions
|
||||
objectResourceStatement.Effect = "Allow"
|
||||
objectResourceStatement.Principal.AWS = []string{"*"}
|
||||
objectResourceStatement.Resources = []string{fmt.Sprintf("%s%s", awsResourcePrefix, bucketName+"/"+objectPrefix+"*")}
|
||||
objectResourceStatement.Actions = readOnlyObjectActions
|
||||
// Save the read only policy.
|
||||
policy.Statements = append(policy.Statements, *bucketResourceStatement, *objectResourceStatement)
|
||||
} else if bucketPolicy == BucketPolicyWriteOnly {
|
||||
// Write only policy.
|
||||
bucketResourceStatement.Effect = "Allow"
|
||||
bucketResourceStatement.Principal.AWS = []string{"*"}
|
||||
bucketResourceStatement.Resources = []string{fmt.Sprintf("%s%s", awsResourcePrefix, bucketName)}
|
||||
bucketResourceStatement.Actions = writeOnlyBucketActions
|
||||
objectResourceStatement.Effect = "Allow"
|
||||
objectResourceStatement.Principal.AWS = []string{"*"}
|
||||
objectResourceStatement.Resources = []string{fmt.Sprintf("%s%s", awsResourcePrefix, bucketName+"/"+objectPrefix+"*")}
|
||||
objectResourceStatement.Actions = writeOnlyObjectActions
|
||||
// Save the write only policy.
|
||||
policy.Statements = append(policy.Statements, *bucketResourceStatement, *objectResourceStatement)
|
||||
}
|
||||
// Save the updated policies.
|
||||
return c.putBucketPolicy(bucketName, policy)
|
||||
}
|
||||
|
||||
// Saves a new bucket policy.
|
||||
func (c Client) putBucketPolicy(bucketName string, policy BucketAccessPolicy) error {
|
||||
// Input validation.
|
||||
if err := isValidBucketName(bucketName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Set acl query.
|
||||
// If there are no policy statements, we should remove entire policy.
|
||||
if len(policy.Statements) == 0 {
|
||||
return c.removeBucketPolicy(bucketName)
|
||||
}
|
||||
|
||||
// Get resources properly escaped and lined up before
|
||||
// using them in http request.
|
||||
urlValues := make(url.Values)
|
||||
urlValues.Set("acl", "")
|
||||
urlValues.Set("policy", "")
|
||||
|
||||
// Add misc headers.
|
||||
customHeader := make(http.Header)
|
||||
|
||||
if acl != "" {
|
||||
customHeader.Set("x-amz-acl", acl.String())
|
||||
} else {
|
||||
customHeader.Set("x-amz-acl", "private")
|
||||
}
|
||||
|
||||
// Instantiate a new request.
|
||||
req, err := c.newRequest("PUT", requestMetadata{
|
||||
bucketName: bucketName,
|
||||
queryValues: urlValues,
|
||||
customHeader: customHeader,
|
||||
})
|
||||
policyBytes, err := json.Marshal(&policy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Initiate the request.
|
||||
resp, err := c.do(req)
|
||||
policyBuffer := bytes.NewReader(policyBytes)
|
||||
reqMetadata := requestMetadata{
|
||||
bucketName: bucketName,
|
||||
queryValues: urlValues,
|
||||
contentBody: policyBuffer,
|
||||
contentLength: int64(len(policyBytes)),
|
||||
contentMD5Bytes: sumMD5(policyBytes),
|
||||
contentSHA256Bytes: sum256(policyBytes),
|
||||
}
|
||||
|
||||
// Execute PUT to upload a new bucket policy.
|
||||
resp, err := c.executeMethod("PUT", reqMetadata)
|
||||
defer closeResponse(resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if resp != nil {
|
||||
// if error return.
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
return httpRespToErrorResponse(resp, bucketName, "")
|
||||
}
|
||||
}
|
||||
|
||||
// return
|
||||
return nil
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user