Compare commits

..
Author SHA1 Message Date
Harshavardhana 54761b22fd Merge pull request #1616 from harshavardhana/tag1
update: Change update tag to verify RELEASE instead of OFFICIAL
2016-02-18 20:05:18 -08:00
Harshavardhana 253f13640c update: Change update tag to verify RELEASE instead of OFFICIAL 2016-02-18 20:01:38 -08:00
Harshavardhana 97110c9676 Merge pull request #1615 from harshavardhana/build
build: Check for gopath and multiple source build locations.
2016-02-18 19:14:40 -08:00
Harshavardhana 9805c4d907 build: Check for gopath and multiple source build locations. 2016-02-18 18:26:47 -08:00
Anand Babu (AB) Periasamy 56d548ad10 Merge pull request #1614 from harshavardhana/fix-shadowing
build/vet: Fix all the shadowed variables.
2016-02-19 07:32:10 +05:30
Harshavardhana c196f6ee08 build/vet: Fix all the shadowed variables. 2016-02-18 17:04:45 -08:00
Harshavardhana db55841e7d Merge pull request #1613 from harshavardhana/go-1.6
build: Default to Golang 1.6
2016-02-18 16:23:24 -08:00
Harshavardhana fb70ef7b1c build: Default to Golang 1.6 2016-02-18 16:08:07 -08:00
Harshavardhana fa82223c50 Merge pull request #1612 from harshavardhana/config-folder
config: Config folder option should be honored.
2016-02-17 16:04:21 -08:00
Harshavardhana 6f3cd87993 config: Config folder option should be honored.
The fix is to load config factory once again, to avoid looking for stale
scoped global variables. For example ``mcCustomConfigDir``

Fixes #1611
2016-02-17 15:59:55 -08:00
Anand Babu (AB) Periasamy 3ca7ac613d Merge pull request #1609 from harshavardhana/fs-s3
fs/s3: move the code for fs and s3 out to the top-level.
2016-02-17 05:53:27 +05:30
Harshavardhana fe5b2f97e3 fs/s3: move the code for fs and s3 out to the top-level.
Now the interface moves to the top level - fixes #1604
2016-02-16 11:27:42 -08:00
Harshavardhana 220bf92a3c Merge pull request #1606 from harshavardhana/solaris
porting: mc now properly works on solaris.
2016-02-15 20:11:35 -08:00
Super-User 5219fd59e8 porting: mc now properly works on solaris.
Fixes #1603
2016-02-15 15:03:40 -08:00
Anand Babu (AB) Periasamy 4832da5cda Merge pull request #1602 from harshavardhana/make-release
build: Now builds for all platforms and builds into 'release/experimental' directory.
2016-02-09 14:22:24 -08:00
Harshavardhana 4ef3dcffc4 build: Now builds for all platforms and builds into 'release/experimental' directory.
Two Makefile options are

- make release
- make experimental

Currently supported OS and arch -

- linux/386
- linux/amd64
- linux/arm
- windows/386
- windows/amd64
- darwin/amd64
2016-02-09 14:18:35 -08:00
Harshavardhana fbe4768658 Merge pull request #1601 from harshavardhana/request-params
mc: update to new changes in minio-go.
2016-02-07 18:09:13 -08:00
Harshavardhana f63de3cc30 mc: update to new changes in minio-go. 2016-02-07 18:03:32 -08:00
Anand Babu (AB) Periasamy 7c7d9e07a2 Merge pull request #1600 from harshavardhana/use-mime
mc: Remove contentdb and use golang pkg/mime instead.
2016-02-06 16:15:51 -08:00
Harshavardhana 708f1e17f4 mc: Remove contentdb and use golang pkg/mime instead.
This is also because golang package sets proper 'charset's
for contentTypes. Also there is no reason for 'mc' to have
its own mimedb.
2016-02-06 10:43:57 -08:00
Krishna Srinivas 8fc48cf24a Merge pull request #1599 from harshavardhana/vendorize
minio-go: Vendorize with new changes.
2016-02-06 13:21:52 +05:30
305 changed files with 99875 additions and 2447 deletions
+2
View File
@@ -2,3 +2,5 @@ cover.out
mc
*~
*.test
release
experimental
+1 -2
View File
@@ -13,8 +13,7 @@ env:
- ARCH=i686
go:
- 1.5.2
- 1.5.3
- 1.6
script:
- diff -au <(gofmt -d *.go) <(printf "")
+5 -5
View File
@@ -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
View File
@@ -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.
+24 -22
View File
@@ -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,13 @@ 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
@rm -fr release
+1 -1
View File
@@ -23,7 +23,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 (
+3
View File
@@ -14,6 +14,9 @@ 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
+3 -3
View File
@@ -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]
)
+48
View File
@@ -0,0 +1,48 @@
#!/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'
}
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}"
GO15VENDOREXPERIMENT=1 GOOS=$os GOARCH=$arch go build --ldflags "${LDFLAGS}" -o $release_str/$os-$arch/$(basename $package).$release_tag
}
main() {
# Build releases.
echo "Executing $release_str builds for OS: ${SUPPORTED_OSARCH}"
for osarch in ${SUPPORTED_OSARCH}; do
go_build ${osarch}
done
}
# Run main.
_init && main
+18 -6
View File
@@ -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,19 +136,28 @@ 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
;;
"*")
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() {
@@ -160,12 +169,15 @@ is_supported_arch() {
"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
}
+40
View File
@@ -0,0 +1,40 @@
#!/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.
#
_init() {
shopt -s extglob
PWD=$(env pwd)
GOPATH=$(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
+1 -1
View File
@@ -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
View File
@@ -25,7 +25,7 @@ import (
"syscall"
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
+2 -27
View File
@@ -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
@@ -75,12 +63,6 @@ func (e BucketNameEmpty) Error() string {
return "Bucket name cannot be empty."
}
// GenericObjectError - generic object operations error
type GenericObjectError struct {
Bucket string
Object string
}
// ObjectAlreadyExists - typed return for MethodNotAllowed
type ObjectAlreadyExists struct {
Object string
@@ -90,13 +72,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{}
+170 -73
View File
@@ -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),
}
}
@@ -722,24 +760,83 @@ func (f *fsClient) MakeBucket(region string) *probe.Error {
// GetBucketACL - get bucket access.
func (f *fsClient) GetBucketAccess() (acl string, err *probe.Error) {
return "", probe.NewError(client.APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
return "", probe.NewError(APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
}
// SetBucketAccess - set bucket access.
func (f *fsClient) SetBucketAccess(acl string) *probe.Error {
return probe.NewError(client.APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"})
return probe.NewError(APINotImplemented{API: "SetBucketAccess", APIType: "filesystem"})
}
// 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
}
+23 -32
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package fs_test
package main
import (
"bytes"
@@ -22,28 +22,19 @@ import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"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 +46,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 +54,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 +72,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 +80,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 +96,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 +130,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,13 +159,13 @@ 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)
@@ -187,13 +178,13 @@ func (s *MySuite) TestBucketACLFails(c *C) {
}
// 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 +196,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 +222,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 +251,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 &&
+66 -64
View File
@@ -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,10 +111,10 @@ 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)
@@ -127,12 +127,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 +143,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)
}
@@ -164,28 +164,28 @@ func (c *s3Client) Put(reader io.Reader, size int64, contentType string, progres
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{})
return n, probe.NewError(ObjectMissing{})
}
return n, probe.NewError(e)
}
@@ -232,7 +232,7 @@ 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)
@@ -248,10 +248,10 @@ func (c *s3Client) MakeBucket(region string) *probe.Error {
func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
bucket, object := c.url2BucketAndObject()
if object != "" {
return "", probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
return "", probe.NewError(InvalidBucketName{Bucket: filepath.Join(bucket, object)})
}
if bucket == "" {
return "", probe.NewError(client.BucketNameEmpty{})
return "", probe.NewError(BucketNameEmpty{})
}
bucketACL, e := c.api.GetBucketACL(bucket)
if e != nil {
@@ -264,10 +264,10 @@ func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
bucket, object := c.url2BucketAndObject()
if object != "" {
return probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
return probe.NewError(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))
if e != nil {
@@ -277,9 +277,9 @@ 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/'
@@ -290,7 +290,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
return nil, probe.NewError(e)
}
c.mutex.Unlock()
return &client.Content{URL: *c.targetURL, Type: os.ModeDir}, nil
return &clientContent{URL: *c.targetURL, Type: os.ModeDir}, nil
}
if object != "" {
metadata, e := c.api.StatObject(bucket, object)
@@ -308,12 +308,12 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
if objectStat.Err != nil {
return nil, probe.NewError(objectStat.Err)
}
content := client.Content{}
content := clientContent{}
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(PathNotFound{Path: c.targetURL.Path})
}
return nil, probe.NewError(e)
}
@@ -329,7 +329,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
c.mutex.Unlock()
return nil, probe.NewError(e)
}
bucketMetadata := new(client.Content)
bucketMetadata := &clientContent{}
bucketMetadata.URL = *c.targetURL
bucketMetadata.Type = os.ModeDir
c.mutex.Unlock()
@@ -389,11 +389,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 +410,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 +418,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 +427,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 +458,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 +487,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 +495,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 +504,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 +523,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 +534,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,7 +544,7 @@ 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()
@@ -552,7 +552,7 @@ func (c *s3Client) listInRoutine(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
@@ -560,7 +560,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
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
@@ -570,11 +570,11 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
case b != "" && !strings.HasSuffix(c.targetURL.Path, string(c.targetURL.Separator)) && o == "":
e := c.api.BucketExists(b)
if e != nil {
contentCh <- &client.Content{
contentCh <- &clientContent{
Err: probe.NewError(e),
}
}
content := new(client.Content)
content := &clientContent{}
content.URL = *c.targetURL
content.Type = os.ModeDir
contentCh <- content
@@ -582,7 +582,7 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
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 +592,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 +622,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 +630,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 +638,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 +646,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 +665,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 +690,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)
}
+10 -19
View File
@@ -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"
)
@@ -168,26 +165,20 @@ 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")
@@ -197,7 +188,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
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 +197,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 +206,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 +216,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 +224,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
+7 -7
View File
@@ -14,21 +14,21 @@
* 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
@@ -47,12 +47,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
+7 -10
View File
@@ -23,15 +23,12 @@ 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/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 +98,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,7 +112,7 @@ 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 := new(Config)
s3Config.AccessKey = hostCfg.AccessKey
s3Config.SecretKey = hostCfg.SecretKey
s3Config.Signature = hostCfg.API
@@ -125,7 +122,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 +133,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
View File
@@ -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.
+1 -1
View File
@@ -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 (
+1 -1
View File
@@ -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.
+17 -3
View File
@@ -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
}
+2 -2
View File
@@ -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 (
+11 -13
View File
@@ -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 {
+7 -8
View File
@@ -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"
)
@@ -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
+1 -2
View File
@@ -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 -21
View File
@@ -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) {
+4 -5
View File
@@ -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.
@@ -144,11 +143,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
}
@@ -173,7 +172,7 @@ func doDiffMain(firstURL, secondURL string) {
if sourceContent.Err != nil {
switch sourceContent.Err.ToGoError().(type) {
// Handle this specifically for filesystem related errors.
case client.BrokenSymlink, client.TooManyLevelsSymlink, client.PathNotFound, client.PathInsufficientPermission:
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, PathInsufficientPermission:
errorIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
default:
fatalIf(sourceContent.Err.Trace(firstURL, secondURL), fmt.Sprintf("Failed on '%s'", firstURL))
+2 -3
View File
@@ -19,8 +19,7 @@ package main
import (
"os"
"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
@@ -49,7 +48,7 @@ func objectDifferenceFactory(targetAlias, targetURL string) (objectDifference, *
current := targetURL
reachedEOF := false
ok := false
var content *client.Content
var content *clientContent
difference := func(suffix string, srcType os.FileMode, srcSize int64) (string, *probe.Error) {
if reachedEOF {
+1 -1
View File
@@ -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 -2
View File
@@ -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+"’.")
+7 -8
View File
@@ -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
}
+4 -5
View File
@@ -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.")
@@ -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
View File
@@ -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 (
+2 -6
View File
@@ -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)
+7 -8
View File
@@ -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"
)
@@ -297,17 +296,17 @@ func doMirrorSession(session *sessionV6) {
switch sURLs.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
+9 -10
View File
@@ -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 {
// 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 %s", tgtURL))
}
}
func deltaSourceTargets(sourceURL string, targetURL string, isForce 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
}
@@ -151,7 +150,7 @@ func deltaSourceTargets(sourceURL string, targetURL string, isForce bool, mirror
}
// either available only in source or size differs and force is set
targetPath := urlJoinPath(targetURL, suffix)
targetContent := &client.Content{URL: *client.NewURL(targetPath)}
targetContent := &clientContent{URL: *newURL(targetPath)}
mirrorURLsCh <- mirrorURLs{
SourceAlias: sourceAlias,
SourceContent: sourceContent,
+4 -6
View File
@@ -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
View File
@@ -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.
-69
View File
@@ -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
View File
@@ -1 +0,0 @@
*#
-86
View File
@@ -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
}
-168
View File
@@ -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
}
-162
View File
@@ -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()
}
+2 -2
View File
@@ -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{}) {
+8
View File
@@ -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()
-5
View File
@@ -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
-6
View File
@@ -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"
+1 -1
View File
@@ -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.
+6 -8
View File
@@ -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
View File
@@ -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 (
+2 -2
View File
@@ -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() {
+1 -1
View File
@@ -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
View File
@@ -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.
+1 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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 (
+3 -4
View File
@@ -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"]
+1 -1
View File
@@ -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 (
+1 -1
View File
@@ -19,7 +19,7 @@ package main
import (
"errors"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/probe"
)
var (
+5 -4
View File
@@ -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 {
@@ -144,7 +145,7 @@ func getReleaseUpdate(updateURL string) {
data, e := http.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")
}
+150 -12
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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(" ")
@@ -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
View File
@@ -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!
![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png)
## So Good!
![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png)
## 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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -1,4 +1,5 @@
// +build darwin freebsd openbsd netbsd
// +build !appengine
package isatty
+1
View File
@@ -1,4 +1,5 @@
// +build linux
// +build !appengine
package isatty
+16
View File
@@ -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
View File
@@ -1,4 +1,5 @@
// +build windows
// +build !appengine
package isatty
+21
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
}
+3 -1
View File
@@ -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
View File
@@ -83,7 +83,7 @@ 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)
+42 -14
View File
@@ -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.
+12 -48
View File
@@ -78,7 +78,7 @@ const (
// NewV2 - instantiate minio client with Amazon S3 signature version
// '2' compatibility.
func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) {
func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) {
clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure)
if err != nil {
return nil, err
@@ -90,7 +90,7 @@ func NewV2(endpoint string, accessKeyID, secretAccessKey string, insecure bool)
// NewV4 - instantiate minio client with Amazon S3 signature version
// '4' compatibility.
func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) {
func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) {
clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure)
if err != nil {
return nil, err
@@ -102,7 +102,7 @@ func NewV4(endpoint string, accessKeyID, secretAccessKey string, insecure bool)
// New - instantiate minio client Client, adds automatic verification
// of signature.
func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (CloudStorageClient, error) {
func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (*Client, error) {
clnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, insecure)
if err != nil {
return nil, err
@@ -112,7 +112,7 @@ func New(endpoint string, accessKeyID, secretAccessKey string, insecure bool) (C
if isGoogleEndpoint(clnt.endpointURL) {
clnt.signature = SignatureV2
}
// If Amazon S3 set to signature v2.
// If Amazon S3 set to signature v2.n
if isAmazonEndpoint(clnt.endpointURL) {
clnt.signature = SignatureV4
}
@@ -138,7 +138,14 @@ func privateNew(endpoint, accessKeyID, secretAccessKey string, insecure bool) (*
clnt.endpointURL = endpointURL
// Instantiate http client and bucket location cache.
clnt.httpClient = &http.Client{}
clnt.httpClient = &http.Client{
// Setting a sensible time out of 30secs to wait for response
// headers. Request is pro-actively cancelled after 30secs
// with no response.
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
}
clnt.bucketLocCache = newBucketLocationCache()
// Return.
@@ -493,46 +500,3 @@ func (c Client) makeTargetURL(bucketName, objectName, bucketLocation string, que
return u, nil
}
// CloudStorageClient - Cloud Storage Client interface.
type CloudStorageClient interface {
// Bucket Read/Write/Stat operations.
MakeBucket(bucketName string, cannedACL BucketACL, location string) error
BucketExists(bucketName string) error
RemoveBucket(bucketName string) error
SetBucketACL(bucketName string, cannedACL BucketACL) error
GetBucketACL(bucketName string) (BucketACL, error)
ListBuckets() ([]BucketInfo, error)
ListObjects(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectInfo
ListIncompleteUploads(bucket, prefix string, recursive bool, doneCh <-chan struct{}) <-chan ObjectMultipartInfo
// Object Read/Write/Stat operations.
GetObject(bucketName, objectName string) (reader *Object, err error)
PutObject(bucketName, objectName string, reader io.Reader, contentType string) (n int64, err error)
StatObject(bucketName, objectName string) (ObjectInfo, error)
RemoveObject(bucketName, objectName string) error
RemoveIncompleteUpload(bucketName, objectName string) error
// File to Object API.
FPutObject(bucketName, objectName, filePath, contentType string) (n int64, err error)
FGetObject(bucketName, objectName, filePath string) error
// PutObjectWithProgress for progress.
PutObjectWithProgress(bucketName, objectName string, reader io.Reader, contentType string, progress io.Reader) (n int64, err error)
// Presigned operations.
PresignedGetObject(bucketName, objectName string, expires time.Duration) (presignedURL string, err error)
PresignedPutObject(bucketName, objectName string, expires time.Duration) (presignedURL string, err error)
PresignedPostPolicy(*PostPolicy) (formData map[string]string, err error)
// Application info.
SetAppInfo(appName, appVersion string)
// Set custom transport.
SetCustomTransport(customTransport http.RoundTripper)
// HTTP tracing methods.
TraceOn(traceOutput io.Writer)
TraceOff()
}
+39 -3
View File
@@ -24,6 +24,7 @@ import (
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"testing"
"time"
@@ -954,11 +955,12 @@ func TestFunctionalV2(t *testing.T) {
t.Fatal("Error: ", err)
}
presignedGetURL, err := c.PresignedGetObject(bucketName, objectName, 3600*time.Second)
// Generate presigned GET object url.
presignedGetURL, err := c.PresignedGetObject(bucketName, objectName, 3600*time.Second, nil)
if err != nil {
t.Fatal("Error: ", err)
}
// Verify if presigned url works.
resp, err := http.Get(presignedGetURL)
if err != nil {
t.Fatal("Error: ", err)
@@ -974,6 +976,34 @@ func TestFunctionalV2(t *testing.T) {
t.Fatal("Error: bytes mismatch.")
}
// Set request parameters.
reqParams := make(url.Values)
reqParams.Set("response-content-disposition", "attachment; filename=\"test.txt\"")
// Generate presigned GET object url.
presignedGetURL, err = c.PresignedGetObject(bucketName, objectName, 3600*time.Second, reqParams)
if err != nil {
t.Fatal("Error: ", err)
}
// Verify if presigned url works.
resp, err = http.Get(presignedGetURL)
if err != nil {
t.Fatal("Error: ", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("Error: ", resp.Status)
}
newPresignedBytes, err = ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal("Error: ", err)
}
if !bytes.Equal(newPresignedBytes, buf) {
t.Fatal("Error: bytes mismatch for presigned GET url.")
}
// Verify content disposition.
if resp.Header.Get("Content-Disposition") != "attachment; filename=\"test.txt\"" {
t.Fatalf("Error: wrong Content-Disposition received %s", resp.Header.Get("Content-Disposition"))
}
presignedPutURL, err := c.PresignedPutObject(bucketName, objectName+"-presigned", 3600*time.Second)
if err != nil {
t.Fatal("Error: ", err)
@@ -987,7 +1017,13 @@ func TestFunctionalV2(t *testing.T) {
if err != nil {
t.Fatal("Error: ", err)
}
httpClient := &http.Client{}
httpClient := &http.Client{
// Setting a sensible time out of 30secs to wait for response
// headers. Request is pro-actively cancelled after 30secs
// with no response.
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
}
resp, err = httpClient.Do(req)
if err != nil {
t.Fatal("Error: ", err)
+37 -2
View File
@@ -24,6 +24,7 @@ import (
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"testing"
"time"
@@ -983,11 +984,13 @@ func TestFunctional(t *testing.T) {
t.Fatal("Error: ", err)
}
presignedGetURL, err := c.PresignedGetObject(bucketName, objectName, 3600*time.Second)
// Generate presigned GET object url.
presignedGetURL, err := c.PresignedGetObject(bucketName, objectName, 3600*time.Second, nil)
if err != nil {
t.Fatal("Error: ", err)
}
// Verify if presigned url works.
resp, err := http.Get(presignedGetURL)
if err != nil {
t.Fatal("Error: ", err)
@@ -1003,6 +1006,32 @@ func TestFunctional(t *testing.T) {
t.Fatal("Error: bytes mismatch.")
}
// Set request parameters.
reqParams := make(url.Values)
reqParams.Set("response-content-disposition", "attachment; filename=\"test.txt\"")
presignedGetURL, err = c.PresignedGetObject(bucketName, objectName, 3600*time.Second, reqParams)
if err != nil {
t.Fatal("Error: ", err)
}
// Verify if presigned url works.
resp, err = http.Get(presignedGetURL)
if err != nil {
t.Fatal("Error: ", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("Error: ", resp.Status)
}
newPresignedBytes, err = ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal("Error: ", err)
}
if !bytes.Equal(newPresignedBytes, buf) {
t.Fatal("Error: bytes mismatch for presigned GET URL.")
}
if resp.Header.Get("Content-Disposition") != "attachment; filename=\"test.txt\"" {
t.Fatalf("Error: wrong Content-Disposition received %s", resp.Header.Get("Content-Disposition"))
}
presignedPutURL, err := c.PresignedPutObject(bucketName, objectName+"-presigned", 3600*time.Second)
if err != nil {
t.Fatal("Error: ", err)
@@ -1016,7 +1045,13 @@ func TestFunctional(t *testing.T) {
if err != nil {
t.Fatal("Error: ", err)
}
httpClient := &http.Client{}
httpClient := &http.Client{
// Setting a sensible time out of 30secs to wait for response
// headers. Request is pro-actively cancelled after 30secs
// with no response.
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
}
resp, err = httpClient.Do(req)
if err != nil {
t.Fatal("Error: ", err)
+13 -4
View File
@@ -73,6 +73,11 @@ func preSignV2(req http.Request, accessKeyID, secretAccessKey string, expires in
// Get encoded URL path.
path := encodeURL2Path(req.URL)
if len(req.URL.Query()) > 0 {
// Keep the usual queries unescaped for string to sign.
query, _ := url.QueryUnescape(queryEncode(req.URL.Query()))
path = path + "?" + query
}
// Find epoch expires when the request will expire.
epochExpires := d.Unix() + expires
@@ -93,12 +98,16 @@ func preSignV2(req http.Request, accessKeyID, secretAccessKey string, expires in
query.Set("AWSAccessKeyId", accessKeyID)
}
// Fill in Expires and Signature for presigned query.
// Fill in Expires for presigned query.
query.Set("Expires", strconv.FormatInt(epochExpires, 10))
query.Set("Signature", signature)
// Encode query and save.
req.URL.RawQuery = query.Encode()
req.URL.RawQuery = queryEncode(query)
// Save signature finally.
req.URL.RawQuery += "&Signature=" + urlEncodePath(signature)
// Return.
return &req
}
@@ -283,7 +292,7 @@ func writeCanonicalizedResource(buf *bytes.Buffer, req http.Request) {
// Request parameters
if len(vv[0]) > 0 {
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(vv[0]))
buf.WriteString(strings.Replace(url.QueryEscape(vv[0]), "+", "%20", -1))
}
}
}
@@ -1,5 +1,5 @@
/*
* Minio Client (C) 2015 Minio, Inc.
* 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.
@@ -34,7 +34,7 @@ type MySuite struct {
var _ = Suite(&MySuite{})
func (s *MySuite) SetUpSuite(c *C) {
root, err := ioutil.TempDir("/tmp", "atomic-")
root, err := ioutil.TempDir(os.TempDir(), "atomic-")
c.Assert(err, IsNil)
s.root = root
}
-26
View File
@@ -1,26 +0,0 @@
# Generate db.go from db.json downloaded nodejs mime-db project.
# NOTE: Autogenerated db.go needs to be vet proofed. \
Manually edit json -> JSON for all variable names
all: checkdeps download build
# go-bindata generates go source from any data file.
checkdeps:
@go get -u github.com/jteeuwen/go-bindata/...
# Download db.json from NodeJS's mime-db project. It is under MIT license.
download: checkdeps
@mkdir db
@wget -nv https://cdn.rawgit.com/jshttp/mime-db/master/db.json -O db/db.json
# After generating db.go, clean up downloaded db.json.
build: download
@go-bindata -pkg contentdb -o db.go db
@rm -fv db/db.json
@rm -rfv db
# Clean auto-generated files and backups.
clean:
@rm -rf db.go
@rm -f *~
-118
View File
@@ -1,118 +0,0 @@
/*
* mime-db: Mime Database, (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 contentdb is a database of file extension to mime content-type.
// Definitions are imported from NodeJS mime-db project under MIT license.
package contentdb
import (
"errors"
"fmt"
"strings"
"sync"
"encoding/json"
)
var (
// Internal lock.
mutex = &sync.Mutex{}
// Make note of initialization.
isInitialized = false
// Database of extension:content-type.
extDB map[string]string
)
// Load JSON data from gobindata and parse them into extDB.
func loadDB() error {
// Structure of JSON data from mime-db project.
type dbEntry struct {
Source string `json:"source"`
Compressible bool `json:"compresible"`
Extensions []string `json:"extensions"`
}
// Access embedded "db.json" inside go-bindata.
jsonDB, e := Asset("db/db.json")
if e != nil {
return e
}
// Convert db.json into go's typed structure.
db := make(map[string]dbEntry)
if e := json.Unmarshal(jsonDB, &db); e != nil {
return e
}
// Generate a new database from mime-db.
for key, val := range db {
if len(val.Extensions) > 0 {
/* Denormalize - each extension has its own
unique content-type now. Looks will be fast. */
for _, ext := range val.Extensions {
/* Single extension type may map to
multiple content-types. In that case,
simply prefer the longest content-type
to maintain some level of
consistency. Only guarantee is,
whatever content type is assigned, it
is appropriate and valid type. */
if strings.Compare(extDB[ext], key) < 0 {
extDB[ext] = key
}
}
}
}
return nil
}
// Init initializes contentdb for lookups. JSON structure is parsed into a simple map of extension and content-type.
func Init() error {
mutex.Lock()
defer mutex.Unlock()
if !isInitialized {
var e error
extDB = make(map[string]string)
if !isInitialized {
e = loadDB()
}
isInitialized = true
return e
}
return nil
}
// Lookup returns matching content-type for known types of file extensions.
func Lookup(extension string) (contentType string, e error) {
if !isInitialized {
return "", errors.New("contentdb is not initialized.")
}
return extDB[extension], e
}
// MustLookup returns matching content-type for known types of file extensions. In case of error, it panics.
func MustLookup(extension string) (contentType string) {
var e error
if contentType, e = Lookup(extension); e != nil {
panic(fmt.Sprintf("Lookup failed: %s\n", e))
}
return contentType
}
-46
View File
@@ -1,46 +0,0 @@
/*
* mime-db: Mime Database, (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 contentdb_test
import (
"testing"
"github.com/minio/minio/pkg/contentdb"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestLookup(c *C) {
// Test initializing.
e := contentdb.Init()
c.Assert(e, IsNil)
// Test MustLookup.
contentType, e := contentdb.Lookup("exe")
c.Assert(e, IsNil)
c.Assert(contentType, Not(Equals), "")
// Test MustLookup.
contentType = contentdb.MustLookup("exe")
c.Assert(contentType, Not(Equals), "")
}
File diff suppressed because one or more lines are too long
+143
View File
@@ -0,0 +1,143 @@
/*
* Minio Cloud Storage, (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 ioutils
import (
"errors"
"io"
"os"
"path/filepath"
"sort"
)
// IsDirEmpty Check if a directory is empty
func IsDirEmpty(dirname string) (status bool, err error) {
f, err := os.Open(dirname)
if err == nil {
defer f.Close()
if _, err = f.Readdirnames(1); err == io.EOF {
status = true
err = nil
}
}
return
}
// FTW walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root.
func FTW(root string, walkFn FTWFunc) error {
info, err := os.Lstat(root)
if err != nil {
return walkFn(root, nil, err)
}
return walk(root, info, walkFn)
}
// byName implements sort.Interface for sorting os.FileInfo list.
type byName []os.FileInfo
func (f byName) Len() int { return len(f) }
func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
func (f byName) Less(i, j int) bool {
n1 := f[i].Name()
if f[i].IsDir() {
n1 = n1 + string(os.PathSeparator)
}
n2 := f[j].Name()
if f[i].IsDir() {
n2 = n2 + string(os.PathSeparator)
}
return n1 < n2
}
// readDir reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDir(dirname string) (fi []os.FileInfo, err error) {
f, err := os.Open(dirname)
if err == nil {
defer f.Close()
if fi, err = f.Readdir(-1); fi != nil {
sort.Sort(byName(fi))
}
}
return
}
// FTWFunc 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 FTWFunc func(path string, info os.FileInfo, err 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")
// ErrDirNotEmpty is used to throw error on directories which have atleast one regular
// file or a symlink left
var ErrDirNotEmpty = errors.New("directory not empty")
// walk recursively descends path, calling walkFn.
func walk(path string, info os.FileInfo, walkFn FTWFunc) error {
err := walkFn(path, info, nil)
if err != nil {
if info.Mode().IsDir() && err == ErrSkipDir {
return nil
}
if info.Mode().IsRegular() && err == ErrSkipFile {
return nil
}
return err
}
if !info.IsDir() {
return nil
}
fis, err := readDir(path)
if err != nil {
return walkFn(path, info, err)
}
for _, fileInfo := range fis {
filename := filepath.Join(path, fileInfo.Name())
if err != nil {
if err := walkFn(filename, fileInfo, err); err != nil && err != ErrSkipDir && err != ErrSkipFile {
return err
}
} else {
err = walk(filename, fileInfo, walkFn)
if err != nil {
if err == ErrSkipDir || err == ErrSkipFile {
return nil
}
return err
}
}
}
return nil
}
@@ -1,5 +1,5 @@
/*
* Minio Cloud Storage, (C) 2015 Minio, Inc.
* Minio Cloud Storage, (C) 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.
@@ -14,12 +14,14 @@
* limitations under the License.
*/
package user_test
package ioutils_test
import (
"io/ioutil"
"os"
"testing"
"github.com/minio/minio/pkg/user"
"github.com/minio/minio/pkg/ioutils"
. "gopkg.in/check.v1"
)
@@ -30,12 +32,12 @@ type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestUser(c *C) {
_, err := user.Current()
func (s *MySuite) TestIoutils(c *C) {
path, err := ioutil.TempDir(os.TempDir(), "minio-ioutils_test")
c.Assert(err, IsNil)
}
defer os.RemoveAll(path)
func (s *MySuite) TestHomeDir(c *C) {
_, err := user.HomeDir()
status, err := ioutils.IsDirEmpty(path)
c.Assert(err, IsNil)
c.Assert(status, Equals, true)
}

Some files were not shown because too many files have changed in this diff Show More