<commit_before>// Copyright 2019 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package prog

import (
	"bytes"
	"fmt"
	"math/rand"
	"sort"
	"testing"

	"github.com/google/go-cmp/cmp"
)

func TestRotationResourceless(t *testing.T) {
	target, rs, _ := initRandomTargetTest(t, "test", "64")
	calls := map[*Syscall]bool{
		target.SyscallMap["test$int"]: true,
	}
	got := MakeRotator(target, calls, rand.New(rs)).Select()
	if diff := cmp.Diff(calls, got); diff != "" {
		t.Fatal(diff)
	}
}

func TestRotationRandom(t *testing.T) {
	target, rs, _ := initTest(t)
	for _, ncalls := range []int{10, 100, 1000, 1e9} {
		ncalls := ncalls
		rnd := rand.New(rand.NewSource(rs.Int63()))
		t.Run(fmt.Sprint(ncalls), func(t *testing.T) {
			t.Parallel()
			calls0 := selectCalls(target, rnd, ncalls)
			calls := MakeRotator(target, calls0, rnd).Select()
			for call := range calls {
				if !calls0[call] {
					t.Errorf("selected disabled syscall %v", call.Name)
				}
			}
			buf := new(bytes.Buffer)
			var array []*Syscall
			for call := range calls {
				array = append(array, call)
			}
			sort.Slice(array, func(i, j int) bool {
				return array[i].Name < array[j].Name
			})
			for _, call := range array {
				fmt.Fprintf(buf, "%v\n", call.Name)
			}
			t.Logf("calls %v->%v:\n%s", len(calls0), len(calls), buf.Bytes())
		})
	}
}

func TestRotationCoverage(t *testing.T) {
	target, rs, _ := initTest(t)
	calls := make(map[*Syscall]bool)
	counters := make(map[string]int)
	for _, call := range target.Syscalls {
		calls[call] = true
		counters[call.Name] = 0
	}
	rotator := MakeRotator(target, calls, rand.New(rs))
	for iter := 0; iter < 2e3; iter++ {
		for call := range rotator.Select() {
			counters[call.Name]++
		}
	}
	type pair struct {
		name  string
		count int
	}
	var pairs []pair
	remain := len(counters)
	for name, count := range counters {
		pairs = append(pairs, pair{name, count})
		if count != 0 {
			remain--
		}
	}
	sort.Slice(pairs, func(i, j int) bool {
		if pairs[i].count != pairs[j].count {
			return pairs[i].count > pairs[j].count
		}
		return pairs[i].name < pairs[j].name
	})
	for i, pair := range pairs {
		t.Logf("# %4d: % 4d %v", i, pair.count, pair.name)
	}
	if remain != 0 {
		t.Fatalf("uncovered syscalls: %v", remain)
	}
}

func selectCalls(target *Target, rnd *rand.Rand, ncalls int) map[*Syscall]bool {
retry:
	calls := make(map[*Syscall]bool)
	for _, call := range target.Syscalls {
		calls[call] = true
	}
	for {
		for {
			remove := 0
			switch {
			case len(calls) > ncalls+1000:
				remove = 100
			case len(calls) > ncalls+50:
				remove = 20
			case len(calls) > ncalls:
				remove = 1
			default:
				return calls
			}
			var array []*Syscall
			for call := range calls {
				array = append(array, call)
			}
			sort.Slice(array, func(i, j int) bool {
				return array[i].ID < array[j].ID
			})
			rnd.Shuffle(len(calls), func(i, j int) {
				array[i], array[j] = array[j], array[i]
			})
			for _, call := range array[:remove] {
				delete(calls, call)
			}
			calls, _ = target.transitivelyEnabled(calls)
			if len(calls) == 0 {
				goto retry
			}
		}
	}
}

func TestRotationDeterminism(t *testing.T) {
	target, rs, _ := initTest(t)
	calls := make(map[*Syscall]bool)
	for _, call := range target.Syscalls {
		calls[call] = true
	}
	seed := rs.Int63()
	rnd0 := rand.New(rand.NewSource(seed))
	calls0 := MakeRotator(target, calls, rnd0).Select()
	rnd1 := rand.New(rand.NewSource(seed))
	calls1 := MakeRotator(target, calls, rnd1).Select()
	if diff := cmp.Diff(calls0, calls1); diff != "" {
		t.Fatal(diff)
	}
}
<commit_msg>prog: make TestRotationCoverage test more robust<commit_after>// Copyright 2019 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package prog

import (
	"bytes"
	"fmt"
	"math/rand"
	"sort"
	"testing"

	"github.com/google/go-cmp/cmp"
)

func TestRotationResourceless(t *testing.T) {
	target, rs, _ := initRandomTargetTest(t, "test", "64")
	calls := map[*Syscall]bool{
		target.SyscallMap["test$int"]: true,
	}
	got := MakeRotator(target, calls, rand.New(rs)).Select()
	if diff := cmp.Diff(calls, got); diff != "" {
		t.Fatal(diff)
	}
}

func TestRotationRandom(t *testing.T) {
	target, rs, _ := initTest(t)
	for _, ncalls := range []int{10, 100, 1000, 1e9} {
		ncalls := ncalls
		rnd := rand.New(rand.NewSource(rs.Int63()))
		t.Run(fmt.Sprint(ncalls), func(t *testing.T) {
			t.Parallel()
			calls0 := selectCalls(target, rnd, ncalls)
			calls := MakeRotator(target, calls0, rnd).Select()
			for call := range calls {
				if !calls0[call] {
					t.Errorf("selected disabled syscall %v", call.Name)
				}
			}
			buf := new(bytes.Buffer)
			var array []*Syscall
			for call := range calls {
				array = append(array, call)
			}
			sort.Slice(array, func(i, j int) bool {
				return array[i].Name < array[j].Name
			})
			for _, call := range array {
				fmt.Fprintf(buf, "%v\n", call.Name)
			}
			t.Logf("calls %v->%v:\n%s", len(calls0), len(calls), buf.Bytes())
		})
	}
}

func TestRotationCoverage(t *testing.T) {
	target, rs, _ := initTest(t)
	calls := make(map[*Syscall]bool)
	counters := make(map[string]int)
	for _, call := range target.Syscalls {
		calls[call] = true
		counters[call.Name] = 0
	}
	rotator := MakeRotator(target, calls, rand.New(rs))
nextIter:
	for iter := 0; iter < 1e4; iter++ {
		for call := range rotator.Select() {
			counters[call.Name]++
		}
		for _, count := range counters {
			if count == 0 {
				continue nextIter
			}
		}
		break
	}
	type pair struct {
		name  string
		count int
	}
	var pairs []pair
	remain := len(counters)
	for name, count := range counters {
		pairs = append(pairs, pair{name, count})
		if count != 0 {
			remain--
		}
	}
	sort.Slice(pairs, func(i, j int) bool {
		if pairs[i].count != pairs[j].count {
			return pairs[i].count > pairs[j].count
		}
		return pairs[i].name < pairs[j].name
	})
	for i, pair := range pairs {
		t.Logf("# %4d: % 4d %v", i, pair.count, pair.name)
	}
	if remain != 0 {
		t.Fatalf("uncovered syscalls: %v", remain)
	}
}

func selectCalls(target *Target, rnd *rand.Rand, ncalls int) map[*Syscall]bool {
retry:
	calls := make(map[*Syscall]bool)
	for _, call := range target.Syscalls {
		calls[call] = true
	}
	for {
		for {
			remove := 0
			switch {
			case len(calls) > ncalls+1000:
				remove = 100
			case len(calls) > ncalls+50:
				remove = 20
			case len(calls) > ncalls:
				remove = 1
			default:
				return calls
			}
			var array []*Syscall
			for call := range calls {
				array = append(array, call)
			}
			sort.Slice(array, func(i, j int) bool {
				return array[i].ID < array[j].ID
			})
			rnd.Shuffle(len(calls), func(i, j int) {
				array[i], array[j] = array[j], array[i]
			})
			for _, call := range array[:remove] {
				delete(calls, call)
			}
			calls, _ = target.transitivelyEnabled(calls)
			if len(calls) == 0 {
				goto retry
			}
		}
	}
}

func TestRotationDeterminism(t *testing.T) {
	target, rs, _ := initTest(t)
	calls := make(map[*Syscall]bool)
	for _, call := range target.Syscalls {
		calls[call] = true
	}
	seed := rs.Int63()
	rnd0 := rand.New(rand.NewSource(seed))
	calls0 := MakeRotator(target, calls, rnd0).Select()
	rnd1 := rand.New(rand.NewSource(seed))
	calls1 := MakeRotator(target, calls, rnd1).Select()
	if diff := cmp.Diff(calls0, calls1); diff != "" {
		t.Fatal(diff)
	}
}
<|endoftext|>


<commit_before>package v1payload

//WorkloadSummary is a smaller representation of a workload
type WorkloadSummary struct {
	ProjectID      string `json:"project_id"`
	WorkloadID     string `json:"workload_id"`
	QueueURL       string `json:"queue_url"`
	Image          string `json:"image"`
	Instances      int    `json:"instances"`
	InputDatasetID string `json:"input_dataset_id"`
}

//ListWorkloadsInput is input for workload listing
type ListWorkloadsInput struct {
	ProjectID string `json:"project_id" valid:"required"`
}

//ListWorkloadsOutput is output for workload listing
type ListWorkloadsOutput struct {
	Workloads []*WorkloadSummary
}

//DescribeWorkloadInput is input for getting workload information
type DescribeWorkloadInput struct {
	ProjectID  string `json:"project_id" valid:"required"`
	WorkloadID string `json:"workload_id"`
}

//TaskStatus represents the status of a task
type TaskStatus string

//DescribeWorkloadOutput is output for getting workload information
type DescribeWorkloadOutput struct {
	WorkloadSummary
	TaskCount map[TaskStatus]int `json:"task_count"`
	Env       map[string]string  `json:"env"`
}

//StartWorkloadInput is input for workload creation
type CreateWorkloadInput struct {
	ProjectID      string            `json:"project_id" valid:"required"`
	Image          string            `json:"image" valid:"required"`
	Instances      int               `json:"instances" valid:"required"`
	InputDatasetID string            `json:"input_dataset_id"`
	UseCuteur      bool              `json:"use_cuteur" valid:"required"`
	Env            map[string]string `json:"env"`
}

//StartWorkloadOutput is output for workload creation
type CreateWorkloadOutput struct {
	WorkloadSummary
}

//StopWorkloadInput is input for workload deletion
type StopWorkloadInput struct {
	ProjectID  string `json:"project_id" valid:"required"`
	WorkloadID string `json:"workload_id" valid:"required"`
}

//StopWorkloadOutput is output for workload deletion
type StopWorkloadOutput struct{}
<commit_msg>Fix use_cutuer<commit_after>package v1payload

//WorkloadSummary is a smaller representation of a workload
type WorkloadSummary struct {
	ProjectID      string `json:"project_id"`
	WorkloadID     string `json:"workload_id"`
	QueueURL       string `json:"queue_url"`
	Image          string `json:"image"`
	Instances      int    `json:"instances"`
	InputDatasetID string `json:"input_dataset_id"`
}

//ListWorkloadsInput is input for workload listing
type ListWorkloadsInput struct {
	ProjectID string `json:"project_id" valid:"required"`
}

//ListWorkloadsOutput is output for workload listing
type ListWorkloadsOutput struct {
	Workloads []*WorkloadSummary
}

//DescribeWorkloadInput is input for getting workload information
type DescribeWorkloadInput struct {
	ProjectID  string `json:"project_id" valid:"required"`
	WorkloadID string `json:"workload_id"`
}

//TaskStatus represents the status of a task
type TaskStatus string

//DescribeWorkloadOutput is output for getting workload information
type DescribeWorkloadOutput struct {
	WorkloadSummary
	TaskCount map[TaskStatus]int `json:"task_count"`
	Env       map[string]string  `json:"env"`
}

//StartWorkloadInput is input for workload creation
type CreateWorkloadInput struct {
	ProjectID      string            `json:"project_id" valid:"required"`
	Image          string            `json:"image" valid:"required"`
	Instances      int               `json:"instances" valid:"required"`
	InputDatasetID string            `json:"input_dataset_id"`
	UseCuteur      bool              `json:"use_cuteur"`
	Env            map[string]string `json:"env"`
}

//StartWorkloadOutput is output for workload creation
type CreateWorkloadOutput struct {
	WorkloadSummary
}

//StopWorkloadInput is input for workload deletion
type StopWorkloadInput struct {
	ProjectID  string `json:"project_id" valid:"required"`
	WorkloadID string `json:"workload_id" valid:"required"`
}

//StopWorkloadOutput is output for workload deletion
type StopWorkloadOutput struct{}
<|endoftext|>


<commit_before>/*
 * This file is part of the KubeVirt project
 *
 * 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.
 *
 * Copyright 2018 Red Hat, Inc.
 * Copyright 2018 The Kubernetes Authors.
 *
 */

package kubecli

import (
	"flag"
	"os"
	"sync"

	secv1 "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
	"github.com/spf13/pflag"
	extclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/client-go/discovery"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	restclient "k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"

	v1 "kubevirt.io/client-go/api/v1"
	cdiclient "kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned"
	k8ssnapshotclient "kubevirt.io/client-go/generated/external-snapshotter/clientset/versioned"
	generatedclient "kubevirt.io/client-go/generated/kubevirt/clientset/versioned"
	networkclient "kubevirt.io/client-go/generated/network-attachment-definition-client/clientset/versioned"
	promclient "kubevirt.io/client-go/generated/prometheus-operator/clientset/versioned"
)

var (
	kubeconfig string
	master     string
)

var virtclient KubevirtClient
var once sync.Once

// Init adds the default `kubeconfig` and `master` flags. It is not added by default to allow integration into
// the different controller generators which normally add these flags too.
func Init() {
	if flag.CommandLine.Lookup("kubeconfig") == nil {
		flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
	}
	if flag.CommandLine.Lookup("master") == nil {
		flag.StringVar(&master, "master", "", "master url")
	}
}

func FlagSet() *flag.FlagSet {
	set := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	set.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
	set.StringVar(&master, "master", "", "master url")
	return set
}

func GetKubevirtSubresourceClientFromFlags(master string, kubeconfig string) (KubevirtClient, error) {
	config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
	if err != nil {
		return nil, err
	}

	config.GroupVersion = &v1.SubresourceStorageGroupVersion
	config.NegotiatedSerializer = serializer.WithoutConversionCodecFactory{CodecFactory: scheme.Codecs}
	config.APIPath = "/apis"
	config.ContentType = runtime.ContentTypeJSON

	restClient, err := rest.RESTClientFor(config)
	if err != nil {
		return nil, err
	}

	coreClient, err := kubernetes.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	generatedKubeVirtClient, err := generatedclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	cdiClient, err := cdiclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	networkClient, err := networkclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	extensionsClient, err := extclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	secClient, err := secv1.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
	if err != nil {
		return nil, err
	}

	prometheusClient, err := promclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	snapshotClient, err := k8ssnapshotclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	dynamicClient, err := dynamic.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	return &kubevirt{
		master,
		kubeconfig,
		restClient,
		config,
		generatedKubeVirtClient,
		cdiClient,
		networkClient,
		extensionsClient,
		secClient,
		discoveryClient,
		prometheusClient,
		snapshotClient,
		dynamicClient,
		coreClient,
	}, nil
}

// DefaultClientConfig creates a clientcmd.ClientConfig with the following hierarchy:
//   1.  Use the kubeconfig builder.  The number of merges and overrides here gets a little crazy.  Stay with me.
//       1.  Merge the kubeconfig itself.  This is done with the following hierarchy rules:
//           1.  CommandLineLocation - this parsed from the command line, so it must be late bound.  If you specify this,
//               then no other kubeconfig files are merged.  This file must exist.
//           2.  If $KUBECONFIG is set, then it is treated as a list of files that should be merged.
//	     3.  HomeDirectoryLocation
//           Empty filenames are ignored.  Files with non-deserializable content produced errors.
//           The first file to set a particular value or map key wins and the value or map key is never changed.
//           This means that the first file to set CurrentContext will have its context preserved.  It also means
//           that if two files specify a "red-user", only values from the first file's red-user are used.  Even
//           non-conflicting entries from the second file's "red-user" are discarded.
//       2.  Determine the context to use based on the first hit in this chain
//           1.  command line argument - again, parsed from the command line, so it must be late bound
//           2.  CurrentContext from the merged kubeconfig file
//           3.  Empty is allowed at this stage
//       3.  Determine the cluster info and auth info to use.  At this point, we may or may not have a context.  They
//           are built based on the first hit in this chain.  (run it twice, once for auth, once for cluster)
//           1.  command line argument
//           2.  If context is present, then use the context value
//           3.  Empty is allowed
//       4.  Determine the actual cluster info to use.  At this point, we may or may not have a cluster info.  Build
//           each piece of the cluster info based on the chain:
//           1.  command line argument
//           2.  If cluster info is present and a value for the attribute is present, use it.
//           3.  If you don't have a server location, bail.
//       5.  Auth info is build using the same rules as cluster info, EXCEPT that you can only have one authentication
//           technique per auth info.  The following conditions result in an error:
//           1.  If there are two conflicting techniques specified from the command line, fail.
//           2.  If the command line does not specify one, and the auth info has conflicting techniques, fail.
//           3.  If the command line specifies one and the auth info specifies another, honor the command line technique.
//   2.  Use default values and potentially prompt for auth information
//
//   However, if it appears that we're running in a kubernetes cluster
//   container environment, then run with the auth info kubernetes mounted for
//   us. Specifically:
//     The env vars KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are
//     set, and the file /var/run/secrets/kubernetes.io/serviceaccount/token
//     exists and is not a directory.
// Initially copied from https://github.com/kubernetes/kubernetes/blob/09f321c80bfc9bca63a5530b56d7a1a3ba80ba9b/pkg/kubectl/cmd/util/factory_client_access.go#L174
func DefaultClientConfig(flags *pflag.FlagSet) clientcmd.ClientConfig {
	loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
	// use the standard defaults for this client command
	// DEPRECATED: remove and replace with something more accurate
	loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig

	flags.StringVar(&loadingRules.ExplicitPath, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests.")

	overrides := &clientcmd.ConfigOverrides{ClusterDefaults: clientcmd.ClusterDefaults}

	flagNames := clientcmd.RecommendedConfigOverrideFlags("")
	// short flagnames are disabled by default.  These are here for compatibility with existing scripts
	flagNames.ClusterOverrideFlags.APIServer.ShortName = "s"

	clientcmd.BindOverrideFlags(overrides, flags, flagNames)
	clientConfig := clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin)

	return clientConfig
}

// this function is defined as a closure so iut could be overwritten by unit tests
var GetKubevirtClientFromClientConfig = func(cmdConfig clientcmd.ClientConfig) (KubevirtClient, error) {
	config, err := cmdConfig.ClientConfig()
	if err != nil {
		return nil, err
	}
	return GetKubevirtClientFromRESTConfig(config)

}

func GetKubevirtClientFromRESTConfig(config *rest.Config) (KubevirtClient, error) {
	config.GroupVersion = &v1.StorageGroupVersion
	config.NegotiatedSerializer = serializer.WithoutConversionCodecFactory{CodecFactory: v1.Codecs}
	config.APIPath = "/apis"
	config.ContentType = runtime.ContentTypeJSON
	if config.UserAgent == "" {
		config.UserAgent = restclient.DefaultKubernetesUserAgent()
	}

	restClient, err := rest.RESTClientFor(config)
	if err != nil {
		return nil, err
	}

	coreClient, err := kubernetes.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	generatedKubeVirtClient, err := generatedclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	cdiClient, err := cdiclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	networkClient, err := networkclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	extensionsClient, err := extclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	secClient, err := secv1.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
	if err != nil {
		return nil, err
	}

	prometheusClient, err := promclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	snapshotClient, err := k8ssnapshotclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	dynamicClient, err := dynamic.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	return &kubevirt{
		master,
		kubeconfig,
		restClient,
		config,
		generatedKubeVirtClient,
		cdiClient,
		networkClient,
		extensionsClient,
		secClient,
		discoveryClient,
		prometheusClient,
		snapshotClient,
		dynamicClient,
		coreClient,
	}, nil
}

func GetKubevirtClientFromFlags(master string, kubeconfig string) (KubevirtClient, error) {
	config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
	if err != nil {
		return nil, err
	}
	return GetKubevirtClientFromRESTConfig(config)
}

func GetKubevirtClient() (KubevirtClient, error) {
	var err error
	once.Do(func() {
		virtclient, err = GetKubevirtClientFromFlags(master, kubeconfig)
	})
	return virtclient, err
}

func GetKubevirtSubresourceClient() (KubevirtClient, error) {
	return GetKubevirtSubresourceClientFromFlags(master, kubeconfig)
}

func GetConfig() (*restclient.Config, error) {
	return clientcmd.BuildConfigFromFlags(master, kubeconfig)
}

func GetKubevirtClientConfig() (*rest.Config, error) {
	config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
	if err != nil {
		return nil, err
	}
	return config, nil
}
<commit_msg>make shallow copy of config parameter<commit_after>/*
 * This file is part of the KubeVirt project
 *
 * 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.
 *
 * Copyright 2018 Red Hat, Inc.
 * Copyright 2018 The Kubernetes Authors.
 *
 */

package kubecli

import (
	"flag"
	"os"
	"sync"

	secv1 "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
	"github.com/spf13/pflag"
	extclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/client-go/discovery"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	restclient "k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"

	v1 "kubevirt.io/client-go/api/v1"
	cdiclient "kubevirt.io/client-go/generated/containerized-data-importer/clientset/versioned"
	k8ssnapshotclient "kubevirt.io/client-go/generated/external-snapshotter/clientset/versioned"
	generatedclient "kubevirt.io/client-go/generated/kubevirt/clientset/versioned"
	networkclient "kubevirt.io/client-go/generated/network-attachment-definition-client/clientset/versioned"
	promclient "kubevirt.io/client-go/generated/prometheus-operator/clientset/versioned"
)

var (
	kubeconfig string
	master     string
)

var virtclient KubevirtClient
var once sync.Once

// Init adds the default `kubeconfig` and `master` flags. It is not added by default to allow integration into
// the different controller generators which normally add these flags too.
func Init() {
	if flag.CommandLine.Lookup("kubeconfig") == nil {
		flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
	}
	if flag.CommandLine.Lookup("master") == nil {
		flag.StringVar(&master, "master", "", "master url")
	}
}

func FlagSet() *flag.FlagSet {
	set := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	set.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
	set.StringVar(&master, "master", "", "master url")
	return set
}

func GetKubevirtSubresourceClientFromFlags(master string, kubeconfig string) (KubevirtClient, error) {
	config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
	if err != nil {
		return nil, err
	}

	config.GroupVersion = &v1.SubresourceStorageGroupVersion
	config.NegotiatedSerializer = serializer.WithoutConversionCodecFactory{CodecFactory: scheme.Codecs}
	config.APIPath = "/apis"
	config.ContentType = runtime.ContentTypeJSON

	restClient, err := rest.RESTClientFor(config)
	if err != nil {
		return nil, err
	}

	coreClient, err := kubernetes.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	generatedKubeVirtClient, err := generatedclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	cdiClient, err := cdiclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	networkClient, err := networkclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	extensionsClient, err := extclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	secClient, err := secv1.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
	if err != nil {
		return nil, err
	}

	prometheusClient, err := promclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	snapshotClient, err := k8ssnapshotclient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	dynamicClient, err := dynamic.NewForConfig(config)
	if err != nil {
		return nil, err
	}

	return &kubevirt{
		master,
		kubeconfig,
		restClient,
		config,
		generatedKubeVirtClient,
		cdiClient,
		networkClient,
		extensionsClient,
		secClient,
		discoveryClient,
		prometheusClient,
		snapshotClient,
		dynamicClient,
		coreClient,
	}, nil
}

// DefaultClientConfig creates a clientcmd.ClientConfig with the following hierarchy:
//   1.  Use the kubeconfig builder.  The number of merges and overrides here gets a little crazy.  Stay with me.
//       1.  Merge the kubeconfig itself.  This is done with the following hierarchy rules:
//           1.  CommandLineLocation - this parsed from the command line, so it must be late bound.  If you specify this,
//               then no other kubeconfig files are merged.  This file must exist.
//           2.  If $KUBECONFIG is set, then it is treated as a list of files that should be merged.
//	     3.  HomeDirectoryLocation
//           Empty filenames are ignored.  Files with non-deserializable content produced errors.
//           The first file to set a particular value or map key wins and the value or map key is never changed.
//           This means that the first file to set CurrentContext will have its context preserved.  It also means
//           that if two files specify a "red-user", only values from the first file's red-user are used.  Even
//           non-conflicting entries from the second file's "red-user" are discarded.
//       2.  Determine the context to use based on the first hit in this chain
//           1.  command line argument - again, parsed from the command line, so it must be late bound
//           2.  CurrentContext from the merged kubeconfig file
//           3.  Empty is allowed at this stage
//       3.  Determine the cluster info and auth info to use.  At this point, we may or may not have a context.  They
//           are built based on the first hit in this chain.  (run it twice, once for auth, once for cluster)
//           1.  command line argument
//           2.  If context is present, then use the context value
//           3.  Empty is allowed
//       4.  Determine the actual cluster info to use.  At this point, we may or may not have a cluster info.  Build
//           each piece of the cluster info based on the chain:
//           1.  command line argument
//           2.  If cluster info is present and a value for the attribute is present, use it.
//           3.  If you don't have a server location, bail.
//       5.  Auth info is build using the same rules as cluster info, EXCEPT that you can only have one authentication
//           technique per auth info.  The following conditions result in an error:
//           1.  If there are two conflicting techniques specified from the command line, fail.
//           2.  If the command line does not specify one, and the auth info has conflicting techniques, fail.
//           3.  If the command line specifies one and the auth info specifies another, honor the command line technique.
//   2.  Use default values and potentially prompt for auth information
//
//   However, if it appears that we're running in a kubernetes cluster
//   container environment, then run with the auth info kubernetes mounted for
//   us. Specifically:
//     The env vars KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are
//     set, and the file /var/run/secrets/kubernetes.io/serviceaccount/token
//     exists and is not a directory.
// Initially copied from https://github.com/kubernetes/kubernetes/blob/09f321c80bfc9bca63a5530b56d7a1a3ba80ba9b/pkg/kubectl/cmd/util/factory_client_access.go#L174
func DefaultClientConfig(flags *pflag.FlagSet) clientcmd.ClientConfig {
	loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
	// use the standard defaults for this client command
	// DEPRECATED: remove and replace with something more accurate
	loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig

	flags.StringVar(&loadingRules.ExplicitPath, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests.")

	overrides := &clientcmd.ConfigOverrides{ClusterDefaults: clientcmd.ClusterDefaults}

	flagNames := clientcmd.RecommendedConfigOverrideFlags("")
	// short flagnames are disabled by default.  These are here for compatibility with existing scripts
	flagNames.ClusterOverrideFlags.APIServer.ShortName = "s"

	clientcmd.BindOverrideFlags(overrides, flags, flagNames)
	clientConfig := clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin)

	return clientConfig
}

// this function is defined as a closure so iut could be overwritten by unit tests
var GetKubevirtClientFromClientConfig = func(cmdConfig clientcmd.ClientConfig) (KubevirtClient, error) {
	config, err := cmdConfig.ClientConfig()
	if err != nil {
		return nil, err
	}
	return GetKubevirtClientFromRESTConfig(config)

}

func GetKubevirtClientFromRESTConfig(config *rest.Config) (KubevirtClient, error) {
	shallowCopy := *config
	shallowCopy.GroupVersion = &v1.StorageGroupVersion
	shallowCopy.NegotiatedSerializer = serializer.WithoutConversionCodecFactory{CodecFactory: v1.Codecs}
	shallowCopy.APIPath = "/apis"
	shallowCopy.ContentType = runtime.ContentTypeJSON
	if config.UserAgent == "" {
		config.UserAgent = restclient.DefaultKubernetesUserAgent()
	}

	restClient, err := rest.RESTClientFor(&shallowCopy)
	if err != nil {
		return nil, err
	}

	coreClient, err := kubernetes.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	generatedKubeVirtClient, err := generatedclient.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	cdiClient, err := cdiclient.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	networkClient, err := networkclient.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	extensionsClient, err := extclient.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	secClient, err := secv1.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	discoveryClient, err := discovery.NewDiscoveryClientForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	prometheusClient, err := promclient.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	snapshotClient, err := k8ssnapshotclient.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	dynamicClient, err := dynamic.NewForConfig(&shallowCopy)
	if err != nil {
		return nil, err
	}

	return &kubevirt{
		master,
		kubeconfig,
		restClient,
		&shallowCopy,
		generatedKubeVirtClient,
		cdiClient,
		networkClient,
		extensionsClient,
		secClient,
		discoveryClient,
		prometheusClient,
		snapshotClient,
		dynamicClient,
		coreClient,
	}, nil
}

func GetKubevirtClientFromFlags(master string, kubeconfig string) (KubevirtClient, error) {
	config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
	if err != nil {
		return nil, err
	}
	return GetKubevirtClientFromRESTConfig(config)
}

func GetKubevirtClient() (KubevirtClient, error) {
	var err error
	once.Do(func() {
		virtclient, err = GetKubevirtClientFromFlags(master, kubeconfig)
	})
	return virtclient, err
}

func GetKubevirtSubresourceClient() (KubevirtClient, error) {
	return GetKubevirtSubresourceClientFromFlags(master, kubeconfig)
}

func GetConfig() (*restclient.Config, error) {
	return clientcmd.BuildConfigFromFlags(master, kubeconfig)
}

func GetKubevirtClientConfig() (*rest.Config, error) {
	config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
	if err != nil {
		return nil, err
	}
	return config, nil
}
<|endoftext|>


<commit_before>package check

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"
	"syscall"
)

var skipDirs = []string{"Godeps", "vendor", "third_party"}

// GoFiles returns a slice of Go filenames
// in a given directory.
func GoFiles(dir string) ([]string, error) {
	var filenames []string
	visit := func(fp string, fi os.FileInfo, err error) error {
		for _, skip := range skipDirs {
			if strings.Contains(fp, skip) {
				return nil
			}
		}
		if err != nil {
			fmt.Println(err) // can't walk here,
			return nil       // but continue walking elsewhere
		}
		if fi.IsDir() {
			return nil // not a file.  ignore.
		}
		ext := filepath.Ext(fi.Name())
		if ext == ".go" {
			filenames = append(filenames, fp)
		}
		return nil
	}

	err := filepath.Walk(dir, visit)

	return filenames, err
}

// lineCount returns the number of lines in a given file
func lineCount(filepath string) (int, error) {
	out, err := exec.Command("wc", "-l", filepath).Output()
	if err != nil {
		return 0, err
	}
	// wc output is like: 999 filename.go
	count, err := strconv.Atoi(strings.Split(strings.TrimSpace(string(out)), " ")[0])
	if err != nil {
		return 0, err
	}

	return count, nil
}

// Error contains the line number and the reason for
// an error output from a command
type Error struct {
	LineNumber  int    `json:"line_number"`
	ErrorString string `json:"error_string"`
}

// FileSummary contains the filename, location of the file
// on GitHub, and all of the errors related to the file
type FileSummary struct {
	Filename string  `json:"filename"`
	FileURL  string  `json:"file_url"`
	Errors   []Error `json:"errors"`
}

// ByFilename implements sort.Interface for []Person based on
// the Age field.
type ByFilename []FileSummary

func (a ByFilename) Len() int           { return len(a) }
func (a ByFilename) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByFilename) Less(i, j int) bool { return a[i].Filename < a[j].Filename }

func getFileSummary(filename, dir, cmd, out string) (FileSummary, error) {
	filename = strings.TrimPrefix(filename, "repos/src")
	githubLink := strings.TrimPrefix(dir, "repos/src")
	fileURL := "https://" + strings.TrimPrefix(dir, "repos/src/") + "/blob/master" + strings.TrimPrefix(filename, githubLink)
	fs := FileSummary{
		Filename: filename,
		FileURL:  fileURL,
	}
	split := strings.Split(string(out), "\n")
	for _, sp := range split[0 : len(split)-1] {
		msg := sp
		var loc string
		if cmd == "gocyclo" {
			s := strings.SplitN(sp, " ", 2)
			loc = s[1]
		} else {
			s := strings.SplitN(sp, ": ", 2)
			loc = s[0]
			if len(s) > 1 {
				msg = s[1]
			}
		}

		e := Error{ErrorString: msg}
		switch cmd {
		case "golint", "gocyclo", "vet":
			ls := strings.Split(loc, ":")
			if len(ls) >= 1 && strings.Contains(loc, filename) {
				idx := len(ls) - 2
				if cmd == "vet" {
					idx = 1
				}
				ln, err := strconv.Atoi(ls[idx])
				if err != nil {
					return fs, err
				}
				e.LineNumber = ln
			}
		}

		fs.Errors = append(fs.Errors, e)
	}

	return fs, nil
}

// GoTool runs a given go command (for example gofmt, go tool vet)
// on a directory
func GoTool(dir string, filenames, command []string) (float64, []FileSummary, error) {
	var failed = []FileSummary{}
	for _, fi := range filenames {
		params := command[1:]
		params = append(params, fi)

		cmd := exec.Command(command[0], params...)
		stdout, err := cmd.StdoutPipe()
		if err != nil {
			return 0, []FileSummary{}, err
		}

		stderr, err := cmd.StderrPipe()
		if err != nil {
			return 0, []FileSummary{}, err
		}

		err = cmd.Start()
		if err != nil {
			return 0, []FileSummary{}, err
		}

		out, err := ioutil.ReadAll(stdout)
		if err != nil {
			return 0, []FileSummary{}, err
		}

		errout, err := ioutil.ReadAll(stderr)
		if err != nil {
			return 0, []FileSummary{}, err
		}

		if string(out) != "" {
			fs, err := getFileSummary(fi, dir, command[0], string(out))
			if err != nil {
				return 0, []FileSummary{}, err
			}
			failed = append(failed, fs)
		}

		// go vet logs to stderr
		if string(errout) != "" {
			cmd := command[0]
			if reflect.DeepEqual(command, []string{"go", "tool", "vet"}) {
				cmd = "vet"
			}
			fs, err := getFileSummary(fi, dir, cmd, string(errout))
			if err != nil {
				return 0, []FileSummary{}, err
			}
			failed = append(failed, fs)
		}

		err = cmd.Wait()
		if exitErr, ok := err.(*exec.ExitError); ok {
			// The program has exited with an exit code != 0

			if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
				// some commands exit 1 when files fail to pass (for example go vet)
				if status.ExitStatus() != 1 {
					return 0, failed, err
					// return 0, Error{}, err
				}
			}
		}

	}

	if len(filenames) == 1 {
		lc, err := lineCount(filenames[0])
		if err != nil {
			return 0, failed, err
		}

		var errors int
		if len(failed) != 0 {
			errors = len(failed[0].Errors)
		}

		return float64(lc-errors) / float64(lc), failed, nil
	}

	return float64(len(filenames)-len(failed)) / float64(len(filenames)), failed, nil
}
<commit_msg>check len s before assigning loc for gocyclo<commit_after>package check

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"
	"syscall"
)

var skipDirs = []string{"Godeps", "vendor", "third_party"}

// GoFiles returns a slice of Go filenames
// in a given directory.
func GoFiles(dir string) ([]string, error) {
	var filenames []string
	visit := func(fp string, fi os.FileInfo, err error) error {
		for _, skip := range skipDirs {
			if strings.Contains(fp, skip) {
				return nil
			}
		}
		if err != nil {
			fmt.Println(err) // can't walk here,
			return nil       // but continue walking elsewhere
		}
		if fi.IsDir() {
			return nil // not a file.  ignore.
		}
		ext := filepath.Ext(fi.Name())
		if ext == ".go" {
			filenames = append(filenames, fp)
		}
		return nil
	}

	err := filepath.Walk(dir, visit)

	return filenames, err
}

// lineCount returns the number of lines in a given file
func lineCount(filepath string) (int, error) {
	out, err := exec.Command("wc", "-l", filepath).Output()
	if err != nil {
		return 0, err
	}
	// wc output is like: 999 filename.go
	count, err := strconv.Atoi(strings.Split(strings.TrimSpace(string(out)), " ")[0])
	if err != nil {
		return 0, err
	}

	return count, nil
}

// Error contains the line number and the reason for
// an error output from a command
type Error struct {
	LineNumber  int    `json:"line_number"`
	ErrorString string `json:"error_string"`
}

// FileSummary contains the filename, location of the file
// on GitHub, and all of the errors related to the file
type FileSummary struct {
	Filename string  `json:"filename"`
	FileURL  string  `json:"file_url"`
	Errors   []Error `json:"errors"`
}

// ByFilename implements sort.Interface for []Person based on
// the Age field.
type ByFilename []FileSummary

func (a ByFilename) Len() int           { return len(a) }
func (a ByFilename) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByFilename) Less(i, j int) bool { return a[i].Filename < a[j].Filename }

func getFileSummary(filename, dir, cmd, out string) (FileSummary, error) {
	filename = strings.TrimPrefix(filename, "repos/src")
	githubLink := strings.TrimPrefix(dir, "repos/src")
	fileURL := "https://" + strings.TrimPrefix(dir, "repos/src/") + "/blob/master" + strings.TrimPrefix(filename, githubLink)
	fs := FileSummary{
		Filename: filename,
		FileURL:  fileURL,
	}
	split := strings.Split(string(out), "\n")
	for _, sp := range split[0 : len(split)-1] {
		msg := sp
		var loc string
		if cmd == "gocyclo" {
			s := strings.SplitN(sp, " ", 2)
			if len(s) > 1 {
				loc = s[1]
			}
		} else {
			s := strings.SplitN(sp, ": ", 2)
			loc = s[0]
			if len(s) > 1 {
				msg = s[1]
			}
		}

		e := Error{ErrorString: msg}
		switch cmd {
		case "golint", "gocyclo", "vet":
			ls := strings.Split(loc, ":")
			if len(ls) >= 1 && strings.Contains(loc, filename) {
				idx := len(ls) - 2
				if cmd == "vet" {
					idx = 1
				}
				ln, err := strconv.Atoi(ls[idx])
				if err != nil {
					return fs, err
				}
				e.LineNumber = ln
			}
		}

		fs.Errors = append(fs.Errors, e)
	}

	return fs, nil
}

// GoTool runs a given go command (for example gofmt, go tool vet)
// on a directory
func GoTool(dir string, filenames, command []string) (float64, []FileSummary, error) {
	var failed = []FileSummary{}
	for _, fi := range filenames {
		params := command[1:]
		params = append(params, fi)

		cmd := exec.Command(command[0], params...)
		stdout, err := cmd.StdoutPipe()
		if err != nil {
			return 0, []FileSummary{}, err
		}

		stderr, err := cmd.StderrPipe()
		if err != nil {
			return 0, []FileSummary{}, err
		}

		err = cmd.Start()
		if err != nil {
			return 0, []FileSummary{}, err
		}

		out, err := ioutil.ReadAll(stdout)
		if err != nil {
			return 0, []FileSummary{}, err
		}

		errout, err := ioutil.ReadAll(stderr)
		if err != nil {
			return 0, []FileSummary{}, err
		}

		if string(out) != "" {
			fs, err := getFileSummary(fi, dir, command[0], string(out))
			if err != nil {
				return 0, []FileSummary{}, err
			}
			failed = append(failed, fs)
		}

		// go vet logs to stderr
		if string(errout) != "" {
			cmd := command[0]
			if reflect.DeepEqual(command, []string{"go", "tool", "vet"}) {
				cmd = "vet"
			}
			fs, err := getFileSummary(fi, dir, cmd, string(errout))
			if err != nil {
				return 0, []FileSummary{}, err
			}
			failed = append(failed, fs)
		}

		err = cmd.Wait()
		if exitErr, ok := err.(*exec.ExitError); ok {
			// The program has exited with an exit code != 0

			if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
				// some commands exit 1 when files fail to pass (for example go vet)
				if status.ExitStatus() != 1 {
					return 0, failed, err
					// return 0, Error{}, err
				}
			}
		}

	}

	if len(filenames) == 1 {
		lc, err := lineCount(filenames[0])
		if err != nil {
			return 0, failed, err
		}

		var errors int
		if len(failed) != 0 {
			errors = len(failed[0].Errors)
		}

		return float64(lc-errors) / float64(lc), failed, nil
	}

	return float64(len(filenames)-len(failed)) / float64(len(filenames)), failed, nil
}
<|endoftext|>


<commit_before>package cli

import (
	"github.com/docker/go-connections/tlsconfig"
	flag "github.com/hyperhq/hypercli/pkg/mflag"
)

// CommonFlags represents flags that are common to both the client and the daemon.
type CommonFlags struct {
	FlagSet   *flag.FlagSet
	PostParse func()

	Debug      bool
	Hosts      []string
	LogLevel   string
	TLS        bool
	TLSVerify  bool
	TLSOptions *tlsconfig.Options
	TrustKey   string
}

// Command is the struct contains command name and description
type Command struct {
	Name        string
	Description string
}

var dockerCommands = []Command{
	{"attach", "Attach to a running container"},
	//{"build", "Build an image from a Dockerfile"},
	{"commit", "Create a new image from a container's changes"},
	{"config", "Config access key and secret key to Hyper server"},
	//{"cp", "Copy files/folders between a container and the local filesystem"},
	{"create", "Create a new container"},
	//{"diff", "Inspect changes on a container's filesystem"},
	//{"events", "Get real time events from the server"},
	{"exec", "Run a command in a running container"},
	//{"export", "Export a container's filesystem as a tar archive"},
	{"history", "Show the history of an image"},
	{"images", "List images"},
	//{"import", "Import the contents from a tarball to create a filesystem image"},
	{"info", "Display system-wide information"},
	{"inspect", "Return low-level information on a container or image"},
	{"kill", "Kill a running container"},
	{"load", "Load an image from a tar archive"},
	{"login", "Register or log in to a Docker registry"},
	{"logout", "Log out from a Docker registry"},
	{"logs", "Fetch the logs of a container"},
	//{"network", "Manage Hyper.sh networks"},
	//{"pause", "Pause all processes within a container"},
	{"port", "List port mappings or a specific mapping for the CONTAINER"},
	{"ps", "List containers"},
	{"pull", "Pull an image or a repository from a registry"},
	{"push", "Push an image or a repository to a registry"},
	{"rename", "Rename a container"},
	{"restart", "Restart a container"},
	{"rm", "Remove one or more containers"},
	{"rmi", "Remove one or more images"},
	{"run", "Run a command in a new container"},
	//{"save", "Save an image(s) to a tar archive"},
	{"search", "Search the Docker Hub for images"},
	{"start", "Start one or more stopped containers"},
	{"stats", "Display a live stream of container(s) resource usage statistics"},
	{"stop", "Stop a running container"},
	//{"tag", "Tag an image into a repository"},
	//{"top", "Display the running processes of a container"},
	//{"unpause", "Unpause all processes within a container"},
	{"update", "Update resources of one or more containers"},
	{"version", "Show the Hyper.sh version information"},
	{"volume", "Manage Hyper.sh volumes"},
	{"snapshot", "Manage Hyper.sh snapshots"},
	{"fip", "Manage Hyper.sh floating IPs"},
	{"wait", "Block until a container stops, then print its exit code"},
	{"compose", "Define and run multi-container applications with Hyper.sh"},
	{"sg", "Manage security group of Hyper.sh"},
	{"service", "Manage service of Hyper.sh"},
	{"cron", "Manage cron service of Hyper.sh"},
	{"func", "Manage func service of Hyper.sh"},
}

// DockerCommands stores all the docker command
var DockerCommands = make(map[string]Command)

func init() {
	for _, cmd := range dockerCommands {
		DockerCommands[cmd.Name] = cmd
	}
}
<commit_msg>Update load description in hyper-help<commit_after>package cli

import (
	"github.com/docker/go-connections/tlsconfig"
	flag "github.com/hyperhq/hypercli/pkg/mflag"
)

// CommonFlags represents flags that are common to both the client and the daemon.
type CommonFlags struct {
	FlagSet   *flag.FlagSet
	PostParse func()

	Debug      bool
	Hosts      []string
	LogLevel   string
	TLS        bool
	TLSVerify  bool
	TLSOptions *tlsconfig.Options
	TrustKey   string
}

// Command is the struct contains command name and description
type Command struct {
	Name        string
	Description string
}

var dockerCommands = []Command{
	{"attach", "Attach to a running container"},
	//{"build", "Build an image from a Dockerfile"},
	{"commit", "Create a new image from a container's changes"},
	{"config", "Config access key and secret key to Hyper server"},
	//{"cp", "Copy files/folders between a container and the local filesystem"},
	{"create", "Create a new container"},
	//{"diff", "Inspect changes on a container's filesystem"},
	//{"events", "Get real time events from the server"},
	{"exec", "Run a command in a running container"},
	//{"export", "Export a container's filesystem as a tar archive"},
	{"history", "Show the history of an image"},
	{"images", "List images"},
	//{"import", "Import the contents from a tarball to create a filesystem image"},
	{"info", "Display system-wide information"},
	{"inspect", "Return low-level information on a container or image"},
	{"kill", "Kill a running container"},
	{"load", "Load a local image or a tar file"},
	{"login", "Register or log in to a Docker registry"},
	{"logout", "Log out from a Docker registry"},
	{"logs", "Fetch the logs of a container"},
	//{"network", "Manage Hyper.sh networks"},
	//{"pause", "Pause all processes within a container"},
	{"port", "List port mappings or a specific mapping for the CONTAINER"},
	{"ps", "List containers"},
	{"pull", "Pull an image or a repository from a registry"},
	{"push", "Push an image or a repository to a registry"},
	{"rename", "Rename a container"},
	{"restart", "Restart a container"},
	{"rm", "Remove one or more containers"},
	{"rmi", "Remove one or more images"},
	{"run", "Run a command in a new container"},
	//{"save", "Save an image(s) to a tar archive"},
	{"search", "Search the Docker Hub for images"},
	{"start", "Start one or more stopped containers"},
	{"stats", "Display a live stream of container(s) resource usage statistics"},
	{"stop", "Stop a running container"},
	//{"tag", "Tag an image into a repository"},
	//{"top", "Display the running processes of a container"},
	//{"unpause", "Unpause all processes within a container"},
	{"update", "Update resources of one or more containers"},
	{"version", "Show the Hyper.sh version information"},
	{"volume", "Manage Hyper.sh volumes"},
	{"snapshot", "Manage Hyper.sh snapshots"},
	{"fip", "Manage Hyper.sh floating IPs"},
	{"wait", "Block until a container stops, then print its exit code"},
	{"compose", "Define and run multi-container applications with Hyper.sh"},
	{"sg", "Manage security group of Hyper.sh"},
	{"service", "Manage service of Hyper.sh"},
	{"cron", "Manage cron service of Hyper.sh"},
	{"func", "Manage func service of Hyper.sh"},
}

// DockerCommands stores all the docker command
var DockerCommands = make(map[string]Command)

func init() {
	for _, cmd := range dockerCommands {
		DockerCommands[cmd.Name] = cmd
	}
}
<|endoftext|>


<commit_before>package cli

import (
	"fmt"
	"github.com/brightbox/gobrightbox"
	"gopkg.in/alecthomas/kingpin.v2"
	"sort"
	"strings"
)

var (
	defaultImageListFields = []string{"id", "owner", "type", "created", "status", "arch", "name"}
	defaultImageShowFields = []string{"id", "type", "owner", "created_at", "status", "locked", "arch",
		"name", "description", "username", "virtual_size", "disk_size", "public", "compatibility_mode",
		"official", "ancestor_id", "license_name"}
)

type imagesCommand struct {
	*CLIApp
	Id      string
	IdList  []string
	ShowAll bool
	Fields  string
}

func imageFields(i *brightbox.Image) map[string]string {
	owner := i.Owner
	itype := i.SourceType
	if i.Official {
		owner = "brightbox"
		itype = "official"
	}
	name := i.Name
	if i.CompatibilityMode {
		name += " (compat)"
	}
	name += " (" + i.Arch + ")"
	var status string
	if i.Status != "available" {
		status = i.Status
	} else if i.Public {
		status = "public"
	} else {
		status = "private"
	}

	return map[string]string{
		"id":                 i.Id,
		"type":               itype,
		"owner":              owner,
		"created":            i.CreatedAt.Format("2006-01-02"),
		"created_at":         formatTime(&i.CreatedAt),
		"status":             status,
		"locked":             formatBool(i.Locked),
		"arch":               i.Arch,
		"name":               i.Name,
		"description":        i.Description,
		"username":           i.Username,
		"virtual_size":       formatInt(i.VirtualSize),
		"disk_size":          formatInt(i.DiskSize),
		"public":             formatBool(i.Public),
		"compatibility_mode": formatBool(i.CompatibilityMode),
		"official":           formatBool(i.Official),
		"ancestor_id":        i.AncestorId,
		"license_name":       i.LicenseName,
	}
}

type imagesForDisplay []brightbox.Image

func (il imagesForDisplay) Len() int      { return len(il) }
func (il imagesForDisplay) Swap(i, j int) { il[i], il[j] = il[j], il[i] }
func (il imagesForDisplay) Less(i, j int) bool {
	a := il.sortKeys(i)
	b := il.sortKeys(j)
	for e := 0; e < len(a); e++ {
		switch a[e].(type) {
		case string:
			if a[e].(string) != b[e].(string) {
				return a[e].(string) < b[e].(string)
			}
		case int64:
			if a[e].(int64) != b[e].(int64) {
				return a[e].(int64) < b[e].(int64)
			}
		case bool:
			if a[e].(bool) != b[e].(bool) {
				return a[e].(bool) == false && b[e].(bool) == true
			}
		}
	}
	return false
}

func (il imagesForDisplay) sortKeys(i int) []interface{} {
	im := il[i]
	return []interface{}{
		!im.Official,
		im.SourceType == "snapshot",
		im.Name, im.Arch,
		im.Status == "deprecated",
		!im.Public,
		-im.CreatedAt.Unix(),
	}
}

func (l *imagesCommand) list(pc *kingpin.ParseContext) error {
	err := l.Configure()
	if err != nil {
		return err
	}

	// Get the account id in parallel to everything else, we don't need it until
	// later anyway.
	achan := make(chan string)
	go func() {
		achan <- l.accountId()
	}()

	out := new(RowFieldOutput)
	out.Setup(strings.Split(l.Fields, ","))

	images, err := l.Client.Images()
	if err != nil {
		return err
	}
	sortedImages := make(imagesForDisplay, 0, len(images))
	for _, i := range images {
		sortedImages = append(sortedImages, i)
	}
	sort.Sort(sortedImages)

	accountId := <-achan
	out.SendHeader()
	for _, i := range sortedImages {
		if l.ShowAll == false {
			if !i.Official && i.Owner != accountId {
				continue
			}
		}
		if err = out.Write(imageFields(&i)); err != nil {
			return err
		}
	}
	out.Flush()
	return nil
}

func (l *imagesCommand) show(pc *kingpin.ParseContext) error {

	err := l.Configure()
	if err != nil {
		return err
	}
	out := new(ShowFieldOutput)
	out.Setup(strings.Split(l.Fields, ","))

	i, err := l.Client.Image(l.Id)
	if err != nil {
		l.Fatalf(err.Error())
	}
	if err = out.Write(imageFields(i)); err != nil {
		return err
	}
	out.Flush()
	return nil

}

func (l *imagesCommand) destroy(pc *kingpin.ParseContext) error {
	err := l.Configure()
	if err != nil {
		return err
	}
	returnError := false
	for _, id := range l.IdList {
		fmt.Printf("Destroying image %s\n", id)
		err := l.Client.DestroyImage(id)
		if err != nil {
			l.Errorf("%s: %s", err.Error(), id)
			returnError = true
		}
	}
	if returnError {
		return errGeneric
	}
	return nil
}

func configureImagesCommand(app *CLIApp) {
	cmd := imagesCommand{CLIApp: app}
	images := app.Command("images", "Manage server images")
	list := images.Command("list", "List server images").Default().Action(cmd.list)
	list.Flag("fields", "Which fields to display").
		Default(strings.Join(defaultImageListFields, ",")).
		StringVar(&cmd.Fields)
	list.Flag("show-all", "Show all public images from all accounts").Default("false").BoolVar(&cmd.ShowAll)
	show := images.Command("show", "View details of a server image").Action(cmd.show)
	show.Flag("fields", "Which fields to display").
		Default(strings.Join(defaultImageShowFields,",")).
		StringVar(&cmd.Fields)
	show.Arg("identifier", "Identifier of image to show").Required().StringVar(&cmd.Id)
	destroy := images.Command("destroy", "Destroy a server image").Action(cmd.destroy)
	destroy.Arg("identifier", "Identifier of image to destroy").Required().StringsVar(&cmd.IdList)

}
<commit_msg>gobrightbox library now spells licence *correctly*<commit_after>package cli

import (
	"fmt"
	"github.com/brightbox/gobrightbox"
	"gopkg.in/alecthomas/kingpin.v2"
	"sort"
	"strings"
)

var (
	defaultImageListFields = []string{"id", "owner", "type", "created", "status", "arch", "name"}
	defaultImageShowFields = []string{"id", "type", "owner", "created_at", "status", "locked", "arch",
		"name", "description", "username", "virtual_size", "disk_size", "public", "compatibility_mode",
		"official", "ancestor_id", "licence_name"}
)

type imagesCommand struct {
	*CLIApp
	Id      string
	IdList  []string
	ShowAll bool
	Fields  string
}

func imageFields(i *brightbox.Image) map[string]string {
	owner := i.Owner
	itype := i.SourceType
	if i.Official {
		owner = "brightbox"
		itype = "official"
	}
	name := i.Name
	if i.CompatibilityMode {
		name += " (compat)"
	}
	name += " (" + i.Arch + ")"
	var status string
	if i.Status != "available" {
		status = i.Status
	} else if i.Public {
		status = "public"
	} else {
		status = "private"
	}

	return map[string]string{
		"id":                 i.Id,
		"type":               itype,
		"owner":              owner,
		"created":            i.CreatedAt.Format("2006-01-02"),
		"created_at":         formatTime(&i.CreatedAt),
		"status":             status,
		"locked":             formatBool(i.Locked),
		"arch":               i.Arch,
		"name":               i.Name,
		"description":        i.Description,
		"username":           i.Username,
		"virtual_size":       formatInt(i.VirtualSize),
		"disk_size":          formatInt(i.DiskSize),
		"public":             formatBool(i.Public),
		"compatibility_mode": formatBool(i.CompatibilityMode),
		"official":           formatBool(i.Official),
		"ancestor_id":        i.AncestorId,
		"licence_name":       i.LicenceName,
	}
}

type imagesForDisplay []brightbox.Image

func (il imagesForDisplay) Len() int      { return len(il) }
func (il imagesForDisplay) Swap(i, j int) { il[i], il[j] = il[j], il[i] }
func (il imagesForDisplay) Less(i, j int) bool {
	a := il.sortKeys(i)
	b := il.sortKeys(j)
	for e := 0; e < len(a); e++ {
		switch a[e].(type) {
		case string:
			if a[e].(string) != b[e].(string) {
				return a[e].(string) < b[e].(string)
			}
		case int64:
			if a[e].(int64) != b[e].(int64) {
				return a[e].(int64) < b[e].(int64)
			}
		case bool:
			if a[e].(bool) != b[e].(bool) {
				return a[e].(bool) == false && b[e].(bool) == true
			}
		}
	}
	return false
}

func (il imagesForDisplay) sortKeys(i int) []interface{} {
	im := il[i]
	return []interface{}{
		!im.Official,
		im.SourceType == "snapshot",
		im.Name, im.Arch,
		im.Status == "deprecated",
		!im.Public,
		-im.CreatedAt.Unix(),
	}
}

func (l *imagesCommand) list(pc *kingpin.ParseContext) error {
	err := l.Configure()
	if err != nil {
		return err
	}

	// Get the account id in parallel to everything else, we don't need it until
	// later anyway.
	achan := make(chan string)
	go func() {
		achan <- l.accountId()
	}()

	out := new(RowFieldOutput)
	out.Setup(strings.Split(l.Fields, ","))

	images, err := l.Client.Images()
	if err != nil {
		return err
	}
	sortedImages := make(imagesForDisplay, 0, len(images))
	for _, i := range images {
		sortedImages = append(sortedImages, i)
	}
	sort.Sort(sortedImages)

	accountId := <-achan
	out.SendHeader()
	for _, i := range sortedImages {
		if l.ShowAll == false {
			if !i.Official && i.Owner != accountId {
				continue
			}
		}
		if err = out.Write(imageFields(&i)); err != nil {
			return err
		}
	}
	out.Flush()
	return nil
}

func (l *imagesCommand) show(pc *kingpin.ParseContext) error {

	err := l.Configure()
	if err != nil {
		return err
	}
	out := new(ShowFieldOutput)
	out.Setup(strings.Split(l.Fields, ","))

	i, err := l.Client.Image(l.Id)
	if err != nil {
		l.Fatalf(err.Error())
	}
	if err = out.Write(imageFields(i)); err != nil {
		return err
	}
	out.Flush()
	return nil

}

func (l *imagesCommand) destroy(pc *kingpin.ParseContext) error {
	err := l.Configure()
	if err != nil {
		return err
	}
	returnError := false
	for _, id := range l.IdList {
		fmt.Printf("Destroying image %s\n", id)
		err := l.Client.DestroyImage(id)
		if err != nil {
			l.Errorf("%s: %s", err.Error(), id)
			returnError = true
		}
	}
	if returnError {
		return errGeneric
	}
	return nil
}

func configureImagesCommand(app *CLIApp) {
	cmd := imagesCommand{CLIApp: app}
	images := app.Command("images", "Manage server images")
	list := images.Command("list", "List server images").Default().Action(cmd.list)
	list.Flag("fields", "Which fields to display").
		Default(strings.Join(defaultImageListFields, ",")).
		StringVar(&cmd.Fields)
	list.Flag("show-all", "Show all public images from all accounts").Default("false").BoolVar(&cmd.ShowAll)
	show := images.Command("show", "View details of a server image").Action(cmd.show)
	show.Flag("fields", "Which fields to display").
		Default(strings.Join(defaultImageShowFields,",")).
		StringVar(&cmd.Fields)
	show.Arg("identifier", "Identifier of image to show").Required().StringVar(&cmd.Id)
	destroy := images.Command("destroy", "Destroy a server image").Action(cmd.destroy)
	destroy.Arg("identifier", "Identifier of image to destroy").Required().StringsVar(&cmd.IdList)

}
<|endoftext|>


<commit_before>// Package client provides a Stripe client for invoking APIs across all resources
package client

import (
	. "github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/account"
	"github.com/stripe/stripe-go/balance"
	"github.com/stripe/stripe-go/bankaccount"
	"github.com/stripe/stripe-go/bitcoinreceiver"
	"github.com/stripe/stripe-go/bitcointransaction"
	"github.com/stripe/stripe-go/card"
	"github.com/stripe/stripe-go/charge"
	"github.com/stripe/stripe-go/countryspec"
	"github.com/stripe/stripe-go/coupon"
	"github.com/stripe/stripe-go/customer"
	"github.com/stripe/stripe-go/discount"
	"github.com/stripe/stripe-go/dispute"
	"github.com/stripe/stripe-go/event"
	"github.com/stripe/stripe-go/fee"
	"github.com/stripe/stripe-go/feerefund"
	"github.com/stripe/stripe-go/fileupload"
	"github.com/stripe/stripe-go/invoice"
	"github.com/stripe/stripe-go/invoiceitem"
	"github.com/stripe/stripe-go/order"
	"github.com/stripe/stripe-go/plan"
	"github.com/stripe/stripe-go/product"
	"github.com/stripe/stripe-go/recipient"
	"github.com/stripe/stripe-go/refund"
	"github.com/stripe/stripe-go/reversal"
	"github.com/stripe/stripe-go/sku"
	"github.com/stripe/stripe-go/sub"
	"github.com/stripe/stripe-go/token"
	"github.com/stripe/stripe-go/transfer"
)

// API is the Stripe client. It contains all the different resources available.
type API struct {
	// Charges is the client used to invoke /charges APIs.
	// For more details see https://stripe.com/docs/api#charges.
	Charges *charge.Client
	// Customers is the client used to invoke /customers APIs.
	// For more details see https://stripe.com/docs/api#customers.
	Customers *customer.Client
	// Cards is the client used to invoke /cards APIs.
	// For more details see https://stripe.com/docs/api#cards.
	Cards *card.Client
	// Subs is the client used to invoke /subscriptions APIs.
	// For more details see https://stripe.com/docs/api#subscriptions.
	Subs *sub.Client
	// Plans is the client used to invoke /plans APIs.
	// For more details see https://stripe.com/docs/api#plans.
	Plans *plan.Client
	// Coupons is the client used to invoke /coupons APIs.
	// For more details see https://stripe.com/docs/api#coupons.
	Coupons *coupon.Client
	// Discounts is the client used to invoke discount-related APIs.
	// For mode details see https://stripe.com/docs/api#discounts.
	Discounts *discount.Client
	// Invoices is the client used to invoke /invoices APIs.
	// For more details see https://stripe.com/docs/api#invoices.
	Invoices *invoice.Client
	// InvoiceItems is the client used to invoke /invoiceitems APIs.
	// For more details see https://stripe.com/docs/api#invoiceitems.
	InvoiceItems *invoiceitem.Client
	// Disputes is the client used to invoke dispute-related APIs.
	// For more details see https://stripe.com/docs/api#disputes.
	Disputes *dispute.Client
	// Transfers is the client used to invoke /transfers APIs.
	// For more details see https://stripe.com/docs/api#transfers.
	Transfers *transfer.Client
	// Recipients is the client used to invoke /recipients APIs.
	// For more details see https://stripe.com/docs/api#recipients.
	Recipients *recipient.Client
	// Refunds is the client used to invoke /refunds APIs.
	// For more details see https://stripe.com/docs/api#refunds.
	Refunds *refund.Client
	// Fees is the client used to invoke /application_fees APIs.
	// For more details see https://stripe.com/docs/api#application_fees.
	Fees *fee.Client
	// FeeRefunds is the client used to invoke /application_fees/refunds APIs.
	// For more details see https://stripe.com/docs/api#fee_refundss.
	FeeRefunds *feerefund.Client
	// Account is the client used to invoke /account APIs.
	// For more details see https://stripe.com/docs/api#account.
	Account *account.Client
	// CountrySpec is the client used to invoke /country_specs APIs.
	// For more details see https://stripe.com/docs/api#country_specs.
	CountrySpec *countryspec.Client
	// Balance is the client used to invoke /balance and transaction-related APIs.
	// For more details see https://stripe.com/docs/api#balance.
	Balance *balance.Client
	// Events is the client used to invoke /events APIs.
	// For more details see https://stripe.com/docs/api#events.
	Events *event.Client
	// Tokens is the client used to invoke /tokens APIs.
	// For more details see https://stripe.com/docs/api#tokens.
	Tokens *token.Client
	// FileUploads is the client used to invoke the uploads /files APIs.
	// For more details see https://stripe.com/docs/api#file_uploads.
	FileUploads *fileupload.Client
	// BitcoinReceivers is the client used to invoke /bitcoin/receivers APIs.
	// For more details see https://stripe.com/docs/api#bitcoin_receivers.
	BitcoinReceivers *bitcoinreceiver.Client
	// BitcoinTransactions is the client used to invoke /bitcoin/transactions APIs.
	// For more details see https://stripe.com/docs/api#bitcoin_receivers.
	BitcoinTransactions *bitcointransaction.Client
	// Reversals is the client used to invoke /transfers/reversals APIs.
	Reversals *reversal.Client
	// BankAccounts is the client used to invoke /accounts/bank_accounts APIs.
	BankAccounts *bankaccount.Client
	// Products is the client used to invoke /products APIs.
	// For more details see https://stripe.com/docs/api#products.
	Products *product.Client
	// Orders is the client used to invoke /orders APIs.
	// For more details see https://stripe.com/docs/api#orders.
	Orders *order.Client
	// Skus is the client used to invoke /skus APIs.
	// For more details see https://stripe.com/docs/api#skus.
	Skus *sku.Client
}

// Init initializes the Stripe client with the appropriate secret key
// as well as providing the ability to override the backend as needed.
func (a *API) Init(key string, backends *Backends) {
	if backends == nil {
		backends = &Backends{GetBackend(APIBackend), GetBackend(UploadsBackend)}
	}

	a.Charges = &charge.Client{B: backends.API, Key: key}
	a.Customers = &customer.Client{B: backends.API, Key: key}
	a.Cards = &card.Client{B: backends.API, Key: key}
	a.Subs = &sub.Client{B: backends.API, Key: key}
	a.Plans = &plan.Client{B: backends.API, Key: key}
	a.Coupons = &coupon.Client{B: backends.API, Key: key}
	a.Discounts = &discount.Client{B: backends.API, Key: key}
	a.Invoices = &invoice.Client{B: backends.API, Key: key}
	a.InvoiceItems = &invoiceitem.Client{B: backends.API, Key: key}
	a.Disputes = &dispute.Client{B: backends.API, Key: key}
	a.Transfers = &transfer.Client{B: backends.API, Key: key}
	a.Recipients = &recipient.Client{B: backends.API, Key: key}
	a.Refunds = &refund.Client{B: backends.API, Key: key}
	a.Fees = &fee.Client{B: backends.API, Key: key}
	a.FeeRefunds = &feerefund.Client{B: backends.API, Key: key}
	a.Account = &account.Client{B: backends.API, Key: key}
	a.CountrySpec = &countryspec.Client{B: backends.API, Key: key}
	a.Balance = &balance.Client{B: backends.API, Key: key}
	a.Events = &event.Client{B: backends.API, Key: key}
	a.Tokens = &token.Client{B: backends.API, Key: key}
	a.FileUploads = &fileupload.Client{B: backends.Uploads, Key: key}
	a.BitcoinReceivers = &bitcoinreceiver.Client{B: backends.API, Key: key}
	a.BitcoinTransactions = &bitcointransaction.Client{B: backends.API, Key: key}
	a.Reversals = &reversal.Client{B: backends.API, Key: key}
	a.BankAccounts = &bankaccount.Client{B: backends.API, Key: key}
	a.Products = &product.Client{B: backends.API, Key: key}
	a.Orders = &order.Client{B: backends.API, Key: key}
	a.Skus = &sku.Client{B: backends.API, Key: key}
}

// New creates a new Stripe client with the appropriate secret key
// as well as providing the ability to override the backends as needed.
func New(key string, backends *Backends) *API {
	api := API{}
	api.Init(key, backends)
	return &api
}
<commit_msg>add order returns to client.api<commit_after>// Package client provides a Stripe client for invoking APIs across all resources
package client

import (
	. "github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/account"
	"github.com/stripe/stripe-go/balance"
	"github.com/stripe/stripe-go/bankaccount"
	"github.com/stripe/stripe-go/bitcoinreceiver"
	"github.com/stripe/stripe-go/bitcointransaction"
	"github.com/stripe/stripe-go/card"
	"github.com/stripe/stripe-go/charge"
	"github.com/stripe/stripe-go/countryspec"
	"github.com/stripe/stripe-go/coupon"
	"github.com/stripe/stripe-go/customer"
	"github.com/stripe/stripe-go/discount"
	"github.com/stripe/stripe-go/dispute"
	"github.com/stripe/stripe-go/event"
	"github.com/stripe/stripe-go/fee"
	"github.com/stripe/stripe-go/feerefund"
	"github.com/stripe/stripe-go/fileupload"
	"github.com/stripe/stripe-go/invoice"
	"github.com/stripe/stripe-go/invoiceitem"
	"github.com/stripe/stripe-go/order"
	"github.com/stripe/stripe-go/orderreturn"
	"github.com/stripe/stripe-go/plan"
	"github.com/stripe/stripe-go/product"
	"github.com/stripe/stripe-go/recipient"
	"github.com/stripe/stripe-go/refund"
	"github.com/stripe/stripe-go/reversal"
	"github.com/stripe/stripe-go/sku"
	"github.com/stripe/stripe-go/sub"
	"github.com/stripe/stripe-go/token"
	"github.com/stripe/stripe-go/transfer"
)

// API is the Stripe client. It contains all the different resources available.
type API struct {
	// Charges is the client used to invoke /charges APIs.
	// For more details see https://stripe.com/docs/api#charges.
	Charges *charge.Client
	// Customers is the client used to invoke /customers APIs.
	// For more details see https://stripe.com/docs/api#customers.
	Customers *customer.Client
	// Cards is the client used to invoke /cards APIs.
	// For more details see https://stripe.com/docs/api#cards.
	Cards *card.Client
	// Subs is the client used to invoke /subscriptions APIs.
	// For more details see https://stripe.com/docs/api#subscriptions.
	Subs *sub.Client
	// Plans is the client used to invoke /plans APIs.
	// For more details see https://stripe.com/docs/api#plans.
	Plans *plan.Client
	// Coupons is the client used to invoke /coupons APIs.
	// For more details see https://stripe.com/docs/api#coupons.
	Coupons *coupon.Client
	// Discounts is the client used to invoke discount-related APIs.
	// For mode details see https://stripe.com/docs/api#discounts.
	Discounts *discount.Client
	// Invoices is the client used to invoke /invoices APIs.
	// For more details see https://stripe.com/docs/api#invoices.
	Invoices *invoice.Client
	// InvoiceItems is the client used to invoke /invoiceitems APIs.
	// For more details see https://stripe.com/docs/api#invoiceitems.
	InvoiceItems *invoiceitem.Client
	// Disputes is the client used to invoke dispute-related APIs.
	// For more details see https://stripe.com/docs/api#disputes.
	Disputes *dispute.Client
	// Transfers is the client used to invoke /transfers APIs.
	// For more details see https://stripe.com/docs/api#transfers.
	Transfers *transfer.Client
	// Recipients is the client used to invoke /recipients APIs.
	// For more details see https://stripe.com/docs/api#recipients.
	Recipients *recipient.Client
	// Refunds is the client used to invoke /refunds APIs.
	// For more details see https://stripe.com/docs/api#refunds.
	Refunds *refund.Client
	// Fees is the client used to invoke /application_fees APIs.
	// For more details see https://stripe.com/docs/api#application_fees.
	Fees *fee.Client
	// FeeRefunds is the client used to invoke /application_fees/refunds APIs.
	// For more details see https://stripe.com/docs/api#fee_refundss.
	FeeRefunds *feerefund.Client
	// Account is the client used to invoke /account APIs.
	// For more details see https://stripe.com/docs/api#account.
	Account *account.Client
	// CountrySpec is the client used to invoke /country_specs APIs.
	// For more details see https://stripe.com/docs/api#country_specs.
	CountrySpec *countryspec.Client
	// Balance is the client used to invoke /balance and transaction-related APIs.
	// For more details see https://stripe.com/docs/api#balance.
	Balance *balance.Client
	// Events is the client used to invoke /events APIs.
	// For more details see https://stripe.com/docs/api#events.
	Events *event.Client
	// Tokens is the client used to invoke /tokens APIs.
	// For more details see https://stripe.com/docs/api#tokens.
	Tokens *token.Client
	// FileUploads is the client used to invoke the uploads /files APIs.
	// For more details see https://stripe.com/docs/api#file_uploads.
	FileUploads *fileupload.Client
	// BitcoinReceivers is the client used to invoke /bitcoin/receivers APIs.
	// For more details see https://stripe.com/docs/api#bitcoin_receivers.
	BitcoinReceivers *bitcoinreceiver.Client
	// BitcoinTransactions is the client used to invoke /bitcoin/transactions APIs.
	// For more details see https://stripe.com/docs/api#bitcoin_receivers.
	BitcoinTransactions *bitcointransaction.Client
	// Reversals is the client used to invoke /transfers/reversals APIs.
	Reversals *reversal.Client
	// BankAccounts is the client used to invoke /accounts/bank_accounts APIs.
	BankAccounts *bankaccount.Client
	// Products is the client used to invoke /products APIs.
	// For more details see https://stripe.com/docs/api#products.
	Products *product.Client
	// Orders is the client used to invoke /orders APIs.
	// For more details see https://stripe.com/docs/api#orders.
	Orders *order.Client
	// OrderReturns is the client used to invoke /order_returns APIs.
	// For more details, see https://stripe.com/docs/api#order_returns.
	OrderReturns *orderreturn.Client
	// Skus is the client used to invoke /skus APIs.
	// For more details see https://stripe.com/docs/api#skus.
	Skus *sku.Client
}

// Init initializes the Stripe client with the appropriate secret key
// as well as providing the ability to override the backend as needed.
func (a *API) Init(key string, backends *Backends) {
	if backends == nil {
		backends = &Backends{GetBackend(APIBackend), GetBackend(UploadsBackend)}
	}

	a.Charges = &charge.Client{B: backends.API, Key: key}
	a.Customers = &customer.Client{B: backends.API, Key: key}
	a.Cards = &card.Client{B: backends.API, Key: key}
	a.Subs = &sub.Client{B: backends.API, Key: key}
	a.Plans = &plan.Client{B: backends.API, Key: key}
	a.Coupons = &coupon.Client{B: backends.API, Key: key}
	a.Discounts = &discount.Client{B: backends.API, Key: key}
	a.Invoices = &invoice.Client{B: backends.API, Key: key}
	a.InvoiceItems = &invoiceitem.Client{B: backends.API, Key: key}
	a.Disputes = &dispute.Client{B: backends.API, Key: key}
	a.Transfers = &transfer.Client{B: backends.API, Key: key}
	a.Recipients = &recipient.Client{B: backends.API, Key: key}
	a.Refunds = &refund.Client{B: backends.API, Key: key}
	a.Fees = &fee.Client{B: backends.API, Key: key}
	a.FeeRefunds = &feerefund.Client{B: backends.API, Key: key}
	a.Account = &account.Client{B: backends.API, Key: key}
	a.CountrySpec = &countryspec.Client{B: backends.API, Key: key}
	a.Balance = &balance.Client{B: backends.API, Key: key}
	a.Events = &event.Client{B: backends.API, Key: key}
	a.Tokens = &token.Client{B: backends.API, Key: key}
	a.FileUploads = &fileupload.Client{B: backends.Uploads, Key: key}
	a.BitcoinReceivers = &bitcoinreceiver.Client{B: backends.API, Key: key}
	a.BitcoinTransactions = &bitcointransaction.Client{B: backends.API, Key: key}
	a.Reversals = &reversal.Client{B: backends.API, Key: key}
	a.BankAccounts = &bankaccount.Client{B: backends.API, Key: key}
	a.Products = &product.Client{B: backends.API, Key: key}
	a.Orders = &order.Client{B: backends.API, Key: key}
	a.OrderReturns = &orderreturn.Client{B: backends.API, Key: key}
	a.Skus = &sku.Client{B: backends.API, Key: key}
}

// New creates a new Stripe client with the appropriate secret key
// as well as providing the ability to override the backends as needed.
func New(key string, backends *Backends) *API {
	api := API{}
	api.Init(key, backends)
	return &api
}
<|endoftext|>


<commit_before>package boardgame

import (
	"math"
)

//TODO: create a Stack interface that both GrowableStack and SizedStack
//implement.

//TODO: should deck, index, and cap all be private?

//Stack is one of the fundamental types in BoardGame. It represents an ordered
//stack of 0 or more Components, all from the same Deck. Each deck has 0 or
//more Stacks based off of it, and together they include all components in
//that deck, with no component residing in more than one stack. Stacks model
//things like a stack of cards, a collection of resource tokens, etc.
type GrowableStack struct {
	//Deck is the deck that we're a part of.
	Deck *Deck
	//The indexes from the given deck that this stack contains, in order.
	Indexes []int
	//Cap, if set, says the maxmimum number of items allowed in the Stack. 0
	//means that the Stack may grow without bound.
	Cap int
}

//SizedStack is a Stack that has a fixed number of slots, any of which may be
//empty. Create a new one with NewSizedStack.
type SizedStack struct {
	//Deck is the deck we're a part of.
	Deck *Deck
	//Indexes will always have a len of size. Slots that are "empty" will have
	//index of -1.
	Indexes []int
	//Size is the number of slots.
	Size int
}

//NewGrowableStack creates a new growable stack with the given Deck and Cap.
func NewGrowableStack(deck *Deck, max int) *GrowableStack {

	if max < 0 {
		max = 0
	}

	return &GrowableStack{
		Deck:    deck,
		Indexes: nil,
		Cap:     max,
	}
}

//NewSizedStack creates a new SizedStack for the given deck, with the
//specified size.
func NewSizedStack(deck *Deck, size int) *SizedStack {
	if size < 0 {
		size = 0
	}

	indexes := make([]int, size)

	for i := 0; i < size; i++ {
		indexes[i] = -1
	}

	return &SizedStack{
		Deck:    deck,
		Indexes: indexes,
		Size:    size,
	}
}

//Len returns the number of items in the stack.
func (s *GrowableStack) Len() int {
	return len(s.Indexes)
}

//Len returns the number of slots in the stack. It will always equal Size.
func (s *SizedStack) Len() int {
	return len(s.Indexes)
}

//ComponentAt fetches the component object representing the n-th object in
//this stack.
func (s *GrowableStack) ComponentAt(index int) *Component {

	//Substantially recreated in SizedStack.ComponentAt()
	if index >= s.Len() || index < 0 {
		return nil
	}

	if s.Deck == nil {
		return nil
	}

	//We don't need to check that s.Indexes[index] is valid because it was
	//checked when it was set, and Decks are immutable.
	return s.Deck.Components()[s.Indexes[index]]
}

//ComponentAt fetches the component object representing the n-th object in
//this stack.
func (s *SizedStack) ComponentAt(index int) *Component {

	//Substantially recreated in GrowableStack.ComponentAt()

	if index >= s.Len() || index < 0 {
		return nil
	}

	if s.Deck == nil {
		return nil
	}

	deckIndex := s.Indexes[index]

	//Check if this is an empty slot
	if deckIndex == -1 {
		return nil
	}

	//We don't need to check that s.Indexes[index] is valid because it was
	//checked when it was set, and Decks are immutable.
	return s.Deck.Components()[deckIndex]
}

//SlotsRemaining returns the count of slots left in this stack. If Cap is 0
//(inifinite) this will be MaxInt64.
func (s *GrowableStack) SlotsRemaining() int {
	if s.Cap <= 0 {
		return math.MaxInt64
	}
	return s.Cap - s.Len()
}

//SlotsRemaining returns the count of unfilled slots in this stack.
func (s *SizedStack) SlotsRemaining() int {
	count := 0
	for _, index := range s.Indexes {
		if index == -1 {
			count++
		}
	}
	return count
}

//InsertFront puts the component at index 0 in this stack, moving all other
//items down by one. The Component you insert should not currently be a member
//of any other stacks, to maintain the deck invariant.
func (s *GrowableStack) InsertFront(c *Component) {

	//Based on how Decks and Chests are constructed, we know the components in
	//the chest hae the right gamename, so no need to check.

	if c.Deck.Name() != s.Deck.Name() {
		//We can only add items that are in our deck.

		//TODO: communicate an error
		return
	}

	if s.SlotsRemaining() < 1 {
		return
	}

	s.Indexes = append([]int{c.DeckIndex}, s.Indexes...)
}

/*

//InsertBack puts the component at the last index in this stack. The
//Component you insert should not currently be a member of any other stacks,
//to maintain the deck invariant.
func (s *Stack) InsertBack(c Component) {

}

//RemoveFront removes the component from the first slot in this stack,
//shifting all later components down by 1. You should then insert the
//component in another stack to maintain the deck invariant.
func (s *Stack) RemoveFront() Component {

}

//RemoveBack removes the component from the last slot in this stack. You
//should then insert the component in another stack to maintain the deck
//invariant.
func (s *Stack) RemoveBack() Component {

}

*/
<commit_msg>Make the empty stack slot be a constant. Part of #12.<commit_after>package boardgame

import (
	"math"
)

const emptyIndexSentinel = -1

//TODO: create a Stack interface that both GrowableStack and SizedStack
//implement.

//TODO: should deck, index, and cap all be private?

//Stack is one of the fundamental types in BoardGame. It represents an ordered
//stack of 0 or more Components, all from the same Deck. Each deck has 0 or
//more Stacks based off of it, and together they include all components in
//that deck, with no component residing in more than one stack. Stacks model
//things like a stack of cards, a collection of resource tokens, etc.
type GrowableStack struct {
	//Deck is the deck that we're a part of.
	Deck *Deck
	//The indexes from the given deck that this stack contains, in order.
	Indexes []int
	//Cap, if set, says the maxmimum number of items allowed in the Stack. 0
	//means that the Stack may grow without bound.
	Cap int
}

//SizedStack is a Stack that has a fixed number of slots, any of which may be
//empty. Create a new one with NewSizedStack.
type SizedStack struct {
	//Deck is the deck we're a part of.
	Deck *Deck
	//Indexes will always have a len of size. Slots that are "empty" will have
	//index of -1.
	Indexes []int
	//Size is the number of slots.
	Size int
}

//NewGrowableStack creates a new growable stack with the given Deck and Cap.
func NewGrowableStack(deck *Deck, max int) *GrowableStack {

	if max < 0 {
		max = 0
	}

	return &GrowableStack{
		Deck:    deck,
		Indexes: nil,
		Cap:     max,
	}
}

//NewSizedStack creates a new SizedStack for the given deck, with the
//specified size.
func NewSizedStack(deck *Deck, size int) *SizedStack {
	if size < 0 {
		size = 0
	}

	indexes := make([]int, size)

	for i := 0; i < size; i++ {
		indexes[i] = emptyIndexSentinel
	}

	return &SizedStack{
		Deck:    deck,
		Indexes: indexes,
		Size:    size,
	}
}

//Len returns the number of items in the stack.
func (s *GrowableStack) Len() int {
	return len(s.Indexes)
}

//Len returns the number of slots in the stack. It will always equal Size.
func (s *SizedStack) Len() int {
	return len(s.Indexes)
}

//ComponentAt fetches the component object representing the n-th object in
//this stack.
func (s *GrowableStack) ComponentAt(index int) *Component {

	//Substantially recreated in SizedStack.ComponentAt()
	if index >= s.Len() || index < 0 {
		return nil
	}

	if s.Deck == nil {
		return nil
	}

	//We don't need to check that s.Indexes[index] is valid because it was
	//checked when it was set, and Decks are immutable.
	return s.Deck.Components()[s.Indexes[index]]
}

//ComponentAt fetches the component object representing the n-th object in
//this stack.
func (s *SizedStack) ComponentAt(index int) *Component {

	//Substantially recreated in GrowableStack.ComponentAt()

	if index >= s.Len() || index < 0 {
		return nil
	}

	if s.Deck == nil {
		return nil
	}

	deckIndex := s.Indexes[index]

	//Check if this is an empty slot
	if deckIndex == emptyIndexSentinel {
		return nil
	}

	//We don't need to check that s.Indexes[index] is valid because it was
	//checked when it was set, and Decks are immutable.
	return s.Deck.Components()[deckIndex]
}

//SlotsRemaining returns the count of slots left in this stack. If Cap is 0
//(inifinite) this will be MaxInt64.
func (s *GrowableStack) SlotsRemaining() int {
	if s.Cap <= 0 {
		return math.MaxInt64
	}
	return s.Cap - s.Len()
}

//SlotsRemaining returns the count of unfilled slots in this stack.
func (s *SizedStack) SlotsRemaining() int {
	count := 0
	for _, index := range s.Indexes {
		if index == emptyIndexSentinel {
			count++
		}
	}
	return count
}

//InsertFront puts the component at index 0 in this stack, moving all other
//items down by one. The Component you insert should not currently be a member
//of any other stacks, to maintain the deck invariant.
func (s *GrowableStack) InsertFront(c *Component) {

	//Based on how Decks and Chests are constructed, we know the components in
	//the chest hae the right gamename, so no need to check.

	if c.Deck.Name() != s.Deck.Name() {
		//We can only add items that are in our deck.

		//TODO: communicate an error
		return
	}

	if s.SlotsRemaining() < 1 {
		return
	}

	s.Indexes = append([]int{c.DeckIndex}, s.Indexes...)
}

/*

//InsertBack puts the component at the last index in this stack. The
//Component you insert should not currently be a member of any other stacks,
//to maintain the deck invariant.
func (s *Stack) InsertBack(c Component) {

}

//RemoveFront removes the component from the first slot in this stack,
//shifting all later components down by 1. You should then insert the
//component in another stack to maintain the deck invariant.
func (s *Stack) RemoveFront() Component {

}

//RemoveBack removes the component from the last slot in this stack. You
//should then insert the component in another stack to maintain the deck
//invariant.
func (s *Stack) RemoveBack() Component {

}

*/
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

var (
	countDirs  int
	countFiles int
	opt        Options
)

func update(f os.FileInfo) {
	if f.IsDir() {
		countDirs++
	} else {
		countFiles++
	}
}

// checkFile checks if we have to add this file.
// Returns true if we have to recurse or false if we don't
func checkFile(file File) bool {
	if opt.excludeEmptyFiles && !file.info.IsDir() && file.info.Size() == 0 {
		return false
	}
	if opt.excludeHiddenFiles && strings.HasPrefix(file.info.Name(), ".") {
		// hidden file or directory
		return false
	}
	if opt.ignoreSymLinks && file.info.Mode()&os.ModeSymlink != 0 {
		return false
	}

	update(file.info)

	// only make hash for files, skip dirs
	if !file.info.IsDir() {
		AddFile(file)
	}
	if !opt.quiet {
		fmt.Printf("[+] Analyzed: %v directories and %v files\r",
			countDirs, countFiles)
	}
	return true
}

// readDir reads the files from the dir "s" recursively and checks if there are duplicated
func readDir(s string) error {
	files, err := ioutil.ReadDir(s)
	if err != nil {
		return err
	}
	if len(files) == 0 {
		return nil
	}

	for _, f := range files {
		path := s + string(filepath.Separator) + f.Name()
		file := File{
			path,
			f,
		}

		recurse := checkFile(file)

		if opt.enableRecursion && recurse && file.info.IsDir() {
			readDir(path)
		}
	}
	return nil
}

// Start the program with the current options. Options param is read only
func Start(options Options) {
	opt = options

	if info, err := os.Stat(opt.currentDir); err == nil && !info.IsDir() && !opt.quiet {
		fmt.Printf("[-] %s is not a valid directory", info.Name())
		return
	}
	if !opt.quiet {
		fmt.Println("[+] Starting in directory:", opt.currentDir)
	}

	err := readDir(opt.currentDir)
	if err != nil && !opt.quiet {
		fmt.Println("[-]", err)
	}

	if !opt.quiet {
		fmt.Printf("\n[+] Stage 1 / 3 completed\n")
	}

	ValidateDuplicatedFiles()

	reportData := ObtainReportData()
	reportData.ReportDuplicated(opt.showSummary)

	file, err := os.Open("icon/success.png")
	if err != nil {
		if !opt.quiet {
			fmt.Println("[-]", err)
		}
		return
	}
	absDir, err := filepath.Abs(file.Name())
	if err != nil {
		if !opt.quiet {
			fmt.Println("[-]", err)
		}
		return
	}
	summary := fmt.Sprintf("%v duplicated files in (%v sets) occupying %v bytes\n",
		reportData.duplicates, reportData.sets, ConvertBytes(reportData.totalSize))
	notification := Notification{"godedupe finish", summary, absDir}
	notification.ShowNotification(opt.showNotification)
}
<commit_msg>allow method to ignore directories<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

var (
	countDirs  int
	countFiles int
	opt        Options
)

func update(f os.FileInfo) {
	if f.IsDir() {
		countDirs++
	} else {
		countFiles++
	}
}

// checkFile checks if we have to add this file.
// Returns true if we have to recurse or false if we don't
func checkFile(file File) bool {
	if opt.excludeEmptyFiles && !file.info.IsDir() && file.info.Size() == 0 {
		return false
	}
	if opt.excludeHiddenFiles && strings.HasPrefix(file.info.Name(), ".") {
		// hidden file or directory
		return false
	}
	if opt.ignoreSymLinks && file.info.Mode()&os.ModeSymlink != 0 {
		return false
	}

	update(file.info)

	// only make hash for files, skip dirs
	if !file.info.IsDir() {
		AddFile(file)
	}
	if !opt.quiet {
		fmt.Printf("[+] Analyzed: %v directories and %v files\r",
			countDirs, countFiles)
	}
	return true
}

// readDir reads the files from the dir "s" recursively and checks if there are duplicated
func readDir(s string) error {
	files, err := ioutil.ReadDir(s)
	if err != nil {
		return err
	}
	if len(files) == 0 {
		return nil
	}

	for _, f := range files {
		if f.Name() == ".godedupe_ignore" {
			return nil
		}
	}

	for _, f := range files {

		path := s + string(filepath.Separator) + f.Name()
		file := File{
			path,
			f,
		}

		recurse := checkFile(file)

		if opt.enableRecursion && recurse && file.info.IsDir() {
			readDir(path)
		}
	}
	return nil
}

// Start the program with the current options. Options param is read only
func Start(options Options) {
	opt = options

	if info, err := os.Stat(opt.currentDir); err == nil && !info.IsDir() && !opt.quiet {
		fmt.Printf("[-] %s is not a valid directory", info.Name())
		return
	}
	if !opt.quiet {
		fmt.Println("[+] Starting in directory:", opt.currentDir)
	}

	err := readDir(opt.currentDir)
	if err != nil && !opt.quiet {
		fmt.Println("[-]", err)
	}

	if !opt.quiet {
		fmt.Printf("\n[+] Stage 1 / 3 completed\n")
	}

	ValidateDuplicatedFiles()

	reportData := ObtainReportData()
	reportData.ReportDuplicated(opt.showSummary)

	file, err := os.Open("icon/success.png")
	if err != nil {
		if !opt.quiet {
			fmt.Println("[-]", err)
		}
		return
	}
	absDir, err := filepath.Abs(file.Name())
	if err != nil {
		if !opt.quiet {
			fmt.Println("[-]", err)
		}
		return
	}
	summary := fmt.Sprintf("%v duplicated files in (%v sets) occupying %v bytes\n",
		reportData.duplicates, reportData.sets, ConvertBytes(reportData.totalSize))
	notification := Notification{"godedupe finish", summary, absDir}
	notification.ShowNotification(opt.showNotification)
}
<|endoftext|>