<commit_before>package gitclient

import (
	"bufio"
	"bytes"
	"cred-alert/mimetype"
	"cred-alert/scanners"
	"cred-alert/scanners/filescanner"
	"cred-alert/sniff"
	"errors"
	"fmt"
	"strings"

	"code.cloudfoundry.org/lager"

	git "gopkg.in/libgit2/git2go.v24"
)

const defaultRemoteName = "origin"

var ErrInterrupted = errors.New("interrupted")

type client struct {
	cloneOptions *git.CloneOptions
}

//go:generate counterfeiter . Client

type Client interface {
	BranchTargets(string) (map[string]string, error)
	Clone(string, string) (*git.Repository, error)
	GetParents(*git.Repository, *git.Oid) ([]*git.Oid, error)
	Fetch(string) (map[string][]*git.Oid, error)
	HardReset(string, *git.Oid) error
	Diff(repositoryPath string, a, b *git.Oid) (string, error)
	BranchCredentialCounts(lager.Logger, string, sniff.Sniffer, git.BranchType) (map[string]uint, error)
}

func New(privateKeyPath, publicKeyPath string) *client {
	credentialsCallback := newCredentialsCallback(privateKeyPath, publicKeyPath)
	return &client{
		cloneOptions: &git.CloneOptions{
			FetchOptions: &git.FetchOptions{
				UpdateFetchhead: true,
				RemoteCallbacks: git.RemoteCallbacks{
					CredentialsCallback:      credentialsCallback,
					CertificateCheckCallback: certificateCheckCallback,
				},
			},
		},
	}
}

func (c *client) BranchTargets(repositoryPath string) (map[string]string, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return nil, err
	}
	defer repo.Free()

	it, err := repo.NewBranchIterator(git.BranchAll)
	if err != nil {
		return nil, err
	}

	var branch *git.Branch
	branches := map[string]string{}
	for {
		branch, _, err = it.Next()
		if err != nil {
			break
		}

		branchName, err := branch.Name()
		if err != nil {
			break
		}

		target := branch.Target()
		if target == nil { // origin/HEAD has no target
			continue
		}

		branches[branchName] = branch.Target().String()
	}

	if branch != nil {
		branch.Free()
	}

	return branches, nil
}

func (c *client) Clone(sshURL, dest string) (*git.Repository, error) {
	return git.Clone(sshURL, dest, c.cloneOptions)
}

func (c *client) GetParents(repo *git.Repository, child *git.Oid) ([]*git.Oid, error) {
	object, err := repo.Lookup(child)
	if err != nil {
		return nil, err
	}
	defer object.Free()

	commit, err := object.AsCommit()
	if err != nil {
		return nil, err
	}
	defer commit.Free()

	var parents []*git.Oid
	var i uint
	for i = 0; i < commit.ParentCount(); i++ {
		parents = append(parents, commit.ParentId(i))
	}

	return parents, nil
}

func (c *client) Fetch(repositoryPath string) (map[string][]*git.Oid, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return nil, err
	}
	defer repo.Free()

	remote, err := repo.Remotes.Lookup(defaultRemoteName)
	if err != nil {
		return nil, err
	}
	defer remote.Free()

	changes := map[string][]*git.Oid{}
	updateTipsCallback := func(refname string, a *git.Oid, b *git.Oid) git.ErrorCode {
		changes[refname] = []*git.Oid{a.Copy(), b.Copy()}
		return 0
	}

	// bleh
	c.cloneOptions.FetchOptions.RemoteCallbacks.UpdateTipsCallback = updateTipsCallback

	var msg string
	err = remote.Fetch([]string{}, c.cloneOptions.FetchOptions, msg)
	if err != nil {
		return nil, err
	}

	return changes, nil
}

func (c *client) HardReset(repositoryPath string, oid *git.Oid) error {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return err
	}
	defer repo.Free()

	object, err := repo.Lookup(oid)
	if err != nil {
		return err
	}
	defer object.Free()

	commit, err := object.AsCommit()
	if err != nil {
		return err
	}
	defer commit.Free()

	return repo.ResetToCommit(commit, git.ResetHard, &git.CheckoutOpts{
		Strategy: git.CheckoutForce,
	})
}

func newCredentialsCallback(privateKeyPath, publicKeyPath string) git.CredentialsCallback {
	return func(url string, username string, allowedTypes git.CredType) (git.ErrorCode, *git.Cred) {
		passphrase := ""
		ret, cred := git.NewCredSshKey(username, publicKeyPath, privateKeyPath, passphrase)
		if ret != 0 {
			fmt.Printf("ret: %d\n", ret)
		}
		return git.ErrorCode(ret), &cred
	}
}

func certificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode {
	// should return an error code if the cert isn't valid
	return git.ErrorCode(0)
}

func (c *client) Diff(repositoryPath string, parent, child *git.Oid) (string, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return "", err
	}
	defer repo.Free()

	var aTree *git.Tree
	if parent != nil {
		var err error
		aTree, err = objectToTree(repo, parent)
		if err != nil {
			return "", err
		}
		defer aTree.Free()
	}

	bTree, err := objectToTree(repo, child)
	if err != nil {
		return "", err
	}
	defer bTree.Free()

	options, err := git.DefaultDiffOptions()
	if err != nil {
		return "", err
	}

	diff, err := repo.DiffTreeToTree(aTree, bTree, &options)
	if err != nil {
		return "", err
	}
	defer diff.Free()

	numDeltas, err := diff.NumDeltas()
	if err != nil {
		return "", err
	}

	var results []string
	for i := 0; i < numDeltas; i++ {
		patch, err := diff.Patch(i)
		if err != nil {
			return "", err
		}
		patchString, err := patch.String()
		if err != nil {
			return "", err
		}
		patch.Free()

		results = append(results, patchString)
	}

	return strings.Join(results, "\n"), nil
}

func (c *client) BranchCredentialCounts(
	logger lager.Logger,
	repositoryPath string,
	sniffer sniff.Sniffer,
	branchType git.BranchType,
) (map[string]uint, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return nil, err
	}
	defer repo.Free()

	it, err := repo.NewBranchIterator(branchType)
	if err != nil {
		return nil, err
	}
	defer it.Free()

	var branch *git.Branch
	var target *git.Oid
	var commit *git.Commit
	var tree *git.Tree
	var branchName string
	var blob *git.Blob

	entryCounts := make(map[git.Oid]uint)
	branchCounts := make(map[string]uint)

	for {
		branch, _, err = it.Next()
		if err != nil {
			break
		}

		target = branch.Target()
		if target == nil {
			continue
		}

		commit, err = repo.LookupCommit(target)
		if err != nil {
			return nil, err
		}

		tree, err = commit.Tree()
		if err != nil {
			return nil, err
		}

		branchName, err = branch.Name()
		if err != nil {
			return nil, err
		}

		err = tree.Walk(func(root string, entry *git.TreeEntry) int {
			if entry.Type == git.ObjectBlob {
				if count, ok := entryCounts[*entry.Id]; ok {
					if count > 0 {
						branchCounts[branchName] += count
					}
					return 0
				}

				blob, err = repo.LookupBlob(entry.Id)
				if err != nil {
					return -1
				}

				var count uint
				r := bufio.NewReader(bytes.NewReader(blob.Contents()))
				mime := mimetype.Mimetype(logger, r)
				if mime == "" || strings.HasPrefix(mime, "text") {
					sniffer.Sniff(
						logger,
						filescanner.New(r, entry.Name),
						func(lager.Logger, scanners.Violation) error {
							count++
							return nil
						},
					)
				}

				entryCounts[*entry.Id] = count
				branchCounts[branchName] += count
			}

			return 0
		})

		if err != nil {
			return nil, err
		}
	}

	if blob != nil {
		blob.Free()
	}

	if tree != nil {
		tree.Free()
	}

	if commit != nil {
		commit.Free()
	}

	if branch != nil {
		branch.Free()
	}

	return branchCounts, nil
}

func objectToTree(repo *git.Repository, oid *git.Oid) (*git.Tree, error) {
	object, err := repo.Lookup(oid)
	if err != nil {
		return nil, err
	}
	defer object.Free()

	commit, err := object.AsCommit()
	if err != nil {
		return nil, err
	}
	defer commit.Free()

	tree, err := commit.Tree()
	if err != nil {
		return nil, err
	}

	return tree, nil
}
<commit_msg>Another attempt at fixing phantom git SHAs<commit_after>package gitclient

import (
	"bufio"
	"bytes"
	"cred-alert/mimetype"
	"cred-alert/scanners"
	"cred-alert/scanners/filescanner"
	"cred-alert/sniff"
	"errors"
	"fmt"
	"strings"

	"code.cloudfoundry.org/lager"

	git "gopkg.in/libgit2/git2go.v24"
)

const defaultRemoteName = "origin"

var ErrInterrupted = errors.New("interrupted")

type client struct {
	privateKeyPath string
	publicKeyPath string
}

//go:generate counterfeiter . Client

type Client interface {
	BranchTargets(string) (map[string]string, error)
	Clone(string, string) (*git.Repository, error)
	GetParents(*git.Repository, *git.Oid) ([]*git.Oid, error)
	Fetch(string) (map[string][]*git.Oid, error)
	HardReset(string, *git.Oid) error
	Diff(repositoryPath string, a, b *git.Oid) (string, error)
	BranchCredentialCounts(lager.Logger, string, sniff.Sniffer, git.BranchType) (map[string]uint, error)
}

func New(privateKeyPath, publicKeyPath string) *client {
	return &client{
		privateKeyPath: privateKeyPath,
		publicKeyPath: publicKeyPath,
	}
}

func (c *client) BranchTargets(repositoryPath string) (map[string]string, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return nil, err
	}
	defer repo.Free()

	it, err := repo.NewBranchIterator(git.BranchAll)
	if err != nil {
		return nil, err
	}

	var branch *git.Branch
	branches := map[string]string{}
	for {
		branch, _, err = it.Next()
		if err != nil {
			break
		}

		branchName, err := branch.Name()
		if err != nil {
			break
		}

		target := branch.Target()
		if target == nil { // origin/HEAD has no target
			continue
		}

		branches[branchName] = branch.Target().String()
	}

	if branch != nil {
		branch.Free()
	}

	return branches, nil
}

func (c *client) Clone(sshURL, dest string) (*git.Repository, error) {
	cloneOptions := &git.CloneOptions{
		FetchOptions: newFetchOptions(c.privateKeyPath, c.publicKeyPath),
	}

	return git.Clone(sshURL, dest, cloneOptions)
}

func (c *client) GetParents(repo *git.Repository, child *git.Oid) ([]*git.Oid, error) {
	object, err := repo.Lookup(child)
	if err != nil {
		return nil, err
	}
	defer object.Free()

	commit, err := object.AsCommit()
	if err != nil {
		return nil, err
	}
	defer commit.Free()

	var parents []*git.Oid
	var i uint
	for i = 0; i < commit.ParentCount(); i++ {
		parents = append(parents, commit.ParentId(i))
	}

	return parents, nil
}

func (c *client) Fetch(repositoryPath string) (map[string][]*git.Oid, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return nil, err
	}
	defer repo.Free()

	remote, err := repo.Remotes.Lookup(defaultRemoteName)
	if err != nil {
		return nil, err
	}
	defer remote.Free()

	changes := map[string][]*git.Oid{}
	updateTipsCallback := func(refname string, a *git.Oid, b *git.Oid) git.ErrorCode {
		changes[refname] = []*git.Oid{a.Copy(), b.Copy()}
		return 0
	}

	fetchOptions := newFetchOptions(c.privateKeyPath, c.publicKeyPath)
    fetchOptions.RemoteCallbacks.UpdateTipsCallback = updateTipsCallback

	var msg string
	err = remote.Fetch([]string{}, fetchOptions, msg)
	if err != nil {
		return nil, err
	}

	return changes, nil
}

func (c *client) HardReset(repositoryPath string, oid *git.Oid) error {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return err
	}
	defer repo.Free()

	object, err := repo.Lookup(oid)
	if err != nil {
		return err
	}
	defer object.Free()

	commit, err := object.AsCommit()
	if err != nil {
		return err
	}
	defer commit.Free()

	return repo.ResetToCommit(commit, git.ResetHard, &git.CheckoutOpts{
		Strategy: git.CheckoutForce,
	})
}

func (c *client) Diff(repositoryPath string, parent, child *git.Oid) (string, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return "", err
	}
	defer repo.Free()

	var aTree *git.Tree
	if parent != nil {
		var err error
		aTree, err = objectToTree(repo, parent)
		if err != nil {
			return "", err
		}
		defer aTree.Free()
	}

	bTree, err := objectToTree(repo, child)
	if err != nil {
		return "", err
	}
	defer bTree.Free()

	options, err := git.DefaultDiffOptions()
	if err != nil {
		return "", err
	}

	diff, err := repo.DiffTreeToTree(aTree, bTree, &options)
	if err != nil {
		return "", err
	}
	defer diff.Free()

	numDeltas, err := diff.NumDeltas()
	if err != nil {
		return "", err
	}

	var results []string
	for i := 0; i < numDeltas; i++ {
		patch, err := diff.Patch(i)
		if err != nil {
			return "", err
		}
		patchString, err := patch.String()
		if err != nil {
			return "", err
		}
		patch.Free()

		results = append(results, patchString)
	}

	return strings.Join(results, "\n"), nil
}

func (c *client) BranchCredentialCounts(
	logger lager.Logger,
	repositoryPath string,
	sniffer sniff.Sniffer,
	branchType git.BranchType,
) (map[string]uint, error) {
	repo, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return nil, err
	}
	defer repo.Free()

	it, err := repo.NewBranchIterator(branchType)
	if err != nil {
		return nil, err
	}
	defer it.Free()

	var branch *git.Branch
	var target *git.Oid
	var commit *git.Commit
	var tree *git.Tree
	var branchName string
	var blob *git.Blob

	entryCounts := make(map[git.Oid]uint)
	branchCounts := make(map[string]uint)

	for {
		branch, _, err = it.Next()
		if err != nil {
			break
		}

		target = branch.Target()
		if target == nil {
			continue
		}

		commit, err = repo.LookupCommit(target)
		if err != nil {
			return nil, err
		}

		tree, err = commit.Tree()
		if err != nil {
			return nil, err
		}

		branchName, err = branch.Name()
		if err != nil {
			return nil, err
		}

		err = tree.Walk(func(root string, entry *git.TreeEntry) int {
			if entry.Type == git.ObjectBlob {
				if count, ok := entryCounts[*entry.Id]; ok {
					if count > 0 {
						branchCounts[branchName] += count
					}
					return 0
				}

				blob, err = repo.LookupBlob(entry.Id)
				if err != nil {
					return -1
				}

				var count uint
				r := bufio.NewReader(bytes.NewReader(blob.Contents()))
				mime := mimetype.Mimetype(logger, r)
				if mime == "" || strings.HasPrefix(mime, "text") {
					sniffer.Sniff(
						logger,
						filescanner.New(r, entry.Name),
						func(lager.Logger, scanners.Violation) error {
							count++
							return nil
						},
					)
				}

				entryCounts[*entry.Id] = count
				branchCounts[branchName] += count
			}

			return 0
		})

		if err != nil {
			return nil, err
		}
	}

	if blob != nil {
		blob.Free()
	}

	if tree != nil {
		tree.Free()
	}

	if commit != nil {
		commit.Free()
	}

	if branch != nil {
		branch.Free()
	}

	return branchCounts, nil
}

func objectToTree(repo *git.Repository, oid *git.Oid) (*git.Tree, error) {
	object, err := repo.Lookup(oid)
	if err != nil {
		return nil, err
	}
	defer object.Free()

	commit, err := object.AsCommit()
	if err != nil {
		return nil, err
	}
	defer commit.Free()

	tree, err := commit.Tree()
	if err != nil {
		return nil, err
	}

	return tree, nil
}

func newCredentialsCallback(privateKeyPath, publicKeyPath string) git.CredentialsCallback {
	return func(url string, username string, allowedTypes git.CredType) (git.ErrorCode, *git.Cred) {
		passphrase := ""
		ret, cred := git.NewCredSshKey(username, publicKeyPath, privateKeyPath, passphrase)
		if ret != 0 {
			fmt.Printf("ret: %d\n", ret)
		}
		return git.ErrorCode(ret), &cred
	}
}

func certificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode {
	// should return an error code if the cert isn't valid
	return git.ErrorCode(0)
}

func newFetchOptions(privateKeyPath, publicKeyPath string) *git.FetchOptions {
	credentialsCallback := newCredentialsCallback(privateKeyPath, publicKeyPath)

	return &git.FetchOptions{
		UpdateFetchhead: true,
		RemoteCallbacks: git.RemoteCallbacks{
			CredentialsCallback:      credentialsCallback,
			CertificateCheckCallback: certificateCheckCallback,
		},
	}
}
<|endoftext|>


<commit_before>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package blob contains types related to storage of content-addressed blobs.
package blob
<commit_msg>Added a warning.<commit_after>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package blob contains types related to storage of content-addressed blobs.
// It is an implementation detail; you should not use it directly.
package blob
<|endoftext|>


<commit_before>package brats_test

import (
	"github.com/cloudfoundry/libbuildpack/bratshelper"
	"github.com/cloudfoundry/libbuildpack/cutlass"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"golang.org/x/crypto/bcrypt"
)

var _ = Describe("Python buildpack", func() {
	bratshelper.UnbuiltBuildpack("python", CopyBrats)
	bratshelper.DeployingAnAppWithAnUpdatedVersionOfTheSameBuildpack(CopyBrats)
	bratshelper.StagingWithBuildpackThatSetsEOL("python", CopyBrats)
	bratshelper.StagingWithADepThatIsNotTheLatest("python", CopyBrats)
	bratshelper.StagingWithCustomBuildpackWithCredentialsInDependencies(`python\-[\d\.]+\-linux\-x64\-(cflinuxfs.*-)?[\da-f]+\.tgz`, CopyBrats)
	bratshelper.DeployAppWithExecutableProfileScript("python", CopyBrats)
	bratshelper.DeployAnAppWithSensitiveEnvironmentVariables(CopyBrats)

	bratshelper.ForAllSupportedVersions("python", CopyBrats, func(pythonVersion string, app *cutlass.App) {
		PushApp(app)

		By("runs a simple webserver", func() {
			Expect(app.GetBody("/")).To(ContainSubstring("Hello World!"))
		})
		By("uses the correct python version", func() {
			Expect(app.Stdout.String()).To(ContainSubstring("Installing python " + pythonVersion))
			Expect(app.GetBody("/version")).To(ContainSubstring(pythonVersion))
		})
		By("encrypts with bcrypt", func() {
			hashedPassword, err := app.GetBody("/bcrypt")
			Expect(err).ToNot(HaveOccurred())
			Expect(bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte("Hello, bcrypt"))).ToNot(HaveOccurred())
		})
		By("supports postgres by raising a no connection error", func() {
			Expect(app.GetBody("/pg")).To(ContainSubstring("could not connect to server: No such file or directory"))
		})
		By("supports mysql by raising a no connection error", func() {
			Expect(app.GetBody("/mysql")).To(ContainSubstring("Can't connect to local MySQL server through socket"))
		})
		By("supports loading and running the hiredis lib", func() {
			Expect(app.GetBody("/redis")).To(ContainSubstring("Hello"))
		})
		By("supports the proper version of unicode", func() {
			maxUnicode := "1114111"
			Expect(app.GetBody("/unicode")).To(ContainSubstring("max unicode: " + maxUnicode))
		})
	})
})
<commit_msg>Update bratshelper.StagingWithCustomBuildpackWithCredentialsInDependencies<commit_after>package brats_test

import (
	"github.com/cloudfoundry/libbuildpack/bratshelper"
	"github.com/cloudfoundry/libbuildpack/cutlass"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"golang.org/x/crypto/bcrypt"
)

var _ = Describe("Python buildpack", func() {
	bratshelper.UnbuiltBuildpack("python", CopyBrats)
	bratshelper.DeployingAnAppWithAnUpdatedVersionOfTheSameBuildpack(CopyBrats)
	bratshelper.StagingWithBuildpackThatSetsEOL("python", CopyBrats)
	bratshelper.StagingWithADepThatIsNotTheLatest("python", CopyBrats)
	bratshelper.StagingWithCustomBuildpackWithCredentialsInDependencies(CopyBrats)
	bratshelper.DeployAppWithExecutableProfileScript("python", CopyBrats)
	bratshelper.DeployAnAppWithSensitiveEnvironmentVariables(CopyBrats)

	bratshelper.ForAllSupportedVersions("python", CopyBrats, func(pythonVersion string, app *cutlass.App) {
		PushApp(app)

		By("runs a simple webserver", func() {
			Expect(app.GetBody("/")).To(ContainSubstring("Hello World!"))
		})
		By("uses the correct python version", func() {
			Expect(app.Stdout.String()).To(ContainSubstring("Installing python " + pythonVersion))
			Expect(app.GetBody("/version")).To(ContainSubstring(pythonVersion))
		})
		By("encrypts with bcrypt", func() {
			hashedPassword, err := app.GetBody("/bcrypt")
			Expect(err).ToNot(HaveOccurred())
			Expect(bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte("Hello, bcrypt"))).ToNot(HaveOccurred())
		})
		By("supports postgres by raising a no connection error", func() {
			Expect(app.GetBody("/pg")).To(ContainSubstring("could not connect to server: No such file or directory"))
		})
		By("supports mysql by raising a no connection error", func() {
			Expect(app.GetBody("/mysql")).To(ContainSubstring("Can't connect to local MySQL server through socket"))
		})
		By("supports loading and running the hiredis lib", func() {
			Expect(app.GetBody("/redis")).To(ContainSubstring("Hello"))
		})
		By("supports the proper version of unicode", func() {
			maxUnicode := "1114111"
			Expect(app.GetBody("/unicode")).To(ContainSubstring("max unicode: " + maxUnicode))
		})
	})
})
<|endoftext|>


<commit_before><commit_msg>Fix logging prefix for HTTP service<commit_after><|endoftext|>


<commit_before>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package zip

import (
	"bytes"
	"io/ioutil"
	"rand"
	"testing"
)

// TODO(adg): a more sophisticated test suite

type WriteTest struct {
	Name   string
	Data   []byte
	Method uint16
	Mode   uint32
}

var writeTests = []WriteTest{
	WriteTest{
		Name:   "foo",
		Data:   []byte("Rabbits, guinea pigs, gophers, marsupial rats, and quolls."),
		Method: Store,
	},
	WriteTest{
		Name:   "bar",
		Data:   nil, // large data set in the test
		Method: Deflate,
		Mode:   0x81ed,
	},
}

func TestWriter(t *testing.T) {
	largeData := make([]byte, 1<<17)
	for i := range largeData {
		largeData[i] = byte(rand.Int())
	}
	writeTests[1].Data = largeData
	defer func() {
		writeTests[1].Data = nil
	}()

	// write a zip file
	buf := new(bytes.Buffer)
	w := NewWriter(buf)

	for _, wt := range writeTests {
		testCreate(t, w, &wt)
	}

	if err := w.Close(); err != nil {
		t.Fatal(err)
	}

	// read it back
	r, err := NewReader(sliceReaderAt(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		t.Fatal(err)
	}
	for i, wt := range writeTests {
		testReadFile(t, r.File[i], &wt)
	}
}

func testCreate(t *testing.T, w *Writer, wt *WriteTest) {
	header := &FileHeader{
		Name:   wt.Name,
		Method: wt.Method,
	}
	if wt.Mode != 0 {
		header.SetMode(wt.Mode)
	}
	f, err := w.CreateHeader(header)
	if err != nil {
		t.Fatal(err)
	}
	_, err = f.Write(wt.Data)
	if err != nil {
		t.Fatal(err)
	}
}

func testReadFile(t *testing.T, f *File, wt *WriteTest) {
	if f.Name != wt.Name {
		t.Fatal("File name: got %q, want %q", f.Name, wt.Name)
	}
	testFileMode(t, f, wt.Mode)
	rc, err := f.Open()
	if err != nil {
		t.Fatal("opening:", err)
	}
	b, err := ioutil.ReadAll(rc)
	if err != nil {
		t.Fatal("reading:", err)
	}
	err = rc.Close()
	if err != nil {
		t.Fatal("closing:", err)
	}
	if !bytes.Equal(b, wt.Data) {
		t.Errorf("File contents %q, want %q", b, wt.Data)
	}
}
<commit_msg>archive/zip: fix Fatal call Error found by govet.<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package zip

import (
	"bytes"
	"io/ioutil"
	"rand"
	"testing"
)

// TODO(adg): a more sophisticated test suite

type WriteTest struct {
	Name   string
	Data   []byte
	Method uint16
	Mode   uint32
}

var writeTests = []WriteTest{
	WriteTest{
		Name:   "foo",
		Data:   []byte("Rabbits, guinea pigs, gophers, marsupial rats, and quolls."),
		Method: Store,
	},
	WriteTest{
		Name:   "bar",
		Data:   nil, // large data set in the test
		Method: Deflate,
		Mode:   0x81ed,
	},
}

func TestWriter(t *testing.T) {
	largeData := make([]byte, 1<<17)
	for i := range largeData {
		largeData[i] = byte(rand.Int())
	}
	writeTests[1].Data = largeData
	defer func() {
		writeTests[1].Data = nil
	}()

	// write a zip file
	buf := new(bytes.Buffer)
	w := NewWriter(buf)

	for _, wt := range writeTests {
		testCreate(t, w, &wt)
	}

	if err := w.Close(); err != nil {
		t.Fatal(err)
	}

	// read it back
	r, err := NewReader(sliceReaderAt(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		t.Fatal(err)
	}
	for i, wt := range writeTests {
		testReadFile(t, r.File[i], &wt)
	}
}

func testCreate(t *testing.T, w *Writer, wt *WriteTest) {
	header := &FileHeader{
		Name:   wt.Name,
		Method: wt.Method,
	}
	if wt.Mode != 0 {
		header.SetMode(wt.Mode)
	}
	f, err := w.CreateHeader(header)
	if err != nil {
		t.Fatal(err)
	}
	_, err = f.Write(wt.Data)
	if err != nil {
		t.Fatal(err)
	}
}

func testReadFile(t *testing.T, f *File, wt *WriteTest) {
	if f.Name != wt.Name {
		t.Fatalf("File name: got %q, want %q", f.Name, wt.Name)
	}
	testFileMode(t, f, wt.Mode)
	rc, err := f.Open()
	if err != nil {
		t.Fatal("opening:", err)
	}
	b, err := ioutil.ReadAll(rc)
	if err != nil {
		t.Fatal("reading:", err)
	}
	err = rc.Close()
	if err != nil {
		t.Fatal("closing:", err)
	}
	if !bytes.Equal(b, wt.Data) {
		t.Errorf("File contents %q, want %q", b, wt.Data)
	}
}
<|endoftext|>


<commit_before>package gobrightbox

// Volume represents a Brightbox Volume
// https://api.gb1.brightbox.com/1.0/#volume
type Volume struct {
	ID          string
	Name        string
	Status      string
	Description string
	Encrypted   bool
	Size        int
	StorageType string `json:"storage_type"`
	Server      *Server
	Account     *Account
	Image       *Image
}

// VolumeOptions is used to create and update volumes
// create and update servers.
type VolumeOptions struct {
	ID    string  `json:"-"`
	Size  *int    `json:"size,omitempty"`
	Image *string `json:"image,omitempty"`
}

// VolumeResizeOptions is used to change the size of a volume
type VolumeResizeOptions struct {
	From int `json:"from"`
	To   int `json:"to"`
}

// ResizeVolume changes the size of a volume
func (c *Client) ResizeVolume(identifier string, options *VolumeResizeOptions) error {
	_, err := c.MakeAPIRequest("POST", "/1.0/volumes/"+identifier+"/resize", options, nil)
	return err
}
<commit_msg>Refactor ResizeVolume<commit_after>package gobrightbox

// Volume represents a Brightbox Volume
// https://api.gb1.brightbox.com/1.0/#volume
type Volume struct {
	ID          string
	Name        string
	Status      string
	Description string
	Encrypted   bool
	Size        int
	StorageType string `json:"storage_type"`
	Server      *Server
	Account     *Account
	Image       *Image
}

// VolumeOptions is used to create and update volumes
// create and update servers.
type VolumeOptions struct {
	ID    string  `json:"-"`
	Size  *int    `json:"size,omitempty"`
	Image *string `json:"image,omitempty"`
}

// ResizeVolume changes the size of a volume
func (c *Client) ResizeVolume(identifier string, oldSize int, newSize int) error {
	options := struct {
		From int `json:"from"`
		To   int `json:"to"`
	}{oldSize, newSize}
	_, err := c.MakeAPIRequest("POST", "/1.0/volumes/"+identifier+"/resize", &options, nil)
	return err
}
<|endoftext|>


<commit_before>package vunikbd

import (
	"fmt"
	"time"

	"github.com/bendahl/uinput"
)

type Keyboard struct {
	name  string
	delay time.Duration
	vk    uinput.Keyboard
}

func NewKeyboard(name string, delay time.Duration) (*Keyboard, error) {
	var err error

	k := Keyboard{
		name:  name,
		delay: delay,
	}

	k.vk, err = uinput.CreateKeyboard("/dev/uinput", k.name)

	return &k, err
}

func (k *Keyboard) Type(s string) {
	for _, r := range s {
		h := fmt.Sprintf("%x\n", r)
		k.vk.SendKeyPress(uinput.KEY_LEFTCTRL)
		k.sleep()
		k.vk.SendKeyPress(uinput.KEY_LEFTSHIFT)
		k.sleep()
		k.vk.SendKeyPress(uinput.KEY_U)
		k.sleep()
		k.vk.SendKeyRelease(uinput.KEY_U)
		k.sleep()
		k.vk.SendKeyRelease(uinput.KEY_LEFTCTRL)
		k.sleep()
		k.vk.SendKeyRelease(uinput.KEY_LEFTSHIFT)
		k.sleep()
		for _, v := range h {
			k.vk.SendKeyPress(keycodes[v])
			k.sleep()
			k.vk.SendKeyRelease(keycodes[v])
			k.sleep()
		}
		k.vk.SendKeyPress(uinput.KEY_ENTER)
		k.sleep()
		k.vk.SendKeyRelease(uinput.KEY_ENTER)
		k.sleep()
	}
}

func (k *Keyboard) sleep() {
	time.Sleep(k.delay)
}

var keycodes map[rune]int

func init() {
	keycodes = make(map[rune]int)
	keycodes['0'] = uinput.KEY_KP0
	keycodes['1'] = uinput.KEY_KP1
	keycodes['2'] = uinput.KEY_KP2
	keycodes['3'] = uinput.KEY_KP3
	keycodes['4'] = uinput.KEY_KP4
	keycodes['5'] = uinput.KEY_KP5
	keycodes['6'] = uinput.KEY_KP6
	keycodes['7'] = uinput.KEY_KP7
	keycodes['8'] = uinput.KEY_KP8
	keycodes['9'] = uinput.KEY_KP9
	keycodes['a'] = uinput.KEY_A
	keycodes['b'] = uinput.KEY_B
	keycodes['c'] = uinput.KEY_C
	keycodes['d'] = uinput.KEY_D
	keycodes['e'] = uinput.KEY_E
	keycodes['f'] = uinput.KEY_F
}
<commit_msg>Minor optimizations<commit_after>package vunikbd

import (
	"fmt"
	"time"

	"github.com/bendahl/uinput"
)

type Keyboard struct {
	name  string
	delay time.Duration
	vk    uinput.Keyboard
}

func NewKeyboard(name string, delay time.Duration) (*Keyboard, error) {
	var err error

	k := Keyboard{
		name:  name,
		delay: delay,
	}

	k.vk, err = uinput.CreateKeyboard("/dev/uinput", k.name)

	return &k, err
}

func (k *Keyboard) Type(s string) {
	for _, r := range s {
		h := fmt.Sprintf("%x\n", r)
		k.vk.SendKeyPress(uinput.KEY_LEFTCTRL)
		k.sleep()
		k.vk.SendKeyPress(uinput.KEY_LEFTSHIFT)
		k.sleep()
		k.vk.SendKeyPress(uinput.KEY_U)
		k.sleep()
		k.vk.SendKeyRelease(uinput.KEY_U)
		k.sleep()
		for _, v := range h {
			k.vk.SendKeyPress(keycodes[v])
			k.sleep()
			k.vk.SendKeyRelease(keycodes[v])
			k.sleep()
		}
		k.vk.SendKeyRelease(uinput.KEY_LEFTCTRL)
		k.sleep()
		k.vk.SendKeyRelease(uinput.KEY_LEFTSHIFT)
		k.sleep()
	}
}

func (k *Keyboard) sleep() {
	time.Sleep(k.delay)
}

var keycodes map[rune]int

func init() {
	keycodes = make(map[rune]int)
	keycodes['0'] = uinput.KEY_KP0
	keycodes['1'] = uinput.KEY_KP1
	keycodes['2'] = uinput.KEY_KP2
	keycodes['3'] = uinput.KEY_KP3
	keycodes['4'] = uinput.KEY_KP4
	keycodes['5'] = uinput.KEY_KP5
	keycodes['6'] = uinput.KEY_KP6
	keycodes['7'] = uinput.KEY_KP7
	keycodes['8'] = uinput.KEY_KP8
	keycodes['9'] = uinput.KEY_KP9
	keycodes['a'] = uinput.KEY_A
	keycodes['b'] = uinput.KEY_B
	keycodes['c'] = uinput.KEY_C
	keycodes['d'] = uinput.KEY_D
	keycodes['e'] = uinput.KEY_E
	keycodes['f'] = uinput.KEY_F
}
<|endoftext|>


<commit_before>/*
Copyright 2014 CoreOS Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package wal

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/coreos/etcd/raft"
)

var (
	infoType  = int64(1)
	entryType = int64(2)
	stateType = int64(3)
)

type WAL struct {
	f   *os.File
	bw  *bufio.Writer
	buf *bytes.Buffer
}

func newWAL(f *os.File) *WAL {
	return &WAL{f, bufio.NewWriter(f), new(bytes.Buffer)}
}

func New(path string) (*WAL, error) {
	f, err := os.Open(path)
	if err == nil {
		f.Close()
		return nil, os.ErrExist
	}
	f, err = os.Create(path)
	if err != nil {
		return nil, err
	}
	return newWAL(f), nil
}

func Open(path string) (*WAL, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	return newWAL(f), nil
}

func (w *WAL) Sync() error {
	if err := w.bw.Flush(); err != nil {
		return err
	}
	return w.f.Sync()
}

func (w *WAL) Close() {
	if w.f != nil {
		w.Sync()
		w.f.Close()
	}
}

func (w *WAL) SaveInfo(id int64) error {
	if err := w.checkAtHead(); err != nil {
		return err
	}
	w.buf.Reset()
	err := binary.Write(w.buf, binary.LittleEndian, id)
	if err != nil {
		panic(err)
	}
	return writeBlock(w.bw, infoType, w.buf.Bytes())
}

func (w *WAL) SaveEntry(e *raft.Entry) error {
	// protobuf?
	b, err := json.Marshal(e)
	if err != nil {
		panic(err)
	}
	return writeBlock(w.bw, entryType, b)
}

func (w *WAL) SaveState(s *raft.State) error {
	w.buf.Reset()
	err := binary.Write(w.buf, binary.LittleEndian, s)
	if err != nil {
		panic(err)
	}
	return writeBlock(w.bw, stateType, w.buf.Bytes())
}

func (w *WAL) checkAtHead() error {
	o, err := w.f.Seek(0, os.SEEK_CUR)
	if err != nil {
		return err
	}
	if o != 0 || w.bw.Buffered() != 0 {
		return fmt.Errorf("cannot write info at %d, expect 0", max(o, int64(w.bw.Buffered())))
	}
	return nil
}

type Node struct {
	Id    int64
	Ents  []raft.Entry
	State raft.State
}

func (w *WAL) LoadNode() (*Node, error) {
	if err := w.checkAtHead(); err != nil {
		return nil, err
	}
	br := bufio.NewReader(w.f)
	b := &block{}

	err := readBlock(br, b)
	if err != nil {
		return nil, err
	}
	if b.t != infoType {
		return nil, fmt.Errorf("the first block of wal is not infoType but %d", b.t)
	}
	id, err := loadInfo(b.d)
	if err != nil {
		return nil, err
	}

	ents := make([]raft.Entry, 0)
	var state raft.State
	for err = readBlock(br, b); err == nil; err = readBlock(br, b) {
		switch b.t {
		case entryType:
			e, err := loadEntry(b.d)
			if err != nil {
				return nil, err
			}
			ents = append(ents, e)
		case stateType:
			s, err := loadState(b.d)
			if err != nil {
				return nil, err
			}
			state = s
		default:
			return nil, fmt.Errorf("unexpected block type %d", b.t)
		}
	}
	if err != io.EOF {
		return nil, err
	}
	return &Node{id, ents, state}, nil
}

func loadInfo(d []byte) (int64, error) {
	if len(d) != 8 {
		return 0, fmt.Errorf("len = %d, want 8", len(d))
	}
	buf := bytes.NewBuffer(d)
	return readInt64(buf)
}

func loadEntry(d []byte) (raft.Entry, error) {
	var e raft.Entry
	err := json.Unmarshal(d, &e)
	return e, err
}

func loadState(d []byte) (raft.State, error) {
	var s raft.State
	buf := bytes.NewBuffer(d)
	err := binary.Read(buf, binary.LittleEndian, &s)
	return s, err
}

func writeInt64(w io.Writer, n int64) error {
	return binary.Write(w, binary.LittleEndian, n)
}

func readInt64(r io.Reader) (int64, error) {
	var n int64
	err := binary.Read(r, binary.LittleEndian, &n)
	return n, err
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
<commit_msg>wal: fix append entry<commit_after>/*
Copyright 2014 CoreOS Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package wal

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/coreos/etcd/raft"
)

var (
	infoType  = int64(1)
	entryType = int64(2)
	stateType = int64(3)
)

type WAL struct {
	f   *os.File
	bw  *bufio.Writer
	buf *bytes.Buffer
}

func newWAL(f *os.File) *WAL {
	return &WAL{f, bufio.NewWriter(f), new(bytes.Buffer)}
}

func New(path string) (*WAL, error) {
	f, err := os.Open(path)
	if err == nil {
		f.Close()
		return nil, os.ErrExist
	}
	f, err = os.Create(path)
	if err != nil {
		return nil, err
	}
	return newWAL(f), nil
}

func Open(path string) (*WAL, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	return newWAL(f), nil
}

func (w *WAL) Sync() error {
	if err := w.bw.Flush(); err != nil {
		return err
	}
	return w.f.Sync()
}

func (w *WAL) Close() {
	if w.f != nil {
		w.Sync()
		w.f.Close()
	}
}

func (w *WAL) SaveInfo(id int64) error {
	if err := w.checkAtHead(); err != nil {
		return err
	}
	w.buf.Reset()
	err := binary.Write(w.buf, binary.LittleEndian, id)
	if err != nil {
		panic(err)
	}
	return writeBlock(w.bw, infoType, w.buf.Bytes())
}

func (w *WAL) SaveEntry(e *raft.Entry) error {
	// protobuf?
	b, err := json.Marshal(e)
	if err != nil {
		panic(err)
	}
	return writeBlock(w.bw, entryType, b)
}

func (w *WAL) SaveState(s *raft.State) error {
	w.buf.Reset()
	err := binary.Write(w.buf, binary.LittleEndian, s)
	if err != nil {
		panic(err)
	}
	return writeBlock(w.bw, stateType, w.buf.Bytes())
}

func (w *WAL) checkAtHead() error {
	o, err := w.f.Seek(0, os.SEEK_CUR)
	if err != nil {
		return err
	}
	if o != 0 || w.bw.Buffered() != 0 {
		return fmt.Errorf("cannot write info at %d, expect 0", max(o, int64(w.bw.Buffered())))
	}
	return nil
}

type Node struct {
	Id    int64
	Ents  []raft.Entry
	State raft.State
}

func (w *WAL) LoadNode() (*Node, error) {
	if err := w.checkAtHead(); err != nil {
		return nil, err
	}
	br := bufio.NewReader(w.f)
	b := &block{}

	err := readBlock(br, b)
	if err != nil {
		return nil, err
	}
	if b.t != infoType {
		return nil, fmt.Errorf("the first block of wal is not infoType but %d", b.t)
	}
	id, err := loadInfo(b.d)
	if err != nil {
		return nil, err
	}

	ents := make([]raft.Entry, 0)
	var state raft.State
	for err = readBlock(br, b); err == nil; err = readBlock(br, b) {
		switch b.t {
		case entryType:
			e, err := loadEntry(b.d)
			if err != nil {
				return nil, err
			}
			ents = append(ents[:e.Index-1], e)
		case stateType:
			s, err := loadState(b.d)
			if err != nil {
				return nil, err
			}
			state = s
		default:
			return nil, fmt.Errorf("unexpected block type %d", b.t)
		}
	}
	if err != io.EOF {
		return nil, err
	}
	return &Node{id, ents, state}, nil
}

func loadInfo(d []byte) (int64, error) {
	if len(d) != 8 {
		return 0, fmt.Errorf("len = %d, want 8", len(d))
	}
	buf := bytes.NewBuffer(d)
	return readInt64(buf)
}

func loadEntry(d []byte) (raft.Entry, error) {
	var e raft.Entry
	err := json.Unmarshal(d, &e)
	return e, err
}

func loadState(d []byte) (raft.State, error) {
	var s raft.State
	buf := bytes.NewBuffer(d)
	err := binary.Read(buf, binary.LittleEndian, &s)
	return s, err
}

func writeInt64(w io.Writer, n int64) error {
	return binary.Write(w, binary.LittleEndian, n)
}

func readInt64(r io.Reader) (int64, error) {
	var n int64
	err := binary.Read(r, binary.LittleEndian, &n)
	return n, err
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
<|endoftext|>


<commit_before>package http2

import (
	"golang.org/x/net/http2"

	"github.com/summerwind/h2spec/config"
	"github.com/summerwind/h2spec/spec"
)

func Settings() *spec.TestGroup {
	tg := NewTestGroup("6.5", "SETTINGS")

	// ACK (0x1):
	// When set, bit 0 indicates that this frame acknowledges receipt
	// and application of the peer's SETTINGS frame. When this bit is
	// set, the payload of the SETTINGS frame MUST be empty. Receipt of
	// a SETTINGS frame with the ACK flag set and a length field value
	// other than 0 MUST be treated as a connection error (Section 5.4.1)
	// of type FRAME_SIZE_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS frame with ACK flag and payload",
		Requirement: "The endpoint MUST respond with a connection error of type FRAME_SIZE_ERROR.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Handshake()
			if err != nil {
				return err
			}

			// SETTINGS frame:
			// length: 0, flags: 0x1, stream_id: 0x0
			conn.Send([]byte("\x00\x00\x01\x04\x01\x00\x00\x00\x00"))
			conn.Send([]byte("\x00"))

			return spec.VerifyConnectionError(conn, http2.ErrCodeFrameSize)
		},
	})

	// SETTINGS frames always apply to a connection, never a single
	// stream. The stream identifier for a SETTINGS frame MUST be
	// zero (0x0). If an endpoint receives a SETTINGS frame whose
	// stream identifier field is anything other than 0x0, the
	// endpoint MUST respond with a connection error (Section 5.4.1)
	// of type PROTOCOL_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS frame with a stream identifier other than 0x0",
		Requirement: "The endpoint MUST respond with a connection error of type PROTOCOL_ERROR.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Handshake()
			if err != nil {
				return err
			}

			// SETTINGS frame:
			// length: 6, flags: 0x0, stream_id: 0x1
			conn.Send([]byte("\x00\x00\x06\x04\x00\x00\x00\x00\x01"))
			conn.Send([]byte("\x00\x03\x00\x00\x00\x64"))

			return spec.VerifyConnectionError(conn, http2.ErrCodeProtocol)
		},
	})

	// The SETTINGS frame affects connection state. A badly formed or
	// incomplete SETTINGS frame MUST be treated as a connection error
	// (Section 5.4.1) of type PROTOCOL_ERROR.
	//
	// A SETTINGS frame with a length other than a multiple of 6 octets
	// MUST be treated as a connection error (Section 5.4.1) of type
	// FRAME_SIZE_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS frame with a length other than a multiple of 6 octets",
		Requirement: "The endpoint MUST respond with a connection error of type FRAME_SIZE_ERROR.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Handshake()
			if err != nil {
				return err
			}

			// SETTINGS frame:
			// length: 8, flags: 0x0, stream_id: 0x0
			conn.Send([]byte("\x00\x00\x09\x04\x00\x00\x00\x00\x00"))
			conn.Send([]byte("\x00\x03\x00\x00\x00\x64\x00\x02"))

			codes := []http2.ErrCode{
				http2.ErrCodeProtocol,
				http2.ErrCodeFrameSize,
			}
			return spec.VerifyStreamError(conn, codes...)
		},
	})

	tg.AddTestGroup(DefinedSETTINGSParameters())
	tg.AddTestGroup(SettingsSynchronization())

	return tg
}
<commit_msg>Send invalid SETTINGS with length of 3<commit_after>package http2

import (
	"golang.org/x/net/http2"

	"github.com/summerwind/h2spec/config"
	"github.com/summerwind/h2spec/spec"
)

func Settings() *spec.TestGroup {
	tg := NewTestGroup("6.5", "SETTINGS")

	// ACK (0x1):
	// When set, bit 0 indicates that this frame acknowledges receipt
	// and application of the peer's SETTINGS frame. When this bit is
	// set, the payload of the SETTINGS frame MUST be empty. Receipt of
	// a SETTINGS frame with the ACK flag set and a length field value
	// other than 0 MUST be treated as a connection error (Section 5.4.1)
	// of type FRAME_SIZE_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS frame with ACK flag and payload",
		Requirement: "The endpoint MUST respond with a connection error of type FRAME_SIZE_ERROR.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Handshake()
			if err != nil {
				return err
			}

			// SETTINGS frame:
			// length: 0, flags: 0x1, stream_id: 0x0
			conn.Send([]byte("\x00\x00\x01\x04\x01\x00\x00\x00\x00"))
			conn.Send([]byte("\x00"))

			return spec.VerifyConnectionError(conn, http2.ErrCodeFrameSize)
		},
	})

	// SETTINGS frames always apply to a connection, never a single
	// stream. The stream identifier for a SETTINGS frame MUST be
	// zero (0x0). If an endpoint receives a SETTINGS frame whose
	// stream identifier field is anything other than 0x0, the
	// endpoint MUST respond with a connection error (Section 5.4.1)
	// of type PROTOCOL_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS frame with a stream identifier other than 0x0",
		Requirement: "The endpoint MUST respond with a connection error of type PROTOCOL_ERROR.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Handshake()
			if err != nil {
				return err
			}

			// SETTINGS frame:
			// length: 6, flags: 0x0, stream_id: 0x1
			conn.Send([]byte("\x00\x00\x06\x04\x00\x00\x00\x00\x01"))
			conn.Send([]byte("\x00\x03\x00\x00\x00\x64"))

			return spec.VerifyConnectionError(conn, http2.ErrCodeProtocol)
		},
	})

	// The SETTINGS frame affects connection state. A badly formed or
	// incomplete SETTINGS frame MUST be treated as a connection error
	// (Section 5.4.1) of type PROTOCOL_ERROR.
	//
	// A SETTINGS frame with a length other than a multiple of 6 octets
	// MUST be treated as a connection error (Section 5.4.1) of type
	// FRAME_SIZE_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends a SETTINGS frame with a length other than a multiple of 6 octets",
		Requirement: "The endpoint MUST respond with a connection error of type FRAME_SIZE_ERROR.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Handshake()
			if err != nil {
				return err
			}

			// SETTINGS frame:
			// length: 3, flags: 0x0, stream_id: 0x0
			conn.Send([]byte("\x00\x00\x03\x04\x00\x00\x00\x00\x00"))
			conn.Send([]byte("\x00\x03\x00"))

			codes := []http2.ErrCode{
				http2.ErrCodeProtocol,
				http2.ErrCodeFrameSize,
			}
			return spec.VerifyStreamError(conn, codes...)
		},
	})

	tg.AddTestGroup(DefinedSETTINGSParameters())
	tg.AddTestGroup(SettingsSynchronization())

	return tg
}
<|endoftext|>


<commit_before>package httpbackend

import (
	"encoding/json"
	"net/http"

	"goji.io/pat"

	"github.com/khades/servbot/models"

	"github.com/khades/servbot/repos"
)

type subdayWithMod struct {
	*models.Subday
	IsMod bool `json:"isMod"`
}
type subdayWithModNoWinners struct {
	*models.SubdayNoWinners
	IsMod bool `json:"isMod"`
}

func subdayList(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	results, error := repos.GetSubdays(channelID)
	if error != nil {
		writeJSONError(w, error.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(&results)
}

func subdayLast(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	channelInfo, error := repos.GetChannelInfo(channelID)
	if error != nil {
		writeJSONError(w, "That channel is not defined", http.StatusForbidden)
		return
	}
	if channelInfo.GetIfUserIsMod(&s.UserID) == true {
		result, error := repos.GetLastSubdayMod(channelID)
		if error != nil {
			writeJSONError(w, error.Error(), http.StatusInternalServerError)
			return
		}
		object := subdayWithMod{result, true}
		json.NewEncoder(w).Encode(object)
	} else {
		result, error := repos.GetLastSubday(channelID)
		if error != nil {
			writeJSONError(w, error.Error(), http.StatusInternalServerError)
			return
		}
		object := subdayWithModNoWinners{result, false}

		json.NewEncoder(w).Encode(object)
	}

}

func subdayByID(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	channelInfo, error := repos.GetChannelInfo(channelID)
	if error != nil {
		writeJSONError(w, "That channel is not defined", http.StatusForbidden)
		return
	}
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	if channelInfo.GetIfUserIsMod(&s.UserID) == true {
		result, error := repos.GetSubdayByIdMod(&id)
		if error != nil {
			writeJSONError(w, error.Error(), http.StatusInternalServerError)
			return
		}
		object := subdayWithMod{result, true}

		json.NewEncoder(w).Encode(object)

	} else {
		result, error := repos.GetSubdayById(&id)
		if error != nil {
			writeJSONError(w, error.Error(), http.StatusInternalServerError)
			return
		}
		object := subdayWithModNoWinners{result, false}

		json.NewEncoder(w).Encode(object)
	}
}
func subdayRandomize(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	winner := repos.PickRandomWinnerForSubday(channelID, &id)
	if winner != nil {
		json.NewEncoder(w).Encode(winner)
	} else {
		json.NewEncoder(w).Encode(optionResponse{"OK"})
	}

}
func subdayPullWinner (w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	user := pat.Param(r, "user")
	if user == "" {
		writeJSONError(w, "user", http.StatusNotFound)
		return
	}
	repos.SubdayPullWinner(&id, &user)
	json.NewEncoder(w).Encode(optionResponse{"OK"})

}
func subdayClose(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	repos.CloseSubday(channelID, &id)
	json.NewEncoder(w).Encode(optionResponse{"OK"})

}
<commit_msg>Feature: Ouputting last subday is id == last<commit_after>package httpbackend

import (
	"encoding/json"
	"net/http"

	"goji.io/pat"

	"github.com/khades/servbot/models"

	"github.com/khades/servbot/repos"
)

type subdayWithMod struct {
	*models.Subday
	IsMod bool `json:"isMod"`
}
type subdayWithModNoWinners struct {
	*models.SubdayNoWinners
	IsMod bool `json:"isMod"`
}

func subdayList(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	results, error := repos.GetSubdays(channelID)
	if error != nil {
		writeJSONError(w, error.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(&results)
}

// func subdayLast(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
// 	channelInfo, error := repos.GetChannelInfo(channelID)
// 	if error != nil {
// 		writeJSONError(w, "That channel is not defined", http.StatusForbidden)
// 		return
// 	}
// 	if channelInfo.GetIfUserIsMod(&s.UserID) == true {
// 		result, error := repos.GetLastSubdayMod(channelID)
// 		if error != nil {
// 			writeJSONError(w, error.Error(), http.StatusInternalServerError)
// 			return
// 		}
// 		object := subdayWithMod{result, true}
// 		json.NewEncoder(w).Encode(object)
// 	} else {
// 		result, error := repos.GetLastSubday(channelID)
// 		if error != nil {
// 			writeJSONError(w, error.Error(), http.StatusInternalServerError)
// 			return
// 		}
// 		object := subdayWithModNoWinners{result, false}

// 		json.NewEncoder(w).Encode(object)
// 	}

// }

func subdayByID(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	channelInfo, error := repos.GetChannelInfo(channelID)
	if error != nil {
		writeJSONError(w, "That channel is not defined", http.StatusForbidden)
		return
	}
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	if channelInfo.GetIfUserIsMod(&s.UserID) == true {
		var result *models.Subday
		if (id != "last") {
			result, error = repos.GetSubdayByIdMod(&id)
			if error != nil {
				writeJSONError(w, error.Error(), http.StatusInternalServerError)
				return
			}

		} else {
			result, error = repos.GetLastSubdayMod(channelID)
			if error != nil {
				writeJSONError(w, error.Error(), http.StatusInternalServerError)
				return
			}
		}

		object := subdayWithMod{result, true}

		json.NewEncoder(w).Encode(object)

	} else {
		var result *models.SubdayNoWinners
		if (id != "last") {
			result, error = repos.GetSubdayById(&id)
			if error != nil {
				writeJSONError(w, error.Error(), http.StatusInternalServerError)
				return
			}

		} else {
			result, error = repos.GetLastSubday(channelID)
			if error != nil {
				writeJSONError(w, error.Error(), http.StatusInternalServerError)
				return
			}
		}
		object := subdayWithModNoWinners{result, false}

		json.NewEncoder(w).Encode(object)
	}
}
func subdayRandomize(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	winner := repos.PickRandomWinnerForSubday(channelID, &id)
	if winner != nil {
		json.NewEncoder(w).Encode(winner)
	} else {
		json.NewEncoder(w).Encode(optionResponse{"OK"})
	}

}
func subdayPullWinner (w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	user := pat.Param(r, "user")
	if user == "" {
		writeJSONError(w, "user", http.StatusNotFound)
		return
	}
	repos.SubdayPullWinner(&id, &user)
	json.NewEncoder(w).Encode(optionResponse{"OK"})

}
func subdayClose(w http.ResponseWriter, r *http.Request, s *models.HTTPSession, channelID *string, channelName *string) {
	id := pat.Param(r, "subdayID")
	if id == "" {
		writeJSONError(w, "subday id is not found", http.StatusNotFound)
		return
	}
	repos.CloseSubday(channelID, &id)
	json.NewEncoder(w).Encode(optionResponse{"OK"})

}
<|endoftext|>


<commit_before>package intercom

import (
    "encoding/json"
)

// Tag represents a tag.
//
// See https://doc.intercom.io/api/#tags for more information.
type Tag struct {
    ID      string
    Name    string
}

// ListTags returns all of the tags that belong to a client.
//
// See https://doc.intercom.io/api/#tags for more information.
func (c *APIClient) ListTags() ([]*Tag, error) {
    req, err := c.NewRequest("GET", "tags", nil)
    if err != nil {
        return nil, err
    }

    var v map[string]interface{}
    err = c.Do(req, &v)
    if err != nil {
        return nil, err
    }

    vv := v["tags"].([]interface{})

    var tags []*Tag
    for _, vvv := range vv {
        var tag Tag;
        j, err := json.Marshal(&vvv)
        if err != nil {
            fmt.Println(err)
            return nil, err
        }
        err = json.Unmarshal(j, &tag)
        if err != nil {
            fmt.Println(err)
            return nil, err
        }
        tags = append(tags, &tag)
    }

    return tags, err
}
<commit_msg>Even better error handling<commit_after>package intercom

import (
    "encoding/json"
)

// Tag represents a tag.
//
// See https://doc.intercom.io/api/#tags for more information.
type Tag struct {
    ID      string
    Name    string
}

// ListTags returns all of the tags that belong to a client.
//
// See https://doc.intercom.io/api/#tags for more information.
func (c *APIClient) ListTags() ([]*Tag, error) {
    req, err := c.NewRequest("GET", "tags", nil)
    if err != nil {
        return nil, err
    }

    var v map[string]interface{}
    err = c.Do(req, &v)
    if err != nil {
        return nil, err
    }

    vv := v["tags"].([]interface{})

    var tags []*Tag
    for _, vvv := range vv {
        var tag Tag;
        j, err := json.Marshal(&vvv)
        if err != nil {
            return nil, err
        }
        err = json.Unmarshal(j, &tag)
        if err != nil {
            return nil, err
        }
        tags = append(tags, &tag)
    }

    return tags, err
}
<|endoftext|>


<commit_before>// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package scope

import (
	"context"
	"net/http"
)

type ctxRunModeKey struct{}

// DefaultRunMode defines the default run mode if the programmer hasn't applied
// the field Mode or the function RunMode.WithContext() to specify a specific
// run mode. It indicates the fall back to the default website and its default
// store.
const DefaultRunMode Hash = 0

// RunMode core type to initialize the run mode of the current request. Allows
// you to create a multi-site / multi-tenant setup. An implementation of this
// lives in storenet.AppRunMode.WithRunMode() middleware.
type RunMode struct {
	Mode Hash
	// ModeFunc if not nil you can create your own function to set a run mode.
	ModeFunc func(http.ResponseWriter, *http.Request) Hash
}

// CalculateMode calls the user defined Mode field or ModeFunction. On an
// invalid mode it falls back to the default run mode, which is a zero Hash.
func (rm RunMode) CalculateMode(w http.ResponseWriter, r *http.Request) Hash {
	h := rm.Mode
	if rm.ModeFunc != nil {
		h = rm.ModeFunc(w, r)
	}
	if s := h.Scope(); s < Website || s > Store {
		// fall back to default because only Website, Group and Store are allowed.
		h = DefaultRunMode
	}
	return h
}

// WithContextRunMode sets the main run mode for the current request. It panics
// when called multiple times for the current context. This function is used in
// net/runmode together with function RunMode.CalculateMode(r, w).
func WithContextRunMode(ctx context.Context, runMode Hash) context.Context {
	if _, ok := ctx.Value(ctxRunModeKey{}).(Hash); ok {
		panic("[scope] You are not allowed to set the runMode more than once for the current context.")
	}
	return context.WithValue(ctx, ctxRunModeKey{}, runMode)
}

// FromContextRunMode returns the run mode Hash from a context. If no entry can
// be found in the context the returned Hash has a default value. This default
// value indicates the fall back to the default website and its default store.
func FromContextRunMode(ctx context.Context) Hash {
	h, ok := ctx.Value(ctxRunModeKey{}).(Hash)
	if !ok {
		return DefaultRunMode // indicates a fall back to a default store of the default website
	}
	return h
}
<commit_msg>store/scope: Update documentation for the usage of runMode<commit_after>// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package scope

import (
	"context"
	"net/http"
)

type ctxRunModeKey struct{}

// DefaultRunMode defines the default run mode if the programmer hasn't applied
// the field Mode or the function RunMode.WithContext() to specify a specific
// run mode. It indicates the fall back to the default website and its default
// store.
const DefaultRunMode Hash = 0

// RunMode core type to initialize the run mode of the current request. Allows
// you to create a multi-site / multi-tenant setup. An implementation of this
// lives in storenet.AppRunMode.WithRunMode() middleware.
type RunMode struct {
	Mode Hash
	// ModeFunc if not nil you can create your own function to set a run mode.
	ModeFunc func(http.ResponseWriter, *http.Request) Hash
}

// CalculateMode calls the user defined Mode field or ModeFunction. On an
// invalid mode it falls back to the default run mode, which is a zero Hash.
func (rm RunMode) CalculateMode(w http.ResponseWriter, r *http.Request) Hash {
	h := rm.Mode
	if rm.ModeFunc != nil {
		h = rm.ModeFunc(w, r)
	}
	if s := h.Scope(); s < Website || s > Store {
		// fall back to default because only Website, Group and Store are allowed.
		h = DefaultRunMode
	}
	return h
}

// WithContextRunMode sets the main run mode for the current request. It panics
// when called multiple times for the current context. This function is used in
// net/runmode together with function RunMode.CalculateMode(r, w).
// Use case for the runMode: Cache Keys and app initialization.
func WithContextRunMode(ctx context.Context, runMode Hash) context.Context {
	if _, ok := ctx.Value(ctxRunModeKey{}).(Hash); ok {
		panic("[scope] You are not allowed to set the runMode more than once for the current context.")
	}
	return context.WithValue(ctx, ctxRunModeKey{}, runMode)
}

// FromContextRunMode returns the run mode Hash from a context. If no entry can
// be found in the context the returned Hash has a default value. This default
// value indicates the fall back to the default website and its default store.
// Use case for the runMode: Cache Keys and app initialization.
func FromContextRunMode(ctx context.Context) Hash {
	h, ok := ctx.Value(ctxRunModeKey{}).(Hash)
	if !ok {
		return DefaultRunMode // indicates a fall back to a default store of the default website
	}
	return h
}
<|endoftext|>


<commit_before>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

package commands

import (
	"archive/tar"
	"compress/gzip"
	"flag"
	"fmt"
	"golang.org/x/net/context"
	"io"
	"net/http"
	"os"
	"qpm.io/common"
	msg "qpm.io/common/messages"
	"qpm.io/qpm/core"
	"strings"
)

type ProgressProxyReader struct {
	io.Reader
	total    int64
	length   int64
	progress float64
}

func (r *ProgressProxyReader) Read(p []byte) (int, error) {
	n, err := r.Reader.Read(p)
	if n > 0 {
		r.total += int64(n)
		percentage := float64(r.total) / float64(r.length) * float64(100)
		i := int(percentage / float64(10))
		is := fmt.Sprintf("%v", i)
		if percentage-r.progress > 2 {
			fmt.Fprintf(os.Stderr, is)
			r.progress = percentage
		}
	}
	return n, err
}

type InstallCommand struct {
	BaseCommand
	pkg common.PackageWrapper
	fs  *flag.FlagSet
}

func NewInstallCommand(ctx core.Context) *InstallCommand {
	return &InstallCommand{
		BaseCommand: BaseCommand{
			Ctx: ctx,
		},
	}
}

func (i InstallCommand) Description() string {
	return "Installs a new package"
}

func (i *InstallCommand) RegisterFlags(flags *flag.FlagSet) {
	i.fs = flags
}

func (i *InstallCommand) Run() error {

	packageName := i.fs.Arg(0)

	err := i.pkg.Load()
	if err != nil {
		i.Error(err)
		return err
	}

	var packageNames []string
	if packageName == "" {
		packageNames = i.pkg.Dependencies
	} else {
		packageNames = []string{packageName}
	}

	// Get list of dependencies from the server
	response, err := i.Ctx.Client.GetDependencies(context.Background(), &msg.DependencyRequest{packageNames})
	if err != nil {
		i.Error(err)
		return err
	}

	if len(response.Dependencies) == 0 {
		i.Info("No package(s) found")
		return nil
	}

	// Save the dependencies in package.json
	err = i.save(response.Dependencies)
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	err = i.pkg.UpdatePri(response.Dependencies)
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	// Download and extract the packages
	for _, d := range response.Dependencies {
		err = i.install(d)
		// FIXME: should we continue installing ?
		if err != nil {
			return err
		}
	}

	return nil
}

func (i *InstallCommand) install(d *msg.Dependency) error {

	url := core.GitHub + "/" + d.Repository.Url + "/" + core.Tarball

	signature := i.pkg.GetDependencySignature(d)
	fmt.Println("Installing", signature)

	fileName, err := i.download(url, core.Vendor)
	if err != nil {
		return err
	}

	err = i.extract(fileName, core.Vendor, d.Name)
	if err != nil {
		return err
	}

	return os.Remove(fileName)
}

func (i *InstallCommand) save(dependencies []*msg.Dependency) error {

	// FIXME: inefficient
	var newDependencies []string
	for _, d := range dependencies {
		exists := false
		signature := i.pkg.GetDependencySignature(d)
		for _, dependency := range i.pkg.Dependencies {
			if dependency == signature {
				exists = true
				i.Info("The package is already a dependency : " + signature)
				break
			}
		}
		if !exists {
			newDependencies = append(newDependencies, signature)
		}
	}
	i.pkg.Dependencies = append(i.pkg.Dependencies, newDependencies...)

	err := i.pkg.Save()
	if err != nil {
		i.Error(err)
		return err
	}

	return nil
}

func (i *InstallCommand) download(url string, destination string) (fileName string, err error) {

	tokens := strings.Split(url, "/")
	fileName = destination + "/" + tokens[len(tokens)-2] + core.TarSuffix // FIXME: we assume it's a tarball

	var output *os.File
	output, err = os.Create(fileName)
	if err != nil {
		// TODO: check file existence first with os.IsExist(err)
		i.Error(err)
		return
	}
	defer output.Close()

	var response *http.Response
	response, err = http.Get(url)
	if err != nil {
		i.Error(err)
		return
	}
	defer response.Body.Close()

	//proxy := &ProgressProxyReader{ Reader: response.Body, length: response.ContentLength }
	//var written int64
	_, err = io.Copy(output, response.Body)
	if err != nil {
		i.Error(err)
		return
	}

	return
}

func (i *InstallCommand) extract(fileName string, destination string, name string) error {

	file, err := os.Open(fileName)

	if err != nil {
		i.Error(err)
		return err
	}

	defer file.Close()

	var fileReader io.ReadCloser = file

	// add a filter to handle gzipped file
	if strings.HasSuffix(fileName, ".gz") {
		if fileReader, err = gzip.NewReader(file); err != nil {
			i.Error(err)
			return err
		}
		defer fileReader.Close()
	}

	tarBallReader := tar.NewReader(fileReader)
	var topDir string

	for {
		header, err := tarBallReader.Next()
		if err != nil {
			if err == io.EOF {
				break
			}
			i.Error(err)
			return err
		}

		filename := destination + "/" + header.Name

		switch header.Typeflag {
		case tar.TypeDir:
			tokens := strings.Split(header.Name, "/")
			topDir = tokens[0]
			err = os.MkdirAll(filename, os.FileMode(header.Mode)) // or use 0755
			if err != nil {
				i.Error(err)
				return err
			}

		case tar.TypeReg:
			writer, err := os.Create(filename)
			if err != nil {
				i.Error(err)
				return err
			}
			io.Copy(writer, tarBallReader)
			err = os.Chmod(filename, os.FileMode(header.Mode))
			if err != nil {
				i.Error(err)
				return err
			}
			writer.Close()

		case tar.TypeXGlobalHeader:
			// Ignore this

		default:
			//i.Info("Unable to extract type : %c in file %s\n", header.Typeflag, filename)
		}
	}

	if topDir != "" {
		path := destination + "/" + name
		os.RemoveAll(path)
		err := os.Rename(destination+"/"+topDir, path)
		if err != nil {
			i.Error(err)
		}
	}

	return nil
}
<commit_msg>Make 'install' use the new nested directory structure.<commit_after>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

package commands

import (
	"archive/tar"
	"compress/gzip"
	"flag"
	"fmt"
	"golang.org/x/net/context"
	"io"
	"net/http"
	"os"
	"qpm.io/common"
	msg "qpm.io/common/messages"
	"qpm.io/qpm/core"
	"strings"
)

type ProgressProxyReader struct {
	io.Reader
	total    int64
	length   int64
	progress float64
}

func (r *ProgressProxyReader) Read(p []byte) (int, error) {
	n, err := r.Reader.Read(p)
	if n > 0 {
		r.total += int64(n)
		percentage := float64(r.total) / float64(r.length) * float64(100)
		i := int(percentage / float64(10))
		is := fmt.Sprintf("%v", i)
		if percentage-r.progress > 2 {
			fmt.Fprintf(os.Stderr, is)
			r.progress = percentage
		}
	}
	return n, err
}

type InstallCommand struct {
	BaseCommand
	pkg common.PackageWrapper
	fs  *flag.FlagSet
}

func NewInstallCommand(ctx core.Context) *InstallCommand {
	return &InstallCommand{
		BaseCommand: BaseCommand{
			Ctx: ctx,
		},
	}
}

func (i InstallCommand) Description() string {
	return "Installs a new package"
}

func (i *InstallCommand) RegisterFlags(flags *flag.FlagSet) {
	i.fs = flags
}

func (i *InstallCommand) Run() error {

	packageName := i.fs.Arg(0)

	err := i.pkg.Load()
	if err != nil {
		i.Error(err)
		return err
	}

	var packageNames []string
	if packageName == "" {
		packageNames = i.pkg.Dependencies
	} else {
		packageNames = []string{packageName}
	}

	// Get list of dependencies from the server
	response, err := i.Ctx.Client.GetDependencies(context.Background(), &msg.DependencyRequest{packageNames})
	if err != nil {
		i.Error(err)
		return err
	}

	if len(response.Dependencies) == 0 {
		i.Info("No package(s) found")
		return nil
	}

	// Save the dependencies in package.json
	err = i.save(response.Dependencies)
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	err = i.pkg.UpdatePri(response.Dependencies)
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	// Download and extract the packages
	for _, d := range response.Dependencies {
		err = i.install(d)
		// FIXME: should we continue installing ?
		if err != nil {
			return err
		}
	}

	return nil
}

func (i *InstallCommand) install(d *msg.Dependency) error {

	url := core.GitHub + "/" + d.Repository.Url + "/" + core.Tarball

	signature := i.pkg.GetDependencySignature(d)
	fmt.Println("Installing", signature)

	fileName, err := i.download(url, core.Vendor)
	if err != nil {
		return err
	}

	err = i.extract(fileName, core.Vendor, d.Name)
	if err != nil {
		return err
	}

	return os.Remove(fileName)
}

func (i *InstallCommand) save(dependencies []*msg.Dependency) error {

	// FIXME: inefficient
	var newDependencies []string
	for _, d := range dependencies {
		exists := false
		signature := i.pkg.GetDependencySignature(d)
		for _, dependency := range i.pkg.Dependencies {
			if dependency == signature {
				exists = true
				i.Info("The package is already a dependency : " + signature)
				break
			}
		}
		if !exists {
			newDependencies = append(newDependencies, signature)
		}
	}
	i.pkg.Dependencies = append(i.pkg.Dependencies, newDependencies...)

	err := i.pkg.Save()
	if err != nil {
		i.Error(err)
		return err
	}

	return nil
}

func (i *InstallCommand) download(url string, destination string) (fileName string, err error) {

	tokens := strings.Split(url, "/")
	fileName = destination + "/" + tokens[len(tokens)-2] + core.TarSuffix // FIXME: we assume it's a tarball

	var output *os.File
	output, err = os.Create(fileName)
	if err != nil {
		// TODO: check file existence first with os.IsExist(err)
		i.Error(err)
		return
	}
	defer output.Close()

	var response *http.Response
	response, err = http.Get(url)
	if err != nil {
		i.Error(err)
		return
	}
	defer response.Body.Close()

	//proxy := &ProgressProxyReader{ Reader: response.Body, length: response.ContentLength }
	//var written int64
	_, err = io.Copy(output, response.Body)
	if err != nil {
		i.Error(err)
		return
	}

	return
}

func (i *InstallCommand) extract(fileName string, destination string, name string) error {

	file, err := os.Open(fileName)

	if err != nil {
		i.Error(err)
		return err
	}

	defer file.Close()

	var fileReader io.ReadCloser = file

	// add a filter to handle gzipped file
	if strings.HasSuffix(fileName, ".gz") {
		if fileReader, err = gzip.NewReader(file); err != nil {
			i.Error(err)
			return err
		}
		defer fileReader.Close()
	}

	tarBallReader := tar.NewReader(fileReader)
	var topDir string

	for {
		header, err := tarBallReader.Next()
		if err != nil {
			if err == io.EOF {
				break
			}
			i.Error(err)
			return err
		}

		filename := destination + "/" + header.Name

		switch header.Typeflag {
		case tar.TypeDir:
			tokens := strings.Split(header.Name, "/")
			topDir = tokens[0]
			err = os.MkdirAll(filename, os.FileMode(header.Mode)) // or use 0755
			if err != nil {
				i.Error(err)
				return err
			}

		case tar.TypeReg:
			writer, err := os.Create(filename)
			if err != nil {
				i.Error(err)
				return err
			}
			io.Copy(writer, tarBallReader)
			err = os.Chmod(filename, os.FileMode(header.Mode))
			if err != nil {
				i.Error(err)
				return err
			}
			writer.Close()

		case tar.TypeXGlobalHeader:
			// Ignore this

		default:
			//i.Info("Unable to extract type : %c in file %s\n", header.Typeflag, filename)
		}
	}

	if topDir != "" {

		path := destination + "/" + strings.Replace(name, ".", "/", -1)

		if err := os.MkdirAll(path, 0755); err != nil {
			i.Error(err)
			return err
		}

		os.RemoveAll(path)
		err := os.Rename(destination+"/"+topDir, path)
		if err != nil {
			i.Error(err)
		}
	}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

package commands

import (
	"flag"
	"fmt"
	"golang.org/x/net/context"
	"io"
	"os"
	"path/filepath"
	"qpm.io/common"
	msg "qpm.io/common/messages"
	"qpm.io/qpm/core"
	"qpm.io/qpm/vcs"
	"strings"
	"text/template"
)

var packageFuncs = template.FuncMap{
	"relPriFile": func(vendorDir string, dep *common.PackageWrapper) string {
		abs := filepath.Join(dep.RootDir(), dep.PriFile())
		rel, err := filepath.Rel(vendorDir, abs)
		if err == nil {
			return rel
		} else {
			return abs
		}
	},
}

var (
	// This template is very dense to avoid excessive whitespace in the generated code.
	// We can address this in a future version of Go (1.6?):
	// https://github.com/golang/go/commit/e6ee26a03b79d0e8b658463bdb29349ca68e1460
	vendorPri = template.Must(template.New("vendorPri").Funcs(packageFuncs).Parse(`
DEFINES += QPM_INIT\\(E\\)=\"E.addImportPath(QStringLiteral(\\\"qrc:/\\\"));\"
{{$vendirDir := .VendorDir}}
{{range $dep := .Dependencies}}
include($$PWD/{{relPriFile $vendirDir $dep}}){{end}}
`))
)

type ProgressProxyReader struct {
	io.Reader
	total    int64
	length   int64
	progress float64
}

func (r *ProgressProxyReader) Read(p []byte) (int, error) {
	n, err := r.Reader.Read(p)
	if n > 0 {
		r.total += int64(n)
		percentage := float64(r.total) / float64(r.length) * float64(100)
		i := int(percentage / float64(10))
		is := fmt.Sprintf("%v", i)
		if percentage-r.progress > 2 {
			fmt.Fprintf(os.Stderr, is)
			r.progress = percentage
		}
	}
	return n, err
}

type InstallCommand struct {
	BaseCommand
	pkg       *common.PackageWrapper
	fs        *flag.FlagSet
	vendorDir string
}

func NewInstallCommand(ctx core.Context) *InstallCommand {
	return &InstallCommand{
		BaseCommand: BaseCommand{
			Ctx: ctx,
		},
	}
}

func (i InstallCommand) Description() string {
	return "Installs a new package"
}

func (i *InstallCommand) RegisterFlags(flags *flag.FlagSet) {
	i.fs = flags

	// TODO: Support other directory names on the command line?
	var err error
	i.vendorDir, err = filepath.Abs(core.Vendor)
	if err != nil {
		i.vendorDir = core.Vendor
	}
}

func (i *InstallCommand) Run() error {

	packageName := i.fs.Arg(0)

	var err error
	i.pkg, err = common.LoadPackage("")
	if err != nil {
		// A missing package file is only an error if packageName is empty
		if os.IsNotExist(err) {
			if packageName == "" {
				err = fmt.Errorf("No %s file found", core.PackageFile)
				i.Error(err)
				return err
			} else {
				// Create a new package
				file, err := filepath.Abs(core.PackageFile)
				if err != nil {
					i.Error(err)
					return err
				}
				i.pkg = common.NewPackageWrapper(file)
			}
		} else {
			i.Error(err)
			return err
		}
	}

	var packageNames []string
	if packageName == "" {
		packageNames = i.pkg.Dependencies
	} else {
		packageNames = []string{packageName}
	}

	// Get list of dependencies from the server
	response, err := i.Ctx.Client.GetDependencies(context.Background(), &msg.DependencyRequest{packageNames})
	if err != nil {
		i.Error(err)
		return err
	}

	if len(response.Dependencies) == 0 {
		i.Info("No package(s) found")
		return nil
	}

	// create the vendor directory if needed
	if _, err = os.Stat(i.vendorDir); err != nil {
		err = os.Mkdir(i.vendorDir, 0755)
	}

	// Download and extract the packages
	packages := []*common.PackageWrapper{}
	for _, d := range response.Dependencies {
		p, err := i.install(d)
		if err != nil {
			return err
		}
		packages = append(packages, p)
	}

	// Save the dependencies in the package file
	err = i.save(packages)
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	err = i.postInstall()
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	return nil
}

func (i *InstallCommand) install(d *msg.Dependency) (*common.PackageWrapper, error) {

	signature := strings.Join([]string{d.Name, d.Version.Label}, "@")
	fmt.Println("Installing", signature)

	pkg, err := vcs.Install(d, i.vendorDir)
	if err != nil {
		i.Error(err)
		return nil, err
	}

	return pkg, nil
}

func (i *InstallCommand) save(newDeps []*common.PackageWrapper) error {

	existingDeps := i.pkg.ParseDependencies()

	for _, d := range newDeps {
		existingVersion, exists := existingDeps[d.Name]
		if exists {
			if d.Version.Label == existingVersion {
				i.Info("The package is already a dependency : " + d.GetDependencySignature())
			} else {
				// TODO: Handle conflicts
				err := fmt.Errorf("Conflict for package %s. Version %s != %s", d.Name, existingVersion, d.Version.Label)
				i.Error(err)
				return err
			}
		} else {
			i.pkg.Dependencies = append(i.pkg.Dependencies, d.GetDependencySignature())
		}
	}

	err := i.pkg.Save()
	if err != nil {
		i.Error(err)
		return err
	}

	return nil
}

func (i *InstallCommand) postInstall() error {
	if err := GenerateVendorPri(i.vendorDir, i.pkg); err != nil {
		i.Error(err)
		return err
	}
	return nil
}

// Generates a vendor.pri inside vendorDir using the information contained in the package file
// and the dependencies
func GenerateVendorPri(vendorDir string, pkg *common.PackageWrapper) error {
	depMap, err := common.LoadPackages(vendorDir)
	if err != nil {
		return err
	}

	var deps []*common.PackageWrapper
	for _, dep := range depMap {
		deps = append(deps, dep)
	}

	vendorPriFile := filepath.Join(vendorDir, core.Vendor+".pri")

	data := struct {
		VendorDir    string
		Package      *common.PackageWrapper
		Dependencies []*common.PackageWrapper
	}{
		vendorDir,
		pkg,
		deps,
	}

	return core.WriteTemplate(vendorPriFile, vendorPri, data)
}
<commit_msg>Add the vendor directory to the INCLUDEPATH.<commit_after>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

package commands

import (
	"flag"
	"fmt"
	"golang.org/x/net/context"
	"io"
	"os"
	"path/filepath"
	"qpm.io/common"
	msg "qpm.io/common/messages"
	"qpm.io/qpm/core"
	"qpm.io/qpm/vcs"
	"strings"
	"text/template"
)

var packageFuncs = template.FuncMap{
	"relPriFile": func(vendorDir string, dep *common.PackageWrapper) string {
		abs := filepath.Join(dep.RootDir(), dep.PriFile())
		rel, err := filepath.Rel(vendorDir, abs)
		if err == nil {
			return rel
		} else {
			return abs
		}
	},
}

var (
	// This template is very dense to avoid excessive whitespace in the generated code.
	// We can address this in a future version of Go (1.6?):
	// https://github.com/golang/go/commit/e6ee26a03b79d0e8b658463bdb29349ca68e1460
	vendorPri = template.Must(template.New("vendorPri").Funcs(packageFuncs).Parse(`
DEFINES += QPM_INIT\\(E\\)=\"E.addImportPath(QStringLiteral(\\\"qrc:/\\\"));\"
INCLUDEPATH += $$PWD
{{$vendirDir := .VendorDir}}
{{range $dep := .Dependencies}}
include($$PWD/{{relPriFile $vendirDir $dep}}){{end}}
`))
)

type ProgressProxyReader struct {
	io.Reader
	total    int64
	length   int64
	progress float64
}

func (r *ProgressProxyReader) Read(p []byte) (int, error) {
	n, err := r.Reader.Read(p)
	if n > 0 {
		r.total += int64(n)
		percentage := float64(r.total) / float64(r.length) * float64(100)
		i := int(percentage / float64(10))
		is := fmt.Sprintf("%v", i)
		if percentage-r.progress > 2 {
			fmt.Fprintf(os.Stderr, is)
			r.progress = percentage
		}
	}
	return n, err
}

type InstallCommand struct {
	BaseCommand
	pkg       *common.PackageWrapper
	fs        *flag.FlagSet
	vendorDir string
}

func NewInstallCommand(ctx core.Context) *InstallCommand {
	return &InstallCommand{
		BaseCommand: BaseCommand{
			Ctx: ctx,
		},
	}
}

func (i InstallCommand) Description() string {
	return "Installs a new package"
}

func (i *InstallCommand) RegisterFlags(flags *flag.FlagSet) {
	i.fs = flags

	// TODO: Support other directory names on the command line?
	var err error
	i.vendorDir, err = filepath.Abs(core.Vendor)
	if err != nil {
		i.vendorDir = core.Vendor
	}
}

func (i *InstallCommand) Run() error {

	packageName := i.fs.Arg(0)

	var err error
	i.pkg, err = common.LoadPackage("")
	if err != nil {
		// A missing package file is only an error if packageName is empty
		if os.IsNotExist(err) {
			if packageName == "" {
				err = fmt.Errorf("No %s file found", core.PackageFile)
				i.Error(err)
				return err
			} else {
				// Create a new package
				file, err := filepath.Abs(core.PackageFile)
				if err != nil {
					i.Error(err)
					return err
				}
				i.pkg = common.NewPackageWrapper(file)
			}
		} else {
			i.Error(err)
			return err
		}
	}

	var packageNames []string
	if packageName == "" {
		packageNames = i.pkg.Dependencies
	} else {
		packageNames = []string{packageName}
	}

	// Get list of dependencies from the server
	response, err := i.Ctx.Client.GetDependencies(context.Background(), &msg.DependencyRequest{packageNames})
	if err != nil {
		i.Error(err)
		return err
	}

	if len(response.Dependencies) == 0 {
		i.Info("No package(s) found")
		return nil
	}

	// create the vendor directory if needed
	if _, err = os.Stat(i.vendorDir); err != nil {
		err = os.Mkdir(i.vendorDir, 0755)
	}

	// Download and extract the packages
	packages := []*common.PackageWrapper{}
	for _, d := range response.Dependencies {
		p, err := i.install(d)
		if err != nil {
			return err
		}
		packages = append(packages, p)
	}

	// Save the dependencies in the package file
	err = i.save(packages)
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	err = i.postInstall()
	// FIXME: should we continue installing ?
	if err != nil {
		return err
	}

	return nil
}

func (i *InstallCommand) install(d *msg.Dependency) (*common.PackageWrapper, error) {

	signature := strings.Join([]string{d.Name, d.Version.Label}, "@")
	fmt.Println("Installing", signature)

	pkg, err := vcs.Install(d, i.vendorDir)
	if err != nil {
		i.Error(err)
		return nil, err
	}

	return pkg, nil
}

func (i *InstallCommand) save(newDeps []*common.PackageWrapper) error {

	existingDeps := i.pkg.ParseDependencies()

	for _, d := range newDeps {
		existingVersion, exists := existingDeps[d.Name]
		if exists {
			if d.Version.Label == existingVersion {
				i.Info("The package is already a dependency : " + d.GetDependencySignature())
			} else {
				// TODO: Handle conflicts
				err := fmt.Errorf("Conflict for package %s. Version %s != %s", d.Name, existingVersion, d.Version.Label)
				i.Error(err)
				return err
			}
		} else {
			i.pkg.Dependencies = append(i.pkg.Dependencies, d.GetDependencySignature())
		}
	}

	err := i.pkg.Save()
	if err != nil {
		i.Error(err)
		return err
	}

	return nil
}

func (i *InstallCommand) postInstall() error {
	if err := GenerateVendorPri(i.vendorDir, i.pkg); err != nil {
		i.Error(err)
		return err
	}
	return nil
}

// Generates a vendor.pri inside vendorDir using the information contained in the package file
// and the dependencies
func GenerateVendorPri(vendorDir string, pkg *common.PackageWrapper) error {
	depMap, err := common.LoadPackages(vendorDir)
	if err != nil {
		return err
	}

	var deps []*common.PackageWrapper
	for _, dep := range depMap {
		deps = append(deps, dep)
	}

	vendorPriFile := filepath.Join(vendorDir, core.Vendor+".pri")

	data := struct {
		VendorDir    string
		Package      *common.PackageWrapper
		Dependencies []*common.PackageWrapper
	}{
		vendorDir,
		pkg,
		deps,
	}

	return core.WriteTemplate(vendorPriFile, vendorPri, data)
}
<|endoftext|>


<commit_before>// Copyright 2014 Arne Roomann-Kurrik
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package twodee

import (
	"math"
	"time"
)

const (
	Step60Hz = time.Duration(16666) * time.Microsecond
	Step30Hz = Step60Hz * 2
	Step20Hz = time.Duration(50000) * time.Microsecond
	Step15Hz = Step30Hz * 2
	Step10Hz = Step20Hz * 2
	Step5Hz  = Step10Hz * 2
)

type AnimationCallback func()

type Animating interface {
	Update(elapsed time.Duration) (done bool)
	SetCallback(callback AnimationCallback)
	HasCallback() bool
	Reset()
}

type Animation struct {
	elapsed  time.Duration
	callback AnimationCallback
}

func NewAnimation() *Animation {
	return &Animation{}
}

func (a *Animation) Update(elapsed time.Duration) (done bool) {
	a.elapsed += elapsed
	return false
}

func (a *Animation) Elapsed() time.Duration {
	return a.elapsed
}

func (a *Animation) Reset() {
	a.elapsed = time.Duration(0)
}

func (a *Animation) SetCallback(callback AnimationCallback) {
	//if a.callback != nil {
	//	a.callback()
	//}
	a.callback = callback
}

func (a *Animation) HasCallback() bool {
	return a.callback != nil
}

func (a *Animation) Callback() {
	if a.HasCallback() {
		a.callback()
	}
}

type FrameAnimation struct {
	*Animation
	FrameLength time.Duration
	Sequence    []int
	Current     int
}

func NewFrameAnimation(length time.Duration, frames []int) *FrameAnimation {
	return &FrameAnimation{
		Animation:   NewAnimation(),
		FrameLength: length,
		Sequence:    frames,
		Current:     frames[0],
	}
}

func (a *FrameAnimation) Update(elapsed time.Duration) (done bool) {
	a.Animation.Update(elapsed)
	index := int(a.Elapsed()/a.FrameLength) % len(a.Sequence)
	a.Current = a.Sequence[index]
	done = false
	if a.HasCallback() && index == len(a.Sequence)-1 {
		a.Callback()
		a.SetCallback(nil)
		done = true
	}
	return
}

func (a *FrameAnimation) OffsetFrame(offset int) int {
	index := int(a.Elapsed()/a.FrameLength) % len(a.Sequence)
	return a.Sequence[(index+offset)%len(a.Sequence)]
}

func (a *FrameAnimation) SetSequence(seq []int) {
	a.Sequence = seq
	a.Current = a.Sequence[0]
	a.Animation.Reset()
}

type ContinuousFunc func(elapsed time.Duration) float32

type ContinuousAnimation struct {
	*Animation
	function ContinuousFunc
}

func NewContinuousAnimation(f ContinuousFunc) *ContinuousAnimation {
	return &ContinuousAnimation{
		Animation: NewAnimation(),
		function:  f,
	}
}

func (a *ContinuousAnimation) Value() float32 {
	return a.function(a.Elapsed())
}

func SineDecayFunc(duration time.Duration, amplitude, frequency, decay float32, callback AnimationCallback) ContinuousFunc {
	var interval = float64(frequency * 2.0 * math.Pi)
	return func(elapsed time.Duration) float32 {
		if elapsed > duration {
			if callback != nil {
				callback()
			}
			return 0.0
		}
		decayAmount := 1.0 - float32(elapsed)/float32(duration)*decay
		return float32(math.Sin(elapsed.Seconds()*interval/duration.Seconds())) * amplitude * decayAmount
	}
}
<commit_msg>Update  animation<commit_after>// Copyright 2014 Arne Roomann-Kurrik
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package twodee

import (
	"math"
	"time"
)

const (
	Step60Hz = time.Duration(16666) * time.Microsecond
	Step30Hz = Step60Hz * 2
	Step20Hz = time.Duration(50000) * time.Microsecond
	Step15Hz = Step30Hz * 2
	Step10Hz = Step20Hz * 2
	Step5Hz  = Step10Hz * 2
)

type AnimationCallback func()

type Animating interface {
	Update(elapsed time.Duration) (done bool)
	SetCallback(callback AnimationCallback)
	HasCallback() bool
	Reset()
}

type Animation struct {
	elapsed  time.Duration
	callback AnimationCallback
}

func NewAnimation() *Animation {
	return &Animation{}
}

func (a *Animation) Update(elapsed time.Duration) (done bool) {
	a.elapsed += elapsed
	return false
}

func (a *Animation) Elapsed() time.Duration {
	return a.elapsed
}

func (a *Animation) Reset() {
	a.elapsed = time.Duration(0)
}

func (a *Animation) SetCallback(callback AnimationCallback) {
	if a.callback != nil {
		a.callback()
	}
	a.callback = callback
}

func (a *Animation) HasCallback() bool {
	return a.callback != nil
}

func (a *Animation) Callback() {
	if a.HasCallback() {
		a.callback()
	}
}

type FrameAnimation struct {
	*Animation
	FrameLength time.Duration
	Sequence    []int
	Current     int
}

func NewFrameAnimation(length time.Duration, frames []int) *FrameAnimation {
	return &FrameAnimation{
		Animation:   NewAnimation(),
		FrameLength: length,
		Sequence:    frames,
		Current:     frames[0],
	}
}

func (a *FrameAnimation) Update(elapsed time.Duration) (done bool) {
	a.Animation.Update(elapsed)
	index := int(a.Elapsed()/a.FrameLength) % len(a.Sequence)
	a.Current = a.Sequence[index]
	done = false
	if a.HasCallback() && index == len(a.Sequence)-1 {
		a.Callback()
		a.SetCallback(nil)
		done = true
	}
	return
}

func (a *FrameAnimation) OffsetFrame(offset int) int {
	index := int(a.Elapsed()/a.FrameLength) % len(a.Sequence)
	return a.Sequence[(index+offset)%len(a.Sequence)]
}

func (a *FrameAnimation) SetSequence(seq []int) {
	a.Sequence = seq
	a.Current = a.Sequence[0]
	a.Animation.Reset()
}

type ContinuousFunc func(elapsed time.Duration) float32

type ContinuousAnimation struct {
	*Animation
	function ContinuousFunc
}

func NewContinuousAnimation(f ContinuousFunc) *ContinuousAnimation {
	return &ContinuousAnimation{
		Animation: NewAnimation(),
		function:  f,
	}
}

func (a *ContinuousAnimation) Value() float32 {
	return a.function(a.Elapsed())
}

func SineDecayFunc(duration time.Duration, amplitude, frequency, decay float32, callback AnimationCallback) ContinuousFunc {
	var interval = float64(frequency * 2.0 * math.Pi)
	return func(elapsed time.Duration) float32 {
		if elapsed > duration {
			if callback != nil {
				callback()
			}
			return 0.0
		}
		decayAmount := 1.0 - float32(elapsed)/float32(duration)*decay
		return float32(math.Sin(elapsed.Seconds()*interval/duration.Seconds())) * amplitude * decayAmount
	}
}
<|endoftext|>


<commit_before>package quorum

import (
	"testing"
)

func TestRandomPlacement(t *testing.T) {
	s := new(State)
	buckets, err := s.RandomPlacement(1)
	if len(buckets) == 0 {
		t.Fatal("Bucket Size = 0!")
	}
	if err != nil {
		t.Fatal("Failed RandomPlacement of 1")
	}

	buckets, err = s.RandomPlacement(0)
	if err != nil {
		t.Fatal("Failed to place 0!")
	}

	buckets, err = s.RandomPlacement(-1)
	if err == nil {
		t.Fatal("Did not produce error for negative number!")
	}

	buckets, err = s.RandomPlacement(9000)
	if err != nil {
		t.Fatal("Failed RandomPlacement of 9000")
	}
}
<commit_msg>Updated test file for randomplacement<commit_after>package quorum

import (
	"testing"
)

func TestRandomPlacement(t *testing.T) {
	s := new(State)
	buckets, err := s.RandomPlacement(1)
	if len(buckets) == 0 {
		t.Fatal("Bucket Size = 0!")
	}
	if err != nil {
		t.Fatal("Failed RandomPlacement of 1")
	}

	buckets, err = s.RandomPlacement(0)
	if err != nil {
		t.Fatal("Failed to place 0!")
	}

	buckets, err = s.RandomPlacement(-1)
	if err == nil {
		t.Fatal("Did not produce error for negative number!")
	}

	buckets, err = s.RandomPlacement(9000)
	if err != nil {
		t.Fatal("Failed RandomPlacement of 9000")
	}
	total := 0
	for i := range buckets {
		total += buckets[i]
	}
	if total != 9000 {
		t.Fatal("Sum of buckets does not equal total given")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"

	"os"
	"os/exec"
	"path"
	"runtime"

	log "github.com/Sirupsen/logrus"
)

// StructuredOuput ...
type StructuredOuput struct {
	planet       string
	output       string
	maxOutLength int
}

func main() {
	opts := Opts{}
	opts.procArgs(os.Args)

	if opts.helpFlag {
		printUsage()
		os.Exit(0)
	}
	if opts.versionFlag {
		printVersion()
		os.Exit(0)
	}

	level := log.InfoLevel
	if opts.debugFlag {
		level = log.DebugLevel
	}
	// Default logfile path
	logDir := path.Join(os.Getenv("ORBIT_HOME"), "logs")
	createLogDirIfNecessary(logDir)
	logFile := path.Join(logDir, "ski.log")
	setupLogger(logFile, level)

	log.Infof("Started with args: %v", os.Args)
	log.Debug(&opts)
	exec := makeExecutor(&opts)
	exec.execMain(&opts)
	log.Infof("Ended with args: %v", os.Args)
}

func createLogDirIfNecessary(dir string) {
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		if err = os.MkdirAll(dir, 0775|os.ModeDir); err != nil {
			// can't do anything
			os.Stderr.WriteString(fmt.Sprintf("%v", err))
		}
	}
}

func makeExecutor(opts *Opts) Executor {
	log.Debugf("Function: makeExecutor")
	executor := Executor{}
	for _, planetID := range opts.planets {
		planet := parseConnectionDetails(planetID)
		valid := isValidPlanet(planet)
		if !valid {
			continue
		}
		planet.id = planetID
		planet.outputStruct = StructuredOuput{planetID, "", 0}
		executor.planets = append(executor.planets, planet)
	}
	log.Debugf("executor: %s", executor)
	return executor
}

func isValidPlanet(planet Planet) bool {
	ok := isSupported(planet.planetType)
	if !ok {
		switch planet.planetType {
		case webServer:
			msg := "Usage of ski with web servers is not implemented"
			os.Stderr.WriteString(msg)
			log.Fatal(msg)
		default:
			msg := "Unkown Type of target"
			os.Stderr.WriteString(msg)
			log.Fatal(msg)
		}
	}
	// TODO: since we know what kind of action is attempted on this server
	// we could check if the action is permitted on the current planet and
	// if not mark it as not valid
	return ok
}

/**
*	Prints the help dialog
 */
func printUsage() {
	usage := `usage: ski [options...] <planets>...
	Options:
	-s="<scriptname>"   Execute script and return result
	-c="<command>"      Execute script and return result
	-t=<"templatename>" Templatefile to be applied
	-p    Pretty print output as a table
	-l    Load bash profiles on Server
	-h    Display this help text
	-v    Show version number
	-d    Show extended debug informations, set logging level to debug
`
	fmt.Println(usage)
}

func getOS() string {
	switch runtime.GOOS {
	case "windows":
		return "Windows"
	case "linux":
		return "Linux"
	case "darwin":
		return "MacOS"
	default:
		return "could not determine OS"
	}
}

func getArch() string {
	switch runtime.GOARCH {
	case "amd64":
		return "64bit"
	case "386":
		return "32bit"
	default:
		return "could not determine architecture"
	}
}

func getOSArch() string {
	switch runtime.GOOS {
	case "linux":
		out, err := exec.Command("uname", "-m").Output()
		if err != nil {
			fmt.Println("error occured")
			fmt.Printf("%s", err)
		}
		return string(out)
	case "windows":
		out, err := exec.Command("if exist \"%ProgramFiles(x86)%\" echo 64-bit").Output()
		if err != nil {
			fmt.Println("error occured")
			fmt.Printf("%s", err)
		}
		if string(out) == "64-bit" {
			return "x86_64"
		}
		return "i686"
	default:
		return "could not determine Operating system"
	}
}
<commit_msg>stop execution if an invalid planet id is in the list.<commit_after>package main

import (
	"fmt"

	"os"
	"os/exec"
	"path"
	"runtime"

	log "github.com/Sirupsen/logrus"
)

// StructuredOuput ...
type StructuredOuput struct {
	planet       string
	output       string
	maxOutLength int
}

func main() {
	opts := Opts{}
	opts.procArgs(os.Args)

	if opts.helpFlag {
		printUsage()
		os.Exit(0)
	}
	if opts.versionFlag {
		printVersion()
		os.Exit(0)
	}

	level := log.InfoLevel
	if opts.debugFlag {
		level = log.DebugLevel
	}
	// Default logfile path
	logDir := path.Join(os.Getenv("ORBIT_HOME"), "logs")
	createLogDirIfNecessary(logDir)
	logFile := path.Join(logDir, "ski.log")
	setupLogger(logFile, level)

	log.Infof("Started with args: %v", os.Args)
	log.Debug(&opts)
	exec := makeExecutor(&opts)
	exec.execMain(&opts)
	log.Infof("Ended with args: %v", os.Args)
}

func createLogDirIfNecessary(dir string) {
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		if err = os.MkdirAll(dir, 0775|os.ModeDir); err != nil {
			// can't do anything
			os.Stderr.WriteString(fmt.Sprintf("%v", err))
		}
	}
}

func makeExecutor(opts *Opts) Executor {
	log.Debugf("Function: makeExecutor")
	executor := Executor{}
	for _, planetID := range opts.planets {
		planet := parseConnectionDetails(planetID)
		if !isValidPlanet(planet) {
			os.Exit(1) // TODO ask if it really is wanted.
		}
		planet.id = planetID
		planet.outputStruct = StructuredOuput{planetID, "", 0}
		executor.planets = append(executor.planets, planet)
	}
	log.Debugf("executor: %s", executor)
	return executor
}

func isValidPlanet(planet Planet) bool {
	ok := isSupported(planet.planetType)
	if !ok {
		switch planet.planetType {
		case webServer:
			os.Stderr.WriteString("Usage of ski with web servers is not implemented")
		default:
			os.Stderr.WriteString("Unkown Type of target")
		}
	}
	// TODO: since we know what kind of action is attempted on this server
	// we could check if the action is permitted on the current planet and
	// if not mark it as not valid
	return ok
}

/**
*	Prints the help dialog
 */
func printUsage() {
	usage := `usage: ski [options...] <planets>...
	Options:
	-s="<scriptname>"   Execute script and return result
	-c="<command>"      Execute script and return result
	-t=<"templatename>" Templatefile to be applied
	-p    Pretty print output as a table
	-l    Load bash profiles on Server
	-h    Display this help text
	-v    Show version number
	-d    Show extended debug informations, set logging level to debug
`
	fmt.Println(usage)
}

func getOS() string {
	switch runtime.GOOS {
	case "windows":
		return "Windows"
	case "linux":
		return "Linux"
	case "darwin":
		return "MacOS"
	default:
		return "could not determine OS"
	}
}

func getArch() string {
	switch runtime.GOARCH {
	case "amd64":
		return "64bit"
	case "386":
		return "32bit"
	default:
		return "could not determine architecture"
	}
}

func getOSArch() string {
	switch runtime.GOOS {
	case "linux":
		out, err := exec.Command("uname", "-m").Output()
		if err != nil {
			fmt.Println("error occured")
			fmt.Printf("%s", err)
		}
		return string(out)
	case "windows":
		out, err := exec.Command("if exist \"%ProgramFiles(x86)%\" echo 64-bit").Output()
		if err != nil {
			fmt.Println("error occured")
			fmt.Printf("%s", err)
		}
		if string(out) == "64-bit" {
			return "x86_64"
		}
		return "i686"
	default:
		return "could not determine Operating system"
	}
}
<|endoftext|>