<commit_before>// Copyright 2017-2019 Authors of Cilium
//
// 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 ciliumTest

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"testing"
	"time"

	"github.com/cilium/cilium/pkg/logging"
	"github.com/cilium/cilium/test/config"
	. "github.com/cilium/cilium/test/ginkgo-ext"
	"github.com/cilium/cilium/test/helpers"
	"github.com/cilium/cilium/test/logger"
	gops "github.com/google/gops/agent"
	"github.com/onsi/ginkgo"
	ginkgoconfig "github.com/onsi/ginkgo/config"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/format"
	"github.com/sirupsen/logrus"
)

var (
	log             = logging.DefaultLogger
	DefaultSettings = map[string]string{
		"K8S_VERSION": "1.19",
	}
	k8sNodesEnv         = "K8S_NODES"
	commandsLogFileName = "cmds.log"
)

func init() {
	// Open socket for using gops to get stacktraces in case the tests deadlock.
	if err := gops.Listen(gops.Options{ShutdownCleanup: true}); err != nil {
		fmt.Fprintf(os.Stderr, "unable to start gops: %s", err)
		os.Exit(-1)
	}

	for k, v := range DefaultSettings {
		getOrSetEnvVar(k, v)
	}
	os.RemoveAll(helpers.TestResultsPath)

	format.UseStringerRepresentation = true
}

func configLogsOutput() {
	log.SetLevel(logrus.DebugLevel)
	log.Out = &logger.TestLogWriter
	logrus.SetFormatter(&logger.Formatter)
	log.Formatter = &logger.Formatter
	log.Hooks.Add(&logger.LogHook{})

	GinkgoWriter = NewWriter(log.Out)
}

func ShowCommands() {
	if !config.CiliumTestConfig.ShowCommands {
		return
	}

	helpers.SSHMetaLogs = NewWriter(os.Stdout)
}

func TestTest(t *testing.T) {
	if config.CiliumTestConfig.TestScope != "" {
		helpers.UserDefinedScope = config.CiliumTestConfig.TestScope
		fmt.Printf("User specified the scope:  %q\n", config.CiliumTestConfig.TestScope)
	}
	if integration := helpers.GetCurrentIntegration(); integration != "" {
		fmt.Printf("Using CNI_INTEGRATION=%q\n", integration)

		switch integration {
		case helpers.CIIntegrationMicrok8s:
			fallthrough
		case helpers.CIIntegrationMinikube:
			fmt.Printf("Disabling multinode testing")
			config.CiliumTestConfig.Multinode = false
		default:
		}
	}

	configLogsOutput()
	ShowCommands()

	if config.CiliumTestConfig.HoldEnvironment {
		RegisterFailHandler(helpers.Fail)
	} else {
		RegisterFailHandler(Fail)
	}
	junitReporter := NewJUnitReporter(fmt.Sprintf(
		"%s.xml", helpers.GetScopeWithVersion()))
	RunSpecsWithDefaultAndCustomReporters(
		t, fmt.Sprintf("Suite-%s", helpers.GetScopeWithVersion()),
		[]ginkgo.Reporter{junitReporter})
}

func goReportSetupStatus() chan bool {
	if ginkgoconfig.DefaultReporterConfig.Verbose ||
		ginkgoconfig.DefaultReporterConfig.Succinct {
		// Dev told us they want more/less information than default. Skip.
		return nil
	}

	exit := make(chan bool)
	go func() {
		done := false
		iter := 0
		for {
			var out string
			select {
			case ok := <-exit:
				if ok {
					out = "●\n"
				} else {
					out = "◌\n"
				}
				done = true
			default:
				out = string(rune(int('◜') + iter%4))
			}
			fmt.Printf("\rSetting up test suite... %s", out)
			if done {
				return
			}
			time.Sleep(250 * time.Millisecond)
			iter++
		}
	}()
	return exit
}

func reportCreateVMFailure(vm string, err error) {
	failmsg := fmt.Sprintf(`
        ===================== ERROR - VM PROVISION FAILED =====================

        Unable to provision and start VM %q: %s", vm, err

        =======================================================================
        `, vm, err)
	GinkgoPrint(failmsg)
	Fail(failmsg)
}

var _ = BeforeAll(func() {
	helpers.Init()
	By("Starting tests: command line parameters: %+v environment variables: %v", config.CiliumTestConfig, os.Environ())
	go func() {
		defer GinkgoRecover()
		time.Sleep(config.CiliumTestConfig.Timeout)
		msg := fmt.Sprintf("Test suite timed out after %s", config.CiliumTestConfig.Timeout)
		By(msg)
		Fail(msg)
	}()

	var err error

	logger := log.WithFields(logrus.Fields{"testName": "BeforeAll"})
	scope, err := helpers.GetScope()
	if err != nil {
		Fail(fmt.Sprintf(
			"Cannot get the scope for running test, please use --cilium.testScope option: %s",
			err))
	}

	switch helpers.GetCurrentIntegration() {
	case helpers.CIIntegrationFlannel:
		switch helpers.GetCurrentK8SEnv() {
		case "1.8":
			log.Infof("Cilium in %q mode is not supported in Kubernetes 1.8 due CNI < 0.6.0", helpers.CIIntegrationFlannel)
			os.Exit(0)
			return
		}
	}

	if config.CiliumTestConfig.SSHConfig != "" {
		// If we set a different VM that it's not in our test environment
		// ginkgo cannot provision it, so skip setup below.
		return
	}

	if progressChan := goReportSetupStatus(); progressChan != nil {
		defer func() { progressChan <- err == nil }()
	}

	switch scope {
	case helpers.Runtime:
		// Boot / provision VMs if specified by configuration.
		if config.CiliumTestConfig.Reprovision {
			err = helpers.CreateVM(helpers.Runtime)
			if err != nil {
				log.WithError(err).Error("Error starting VM")
				reportCreateVMFailure(helpers.Runtime, err)
			}
		}

		vm := helpers.InitRuntimeHelper(helpers.Runtime, logger)
		err = vm.SetUpCilium()

		if err != nil {
			// AfterFailed function is not defined in this scope, fired the
			// ReportFailed manually for this assert to gather cilium logs Fix
			// #3428
			vm.ReportFailed()
			log.WithError(err).Error("Cilium was unable to be set up correctly")
			reportCreateVMFailure(helpers.Runtime, err)
		}
		go vm.PprofReport()

	case helpers.K8s:
		//FIXME: This should be:
		// Start k8s1 and provision kubernetes.
		// When finish, start to build cilium in background
		// Start k8s2
		// Wait until compilation finished, and pull cilium image on k8s2

		// Name for K8s VMs depends on K8s version that is running.

		// Boot / provision VMs if specified by configuration.
		if config.CiliumTestConfig.Reprovision {
			var nodesInt int
			nodes := os.Getenv(k8sNodesEnv)
			if nodes != "" {
				nodesInt, err = strconv.Atoi(nodes)
				if err != nil {
					Fail(fmt.Sprintf("%s value is not a number %q", k8sNodesEnv, nodes))
				}
			}

			err = helpers.CreateVM(helpers.K8s1VMName())
			if err != nil {
				reportCreateVMFailure(helpers.K8s1VMName(), err)
			}

			if nodesInt != 1 {
				err = helpers.CreateVM(helpers.K8s2VMName())
				if err != nil {
					reportCreateVMFailure(helpers.K8s2VMName(), err)
				}
			}

			// For Nightly test we need to have more than two kubernetes nodes. If
			// the env variable K8S_NODES is present, more nodes will be created.
			if nodesInt > 2 {
				for i := 3; i <= nodesInt; i++ {
					vmName := fmt.Sprintf("%s%d-%s", helpers.K8s, i, helpers.GetCurrentK8SEnv())
					err = helpers.CreateVM(vmName)
					if err != nil {
						reportCreateVMFailure(vmName, err)
					}
				}
			}
		}
		kubectl := helpers.CreateKubectl(helpers.K8s1VMName(), logger)
		kubectl.PrepareCluster()

		// Cleanup all cilium components if there are any leftovers from previous
		// run, like when running tests locally.
		kubectl.CleanupCiliumComponents()

		kubectl.ApplyDefault(kubectl.GetFilePath("../examples/kubernetes/addons/prometheus/monitoring-example.yaml"))

		go kubectl.PprofReport()
	}
})

var _ = AfterSuite(func() {
	if !helpers.IsRunningOnJenkins() {
		GinkgoPrint("AfterSuite: not running on Jenkins; leaving VMs running for debugging")
		return
	}
	// Errors are not checked here because it should fail on BeforeAll
	scope, _ := helpers.GetScope()
	GinkgoPrint("cleaning up VMs started for %s tests", scope)
	switch scope {
	case helpers.Runtime:
		helpers.DestroyVM(helpers.Runtime)
	case helpers.K8s:
		helpers.DestroyVM(helpers.K8s1VMName())
		helpers.DestroyVM(helpers.K8s2VMName())
	}
})

func getOrSetEnvVar(key, value string) {
	if val := os.Getenv(key); val == "" {
		log.Infof("environment variable %q was not set; setting to default value %q", key, value)
		os.Setenv(key, value)
	}
}

var _ = AfterEach(func() {

	// Send the Checks output to Junit report to be render on Jenkins.
	defer helpers.CheckLogs.Reset()
	GinkgoPrint("<Checks>\n%s\n</Checks>\n", helpers.CheckLogs.Buffer.String())

	defer logger.TestLogWriterReset()
	err := helpers.CreateLogFile(logger.TestLogFileName, logger.TestLogWriter.Bytes())
	if err != nil {
		log.WithError(err).Errorf("cannot create log file '%s'", logger.TestLogFileName)
		return
	}

	defer helpers.SSHMetaLogs.Reset()
	err = helpers.CreateLogFile(commandsLogFileName, helpers.SSHMetaLogs.Bytes())
	if err != nil {
		log.WithError(err).Errorf("cannot create log file '%s'", commandsLogFileName)
		return
	}

	// This piece of code is to enable zip attachments on Junit Output.
	if ginkgo.CurrentGinkgoTestDescription().Failed && helpers.IsRunningOnJenkins() {
		// ReportDirectory is already created. No check the error
		path, _ := helpers.CreateReportDirectory()
		zipFileName := fmt.Sprintf("%s_%s.zip", helpers.MakeUID(), GetTestName())
		zipFilePath := filepath.Join(helpers.TestResultsPath, zipFileName)

		_, err := exec.Command(
			"/bin/bash", "-c",
			fmt.Sprintf("zip -qr %s %s", zipFilePath, path)).CombinedOutput()
		if err != nil {
			log.WithError(err).Errorf("cannot create zip file '%s'", zipFilePath)
		}

		GinkgoPrint("[[ATTACHMENT|%s]]", zipFileName)
	}

	if !ginkgo.CurrentGinkgoTestDescription().Failed && helpers.IsRunningOnJenkins() {
		// If the test success delete the monitor.log filename to not store all
		// the data in Jenkins
		testPath, err := helpers.CreateReportDirectory()
		if err != nil {
			log.WithError(err).Error("cannot retrieve test result path")
			return
		}
		_ = os.Remove(filepath.Join(testPath, helpers.MonitorLogFileName))
	}
})
<commit_msg>test: Replace exit code -1 with exit code 1<commit_after>// Copyright 2017-2019 Authors of Cilium
//
// 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 ciliumTest

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"testing"
	"time"

	"github.com/cilium/cilium/pkg/logging"
	"github.com/cilium/cilium/test/config"
	. "github.com/cilium/cilium/test/ginkgo-ext"
	"github.com/cilium/cilium/test/helpers"
	"github.com/cilium/cilium/test/logger"
	gops "github.com/google/gops/agent"
	"github.com/onsi/ginkgo"
	ginkgoconfig "github.com/onsi/ginkgo/config"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/format"
	"github.com/sirupsen/logrus"
)

var (
	log             = logging.DefaultLogger
	DefaultSettings = map[string]string{
		"K8S_VERSION": "1.19",
	}
	k8sNodesEnv         = "K8S_NODES"
	commandsLogFileName = "cmds.log"
)

func init() {
	// Open socket for using gops to get stacktraces in case the tests deadlock.
	if err := gops.Listen(gops.Options{ShutdownCleanup: true}); err != nil {
		fmt.Fprintf(os.Stderr, "unable to start gops: %s", err)
		os.Exit(1)
	}

	for k, v := range DefaultSettings {
		getOrSetEnvVar(k, v)
	}
	os.RemoveAll(helpers.TestResultsPath)

	format.UseStringerRepresentation = true
}

func configLogsOutput() {
	log.SetLevel(logrus.DebugLevel)
	log.Out = &logger.TestLogWriter
	logrus.SetFormatter(&logger.Formatter)
	log.Formatter = &logger.Formatter
	log.Hooks.Add(&logger.LogHook{})

	GinkgoWriter = NewWriter(log.Out)
}

func ShowCommands() {
	if !config.CiliumTestConfig.ShowCommands {
		return
	}

	helpers.SSHMetaLogs = NewWriter(os.Stdout)
}

func TestTest(t *testing.T) {
	if config.CiliumTestConfig.TestScope != "" {
		helpers.UserDefinedScope = config.CiliumTestConfig.TestScope
		fmt.Printf("User specified the scope:  %q\n", config.CiliumTestConfig.TestScope)
	}
	if integration := helpers.GetCurrentIntegration(); integration != "" {
		fmt.Printf("Using CNI_INTEGRATION=%q\n", integration)

		switch integration {
		case helpers.CIIntegrationMicrok8s:
			fallthrough
		case helpers.CIIntegrationMinikube:
			fmt.Printf("Disabling multinode testing")
			config.CiliumTestConfig.Multinode = false
		default:
		}
	}

	configLogsOutput()
	ShowCommands()

	if config.CiliumTestConfig.HoldEnvironment {
		RegisterFailHandler(helpers.Fail)
	} else {
		RegisterFailHandler(Fail)
	}
	junitReporter := NewJUnitReporter(fmt.Sprintf(
		"%s.xml", helpers.GetScopeWithVersion()))
	RunSpecsWithDefaultAndCustomReporters(
		t, fmt.Sprintf("Suite-%s", helpers.GetScopeWithVersion()),
		[]ginkgo.Reporter{junitReporter})
}

func goReportSetupStatus() chan bool {
	if ginkgoconfig.DefaultReporterConfig.Verbose ||
		ginkgoconfig.DefaultReporterConfig.Succinct {
		// Dev told us they want more/less information than default. Skip.
		return nil
	}

	exit := make(chan bool)
	go func() {
		done := false
		iter := 0
		for {
			var out string
			select {
			case ok := <-exit:
				if ok {
					out = "●\n"
				} else {
					out = "◌\n"
				}
				done = true
			default:
				out = string(rune(int('◜') + iter%4))
			}
			fmt.Printf("\rSetting up test suite... %s", out)
			if done {
				return
			}
			time.Sleep(250 * time.Millisecond)
			iter++
		}
	}()
	return exit
}

func reportCreateVMFailure(vm string, err error) {
	failmsg := fmt.Sprintf(`
        ===================== ERROR - VM PROVISION FAILED =====================

        Unable to provision and start VM %q: %s", vm, err

        =======================================================================
        `, vm, err)
	GinkgoPrint(failmsg)
	Fail(failmsg)
}

var _ = BeforeAll(func() {
	helpers.Init()
	By("Starting tests: command line parameters: %+v environment variables: %v", config.CiliumTestConfig, os.Environ())
	go func() {
		defer GinkgoRecover()
		time.Sleep(config.CiliumTestConfig.Timeout)
		msg := fmt.Sprintf("Test suite timed out after %s", config.CiliumTestConfig.Timeout)
		By(msg)
		Fail(msg)
	}()

	var err error

	logger := log.WithFields(logrus.Fields{"testName": "BeforeAll"})
	scope, err := helpers.GetScope()
	if err != nil {
		Fail(fmt.Sprintf(
			"Cannot get the scope for running test, please use --cilium.testScope option: %s",
			err))
	}

	switch helpers.GetCurrentIntegration() {
	case helpers.CIIntegrationFlannel:
		switch helpers.GetCurrentK8SEnv() {
		case "1.8":
			log.Infof("Cilium in %q mode is not supported in Kubernetes 1.8 due CNI < 0.6.0", helpers.CIIntegrationFlannel)
			os.Exit(0)
			return
		}
	}

	if config.CiliumTestConfig.SSHConfig != "" {
		// If we set a different VM that it's not in our test environment
		// ginkgo cannot provision it, so skip setup below.
		return
	}

	if progressChan := goReportSetupStatus(); progressChan != nil {
		defer func() { progressChan <- err == nil }()
	}

	switch scope {
	case helpers.Runtime:
		// Boot / provision VMs if specified by configuration.
		if config.CiliumTestConfig.Reprovision {
			err = helpers.CreateVM(helpers.Runtime)
			if err != nil {
				log.WithError(err).Error("Error starting VM")
				reportCreateVMFailure(helpers.Runtime, err)
			}
		}

		vm := helpers.InitRuntimeHelper(helpers.Runtime, logger)
		err = vm.SetUpCilium()

		if err != nil {
			// AfterFailed function is not defined in this scope, fired the
			// ReportFailed manually for this assert to gather cilium logs Fix
			// #3428
			vm.ReportFailed()
			log.WithError(err).Error("Cilium was unable to be set up correctly")
			reportCreateVMFailure(helpers.Runtime, err)
		}
		go vm.PprofReport()

	case helpers.K8s:
		//FIXME: This should be:
		// Start k8s1 and provision kubernetes.
		// When finish, start to build cilium in background
		// Start k8s2
		// Wait until compilation finished, and pull cilium image on k8s2

		// Name for K8s VMs depends on K8s version that is running.

		// Boot / provision VMs if specified by configuration.
		if config.CiliumTestConfig.Reprovision {
			var nodesInt int
			nodes := os.Getenv(k8sNodesEnv)
			if nodes != "" {
				nodesInt, err = strconv.Atoi(nodes)
				if err != nil {
					Fail(fmt.Sprintf("%s value is not a number %q", k8sNodesEnv, nodes))
				}
			}

			err = helpers.CreateVM(helpers.K8s1VMName())
			if err != nil {
				reportCreateVMFailure(helpers.K8s1VMName(), err)
			}

			if nodesInt != 1 {
				err = helpers.CreateVM(helpers.K8s2VMName())
				if err != nil {
					reportCreateVMFailure(helpers.K8s2VMName(), err)
				}
			}

			// For Nightly test we need to have more than two kubernetes nodes. If
			// the env variable K8S_NODES is present, more nodes will be created.
			if nodesInt > 2 {
				for i := 3; i <= nodesInt; i++ {
					vmName := fmt.Sprintf("%s%d-%s", helpers.K8s, i, helpers.GetCurrentK8SEnv())
					err = helpers.CreateVM(vmName)
					if err != nil {
						reportCreateVMFailure(vmName, err)
					}
				}
			}
		}
		kubectl := helpers.CreateKubectl(helpers.K8s1VMName(), logger)
		kubectl.PrepareCluster()

		// Cleanup all cilium components if there are any leftovers from previous
		// run, like when running tests locally.
		kubectl.CleanupCiliumComponents()

		kubectl.ApplyDefault(kubectl.GetFilePath("../examples/kubernetes/addons/prometheus/monitoring-example.yaml"))

		go kubectl.PprofReport()
	}
})

var _ = AfterSuite(func() {
	if !helpers.IsRunningOnJenkins() {
		GinkgoPrint("AfterSuite: not running on Jenkins; leaving VMs running for debugging")
		return
	}
	// Errors are not checked here because it should fail on BeforeAll
	scope, _ := helpers.GetScope()
	GinkgoPrint("cleaning up VMs started for %s tests", scope)
	switch scope {
	case helpers.Runtime:
		helpers.DestroyVM(helpers.Runtime)
	case helpers.K8s:
		helpers.DestroyVM(helpers.K8s1VMName())
		helpers.DestroyVM(helpers.K8s2VMName())
	}
})

func getOrSetEnvVar(key, value string) {
	if val := os.Getenv(key); val == "" {
		log.Infof("environment variable %q was not set; setting to default value %q", key, value)
		os.Setenv(key, value)
	}
}

var _ = AfterEach(func() {

	// Send the Checks output to Junit report to be render on Jenkins.
	defer helpers.CheckLogs.Reset()
	GinkgoPrint("<Checks>\n%s\n</Checks>\n", helpers.CheckLogs.Buffer.String())

	defer logger.TestLogWriterReset()
	err := helpers.CreateLogFile(logger.TestLogFileName, logger.TestLogWriter.Bytes())
	if err != nil {
		log.WithError(err).Errorf("cannot create log file '%s'", logger.TestLogFileName)
		return
	}

	defer helpers.SSHMetaLogs.Reset()
	err = helpers.CreateLogFile(commandsLogFileName, helpers.SSHMetaLogs.Bytes())
	if err != nil {
		log.WithError(err).Errorf("cannot create log file '%s'", commandsLogFileName)
		return
	}

	// This piece of code is to enable zip attachments on Junit Output.
	if ginkgo.CurrentGinkgoTestDescription().Failed && helpers.IsRunningOnJenkins() {
		// ReportDirectory is already created. No check the error
		path, _ := helpers.CreateReportDirectory()
		zipFileName := fmt.Sprintf("%s_%s.zip", helpers.MakeUID(), GetTestName())
		zipFilePath := filepath.Join(helpers.TestResultsPath, zipFileName)

		_, err := exec.Command(
			"/bin/bash", "-c",
			fmt.Sprintf("zip -qr %s %s", zipFilePath, path)).CombinedOutput()
		if err != nil {
			log.WithError(err).Errorf("cannot create zip file '%s'", zipFilePath)
		}

		GinkgoPrint("[[ATTACHMENT|%s]]", zipFileName)
	}

	if !ginkgo.CurrentGinkgoTestDescription().Failed && helpers.IsRunningOnJenkins() {
		// If the test success delete the monitor.log filename to not store all
		// the data in Jenkins
		testPath, err := helpers.CreateReportDirectory()
		if err != nil {
			log.WithError(err).Error("cannot retrieve test result path")
			return
		}
		_ = os.Remove(filepath.Join(testPath, helpers.MonitorLogFileName))
	}
})
<|endoftext|>


<commit_before>// +build endtoend

package repoclone

import (
	"github.com/stretchr/testify/assert"
	"log"
	"os"
	"testing"
)

var testDir = "../test_directory/"

func TestMain(m *testing.M) {
	setup()
	output := m.Run()
	teardown()
	os.Exit(output)
}

func setup() {
	// Set this to true if you want more detail from the tests
	debug = false

	log.Println("Running build on repoclone")
	run("./cmd/repoclone", "go", "build") // compile repoclone
	log.Println("Creating directory")
	run("./", "mkdir", testDir) // make test dir
}

func teardown() {
	run("../", "rm", "-rf", testDir) // remove build dir
}

func TestClone(t *testing.T) {
	fuzzyDir := testDir + "fuzzy-octo-parakeet"
	defer os.RemoveAll(fuzzyDir)

	// Run the program to clone the repo
	run(testDir, "../repoclone/cmd/repoclone/repoclone", "RepoFetch")
	assert.True(t, fileExists(fuzzyDir+"/SecondFile.txt"))
}

func TestUpdate(t *testing.T) {
	defer os.RemoveAll("fuzzy-octo-parakeet")

	fuzzyDir := testDir + "fuzzy-octo-parakeet/"

	// Run the program to clone the repo
	run(testDir, "../repoclone/cmd/repoclone/repoclone", "RepoFetch")

	// Reset the repo to a previous commit
	run(fuzzyDir, "git", "reset", "840a42c1029c20b7b510753162894f4e47dcde1f")
	run(fuzzyDir, "rm", "SecondFile.txt")
	assert.False(t, fileExists("SecondFile.txt"))

	// Run the program again to pull this time
	run(testDir, "../repoclone/cmd/repoclone/repoclone", "RepoFetch", "-d")

	//assert that SecondFile does exist
	assert.True(t, fileExists(fuzzyDir+"/SecondFile.txt"))
}
<commit_msg>Tests cleaning up after themselves<commit_after>// +build endtoend

package repoclone

import (
	"github.com/stretchr/testify/assert"
	"log"
	"os"
	"testing"
)

var testDir = "../test_directory/"

func TestMain(m *testing.M) {
	setup()
	output := m.Run()
    debug = true
	teardown()
	os.Exit(output)
}

func setup() {
	// Set this to true if you want more detail from the tests
	debug = false

	log.Println("Running build on repoclone")
	run("./cmd/repoclone", "go", "build") // compile repoclone
	log.Println("Creating directory")
	run("./", "mkdir", testDir) // make test dir
}

func teardown() {
	run("./", "rm", "-rf", testDir) // remove build dir
}

func TestClone(t *testing.T) {
	fuzzyDir := testDir + "fuzzy-octo-parakeet"
	defer os.RemoveAll(fuzzyDir)

	// Run the program to clone the repo
	run(testDir, "../repoclone/cmd/repoclone/repoclone", "RepoFetch")
	assert.True(t, fileExists(fuzzyDir+"/SecondFile.txt"))
}

func TestUpdate(t *testing.T) {
	defer os.RemoveAll("fuzzy-octo-parakeet")

	fuzzyDir := testDir + "fuzzy-octo-parakeet/"

	// Run the program to clone the repo
	run(testDir, "../repoclone/cmd/repoclone/repoclone", "RepoFetch")

	// Reset the repo to a previous commit
	run(fuzzyDir, "git", "reset", "840a42c1029c20b7b510753162894f4e47dcde1f")
	run(fuzzyDir, "rm", "SecondFile.txt")
	assert.False(t, fileExists("SecondFile.txt"))

	// Run the program again to pull this time
	run(testDir, "../repoclone/cmd/repoclone/repoclone", "RepoFetch", "-d")

	//assert that SecondFile does exist
	assert.True(t, fileExists(fuzzyDir+"/SecondFile.txt"))
}
<|endoftext|>


<commit_before>package table

import "fmt"

type Table struct {
	data   []interface{}
	width  int
	height int
}

func New(width int, height int) Table {
	return Table{
		data:   make([]interface{}, width*height),
		width:  width,
		height: height,
	}
}

func (table *Table) GetWidth() int {
	return table.width
}

func (table *Table) GetHeight() int {
	return table.height
}

func (table *Table) Set(row int, column int, value interface{}) {
	table.data[table.getIndex(row, column)] = value
}

func (table *Table) Get(row int, column int) interface{} {
	return table.data[table.getIndex(row, column)]
}

func (table *Table) getIndex(row int, column int) int {
	if row >= table.height {
		panic(fmt.Sprintf("Table::get_index: `row` overflow (%v >= %v)", row, table.height))
	}
	if column >= table.width {
		panic(fmt.Sprintf("Table::get_index: `column` overflow (%v >= %v)", column, table.width))
	}

	return row*table.width + column
}
<commit_msg>Updates `Table` to be more idiomatic.<commit_after>package table

import "fmt"

type Table struct {
	data   []interface{}
	width  int
	height int
}

func New(width int, height int) Table {
	return Table{
		data:   make([]interface{}, width*height),
		width:  width,
		height: height,
	}
}

func (table *Table) Width() int {
	return table.width
}

func (table *Table) Height() int {
	return table.height
}

func (table *Table) Set(row int, column int, value interface{}) {
	table.data[table.index(row, column)] = value
}

func (table *Table) Get(row int, column int) interface{} {
	return table.data[table.index(row, column)]
}

func (table *Table) index(row int, column int) int {
	if row >= table.height {
		panic(fmt.Sprintf("Table::get_index: `row` overflow (%v >= %v)", row, table.height))
	}
	if column >= table.width {
		panic(fmt.Sprintf("Table::get_index: `column` overflow (%v >= %v)", column, table.width))
	}

	return row*table.width + column
}
<|endoftext|>


<commit_before>/**
 * (C) Copyright 2014, Deft Labs
 *
 * 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 dlshared

import (
	"errors"
	"testing"
)

// Confirm the way errors behave.
func TestErrors(t *testing.T) {

	err := errors.New("test")

	if nil == err {
		t.Errorf("TestErrors is broken - nil == error")
	}

	if err != err {
		t.Errorf("TestErrors is broken - error == error")
	}
}

// Confirm the way slices behave.
func TestSlices(t *testing.T) {

	var slice []byte

	if slice != nil {
		t.Errorf("TestSlice is broken - slice is not nil")
	}

	if len(slice) != 0 {
		t.Errorf("TestSlice is broken - slice length is not zero")
	}
}

// Confirm the way maps behave.
func TestMaps(t *testing.T) {

	mapTest := make(map[string]string)
	mapTest["one"] = "one"
	mapTest["two"] = "two"
	mapTest["three"] = "three"

	if _, found := mapTest["four"]; found {
		t.Errorf("TestMaps is broken - something found that does not exist")
	}

	if _, found := mapTest["one"]; !found {
		t.Errorf("TestMaps is broken - something not found that should be found")
	}

	// A missing key, should not panic.
	emptyStr := mapTest["four"]

	if len(emptyStr) != 0 {
		t.Errorf("TestMaps is broken - the empty value has something")
	}
}

<commit_msg>added data type tests<commit_after>/**
 * (C) Copyright 2014, Deft Labs
 *
 * 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 dlshared

import (
	"fmt"
	"errors"
	"testing"
)

// Confirm the way errors behave.
func TestErrors(t *testing.T) {

	err := errors.New("test")

	if nil == err {
		t.Errorf("TestErrors is broken - nil == error")
	}

	if err != err {
		t.Errorf("TestErrors is broken - error == error")
	}
}

// Confirm the way slices behave.
func TestSlices(t *testing.T) {

	var slice []byte

	if slice != nil {
		t.Errorf("TestSlice is broken - slice is not nil")
	}

	if len(slice) != 0 {
		t.Errorf("TestSlice is broken - slice length is not zero")
	}
}

// Confirm the way data types behave.
func TestDataTypes(t *testing.T) {

	val := fmt.Sprintf("%t", true)
	if val != "true" {
		t.Errorf("TestDataTypes is broken - true != true")
	}

	val = fmt.Sprintf("%t", false)
	if val != "false" {
		t.Errorf("TestDataTypes is broken - false != false")
	}
}

// Confirm the way maps behave.
func TestMaps(t *testing.T) {

	mapTest := make(map[string]string)
	mapTest["one"] = "one"
	mapTest["two"] = "two"
	mapTest["three"] = "three"

	if _, found := mapTest["four"]; found {
		t.Errorf("TestMaps is broken - something found that does not exist")
	}

	if _, found := mapTest["one"]; !found {
		t.Errorf("TestMaps is broken - something not found that should be found")
	}

	// A missing key, should not panic.
	emptyStr := mapTest["four"]

	if len(emptyStr) != 0 {
		t.Errorf("TestMaps is broken - the empty value has something")
	}

	var testMap map[string]string

	// Make sure a var map is nil
	if testMap != nil {
		t.Errorf("TestMaps is broken - uninitiated map should be nil")
	}
}

<|endoftext|>


<commit_before>/**
 * (C) Copyright 2014, Deft Labs
 *
 * 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 dlshared

import (
	"fmt"
	"sync"
	"time"
	"errors"
	"testing"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

func TestTime(t *testing.T) {

	now := time.Now()

	// This should not panic or return true.
	var toCheck time.Time
	if now.Before(toCheck) { t.Errorf("TestTime is broken - nothing is before Now") }
	if !now.After(toCheck) { t.Errorf("TestTime is broken - nothing is after Now") }
}

func TestChannels1(t *testing.T) {

	channel := make(chan bool, 1)

	channel <- true

	value, ok := <- channel

	if !value { t.Errorf("TestChannels1 is broken - value should be true") }

	if !ok { t.Errorf("TestChannels1 is broken - ok is false") }

	var waitGroup sync.WaitGroup

	// We are going to block here.
	go func() {
		waitGroup.Add(1)
		value, ok = <- channel
		if ok { t.Errorf("TestChannels1 is broken - ok should be false") }
		waitGroup.Done()
	}()

	close(channel)

	channel = make(chan bool, 1)

	waitGroup.Wait()

	// Make sure this exits as expected too.
	go func() {
		waitGroup.Add(1)
		<- channel
		waitGroup.Done()
	}()

	close(channel)
	waitGroup.Wait()

	structChannel := make(chan *bson.M, 1)
	close(structChannel)
	result := <- structChannel

	if result != nil { t.Errorf("TestChannels1 is broken - result should be nil") }

}

func TestChannels(t *testing.T) {
	test := &testPanicStruct{}
	channel := make(chan bool)
	close(channel)
	test.call2(channel)
	if test.called0 != 1 { t.Errorf("TestChannels is broken - called0 should be 1 but, is %d", test.called0) }

	test.called0 = 0

	channel1 := make(chan bool)

	go test.call3(channel1)

	close(channel1)

	time.Sleep(400*time.Millisecond)

	if test.called0 != 0 { t.Errorf("TestChannels is broken - called0 should be 0 but, is %d", test.called0) }
}

type testPanicStruct struct {
	called0 int
	called1 int
}

func (self *testPanicStruct) call3(channel chan bool) {
	defer func() { if r := recover(); r != nil { self.called0++ } }()
	for v := range channel { if v { } }
}

func (self *testPanicStruct) call2(channel chan bool) {
	defer func() { if r := recover(); r != nil { self.called0++ } }()
	channel <- true
}

func (self *testPanicStruct) call0() {
	defer func() { self.called0++ }()
	defer func() {
		if r := recover(); r != nil { }
		self.called0++
	}()
	panic("This is a panic: 0")
}

func (self *testPanicStruct) call1() {
	defer func() { self.called0++ }()
	panic("This is a panic: 1")
}

func TestPanic(t *testing.T) {

	test := &testPanicStruct{}

	test.call0()

	if test.called0 != 2 { t.Errorf("TestPanic is broken - called0 should be 2 but, is %d", test.called0) }

	defer func() {
		recover()
		if test.called1 != 0 { t.Errorf("TestPanic is broken - called1 should be zero but, is %d", test.called1) }
	}()

	test.call1()
}

func TestDivisionEquals(t *testing.T) {

	value := 10
	value /= 1
	if value != 10 { t.Errorf("TestDivisionEquals is broken - value off") }

	value = 20
	value /= 2
	if value != 10 { t.Errorf("TestDivisionEquals is broken - value off") }
}

type structPointerTest struct { name string }

func TestClosures(t *testing.T) {

	counter := testClosureMethod()

	for i := 0; i < 9; i++ { counter() }

	if counter() != 10 { t.Errorf("TestClosures is broken - count off") }
}

func testClosureMethod() func() int {
	count := 0
	return func() int { count++; return count }
}

func TestDeleteMissingKeyInMap(t *testing.T) { delete(make(map[string]string, 0), "missing") }

func TestDeletingKeysInMapWhileInRange(t *testing.T) {

	test := map[string]string { "test0": "value", "test1": "value", "test2": "value" }

	count := 0

	for key, _ := range test { delete(test, key); count++ }

	if count != 3 { t.Errorf("TestDeletingKeysInMapWhileInRange is broken - count off") }

	if len(test) != 0 { t.Errorf("TestDeletingKeysInMapWhileInRange is broken - length not zero") }

	for _, _ = range test {  }
}

func TestNilErr(t *testing.T) {
	if nil == mgo.ErrNotFound { t.Errorf("TestNilErr is broken - mgo not found matches nil") }
	if mgo.IsDup(nil) { t.Errorf("TestNilErr is broken - is dup matches nil") }
}

// Confirm the way structs/pointers works.
func TestStructs(t *testing.T) {

	id1 := structPointerTest{ name: "test" }
	id2 := structPointerTest{ name: "test" }

	if id1 != id2 { t.Errorf("TestStructs is broken - no match") }

	p1 := &id1
	p2 := &id2

	if p1 == p2 { t.Errorf("TestStructs is broken - pointer match") }
	if *p1 != *p2 { t.Errorf("TestStructs is broken - deferenced pointer - no match") }

	id1 = structPointerTest{ name: "test0" }
	id2 = structPointerTest{ name: "test1" }

	if id1 == id2 { t.Errorf("TestStructs is broken - match") }

	p1 = &id1
	p2 = &id2

	if p1 == p2 { t.Errorf("TestStructs is broken - pointer match") }
	if *p1 == *p2 { t.Errorf("TestStructs is broken - deferenced pointer match") }
}

func TestObjectId(t *testing.T) {

	id1 := bson.ObjectIdHex("532b19b784a8f7f139f3e338")
	id2 := bson.ObjectIdHex("532b19b784a8f7f139f3e338")

	if id1 != id2 { t.Errorf("TestObjectId is broken - no match") }

	p1 := &id1
	p2 := &id2

	if p1 == p2 { t.Errorf("TestObjectId is broken - pointer match") }
	if *p1 != *p2 { t.Errorf("TestObjectId is broken - deferenced pointer - no match") }

	id1 = bson.ObjectIdHex("532b19b784a8f7f139f3e338")
	id2 = bson.ObjectIdHex("532b19b884a8f7f139f3e339")

	if id1 == id2 { t.Errorf("TestStructs is broken - match") }

	p1 = &id1
	p2 = &id2

	if p1 == p2 { t.Errorf("TestStructs is broken - pointer match") }
	if *p1 == *p2 { t.Errorf("TestStructs is broken - deferenced pointer match") }
}

// Confirm the way errors behave.
func TestErrors(t *testing.T) {

	err := errors.New("test")

	if nil == err { t.Errorf("TestErrors is broken - nil == error") }

	if err != err { t.Errorf("TestErrors is broken - error == error") }
}

// Confirm the way slices behave.
func TestSlices(t *testing.T) {

	var slice []byte

	if slice != nil { t.Errorf("TestSlice is broken - slice is not nil") }

	if len(slice) != 0 { t.Errorf("TestSlice is broken - slice length is not zero") }
}

// Confirm the way data types behave.
func TestDataTypes(t *testing.T) {

	val := fmt.Sprintf("%t", true)
	if val != "true" { t.Errorf("TestDataTypes is broken - true != true") }

	val = fmt.Sprintf("%t", false)
	if val != "false" { t.Errorf("TestDataTypes is broken - false != false") }
}

// Confirm the way range behaves.
func TestRange(t *testing.T) {

	var test map[string]string

	// This should not panic
	for _, _ = range test { }

	// Just to be clear again
	test = nil

	// This should not panic
	for _, _ = range test { }
}

// Confirm the way maps behave.
func TestMaps(t *testing.T) {

	mapTest := make(map[string]string)
	mapTest["one"] = "one"
	mapTest["two"] = "two"
	mapTest["three"] = "three"

	if _, found := mapTest["four"]; found { t.Errorf("TestMaps is broken - something found that does not exist") }

	if _, found := mapTest["one"]; !found { t.Errorf("TestMaps is broken - something not found that should be found") }

	// A missing key, should not panic.
	emptyStr := mapTest["four"]

	if len(emptyStr) != 0 { t.Errorf("TestMaps is broken - the empty value has something") }

	var testMap map[string]string

	// Make sure a var map is nil
	if testMap != nil { t.Errorf("TestMaps is broken - uninitiated map should be nil") }

	// This should not panic.
	for _, v := range testMap { if v == "" { } }
}

<commit_msg>added duration test.<commit_after>/**
 * (C) Copyright 2014, Deft Labs
 *
 * 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 dlshared

import (
	"fmt"
	"sync"
	"time"
	"errors"
	"testing"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

func TestTime(t *testing.T) {

	now := time.Now()

	// This should not panic or return true.
	var toCheck time.Time
	if now.Before(toCheck) { t.Errorf("TestTime is broken - nothing is before Now") }
	if !now.After(toCheck) { t.Errorf("TestTime is broken - nothing is after Now") }
}

func TestTimeDuration(t *testing.T) {

	now := time.Now()
	then := now.Add(60*time.Second)

	duration := then.Sub(now)

	if duration.Seconds() != 60 { t.Errorf("TestTimeDuration is broken - value should be 60") }
}

func TestChannels1(t *testing.T) {

	channel := make(chan bool, 1)

	channel <- true

	value, ok := <- channel

	if !value { t.Errorf("TestChannels1 is broken - value should be true") }

	if !ok { t.Errorf("TestChannels1 is broken - ok is false") }

	var waitGroup sync.WaitGroup

	// We are going to block here.
	go func() {
		waitGroup.Add(1)
		value, ok = <- channel
		if ok { t.Errorf("TestChannels1 is broken - ok should be false") }
		waitGroup.Done()
	}()

	close(channel)

	channel = make(chan bool, 1)

	waitGroup.Wait()

	// Make sure this exits as expected too.
	go func() {
		waitGroup.Add(1)
		<- channel
		waitGroup.Done()
	}()

	close(channel)
	waitGroup.Wait()

	structChannel := make(chan *bson.M, 1)
	close(structChannel)
	result := <- structChannel

	if result != nil { t.Errorf("TestChannels1 is broken - result should be nil") }

}

func TestChannels(t *testing.T) {
	test := &testPanicStruct{}
	channel := make(chan bool)
	close(channel)
	test.call2(channel)
	if test.called0 != 1 { t.Errorf("TestChannels is broken - called0 should be 1 but, is %d", test.called0) }

	test.called0 = 0

	channel1 := make(chan bool)

	go test.call3(channel1)

	close(channel1)

	time.Sleep(400*time.Millisecond)

	if test.called0 != 0 { t.Errorf("TestChannels is broken - called0 should be 0 but, is %d", test.called0) }
}

type testPanicStruct struct {
	called0 int
	called1 int
}

func (self *testPanicStruct) call3(channel chan bool) {
	defer func() { if r := recover(); r != nil { self.called0++ } }()
	for v := range channel { if v { } }
}

func (self *testPanicStruct) call2(channel chan bool) {
	defer func() { if r := recover(); r != nil { self.called0++ } }()
	channel <- true
}

func (self *testPanicStruct) call0() {
	defer func() { self.called0++ }()
	defer func() {
		if r := recover(); r != nil { }
		self.called0++
	}()
	panic("This is a panic: 0")
}

func (self *testPanicStruct) call1() {
	defer func() { self.called0++ }()
	panic("This is a panic: 1")
}

func TestPanic(t *testing.T) {

	test := &testPanicStruct{}

	test.call0()

	if test.called0 != 2 { t.Errorf("TestPanic is broken - called0 should be 2 but, is %d", test.called0) }

	defer func() {
		recover()
		if test.called1 != 0 { t.Errorf("TestPanic is broken - called1 should be zero but, is %d", test.called1) }
	}()

	test.call1()
}

func TestDivisionEquals(t *testing.T) {

	value := 10
	value /= 1
	if value != 10 { t.Errorf("TestDivisionEquals is broken - value off") }

	value = 20
	value /= 2
	if value != 10 { t.Errorf("TestDivisionEquals is broken - value off") }
}

type structPointerTest struct { name string }

func TestClosures(t *testing.T) {

	counter := testClosureMethod()

	for i := 0; i < 9; i++ { counter() }

	if counter() != 10 { t.Errorf("TestClosures is broken - count off") }
}

func testClosureMethod() func() int {
	count := 0
	return func() int { count++; return count }
}

func TestDeleteMissingKeyInMap(t *testing.T) { delete(make(map[string]string, 0), "missing") }

func TestDeletingKeysInMapWhileInRange(t *testing.T) {

	test := map[string]string { "test0": "value", "test1": "value", "test2": "value" }

	count := 0

	for key, _ := range test { delete(test, key); count++ }

	if count != 3 { t.Errorf("TestDeletingKeysInMapWhileInRange is broken - count off") }

	if len(test) != 0 { t.Errorf("TestDeletingKeysInMapWhileInRange is broken - length not zero") }

	for _, _ = range test {  }
}

func TestNilErr(t *testing.T) {
	if nil == mgo.ErrNotFound { t.Errorf("TestNilErr is broken - mgo not found matches nil") }
	if mgo.IsDup(nil) { t.Errorf("TestNilErr is broken - is dup matches nil") }
}

// Confirm the way structs/pointers works.
func TestStructs(t *testing.T) {

	id1 := structPointerTest{ name: "test" }
	id2 := structPointerTest{ name: "test" }

	if id1 != id2 { t.Errorf("TestStructs is broken - no match") }

	p1 := &id1
	p2 := &id2

	if p1 == p2 { t.Errorf("TestStructs is broken - pointer match") }
	if *p1 != *p2 { t.Errorf("TestStructs is broken - deferenced pointer - no match") }

	id1 = structPointerTest{ name: "test0" }
	id2 = structPointerTest{ name: "test1" }

	if id1 == id2 { t.Errorf("TestStructs is broken - match") }

	p1 = &id1
	p2 = &id2

	if p1 == p2 { t.Errorf("TestStructs is broken - pointer match") }
	if *p1 == *p2 { t.Errorf("TestStructs is broken - deferenced pointer match") }
}

func TestObjectId(t *testing.T) {

	id1 := bson.ObjectIdHex("532b19b784a8f7f139f3e338")
	id2 := bson.ObjectIdHex("532b19b784a8f7f139f3e338")

	if id1 != id2 { t.Errorf("TestObjectId is broken - no match") }

	p1 := &id1
	p2 := &id2

	if p1 == p2 { t.Errorf("TestObjectId is broken - pointer match") }
	if *p1 != *p2 { t.Errorf("TestObjectId is broken - deferenced pointer - no match") }

	id1 = bson.ObjectIdHex("532b19b784a8f7f139f3e338")
	id2 = bson.ObjectIdHex("532b19b884a8f7f139f3e339")

	if id1 == id2 { t.Errorf("TestStructs is broken - match") }

	p1 = &id1
	p2 = &id2

	if p1 == p2 { t.Errorf("TestStructs is broken - pointer match") }
	if *p1 == *p2 { t.Errorf("TestStructs is broken - deferenced pointer match") }
}

// Confirm the way errors behave.
func TestErrors(t *testing.T) {

	err := errors.New("test")

	if nil == err { t.Errorf("TestErrors is broken - nil == error") }

	if err != err { t.Errorf("TestErrors is broken - error == error") }
}

// Confirm the way slices behave.
func TestSlices(t *testing.T) {

	var slice []byte

	if slice != nil { t.Errorf("TestSlice is broken - slice is not nil") }

	if len(slice) != 0 { t.Errorf("TestSlice is broken - slice length is not zero") }
}

// Confirm the way data types behave.
func TestDataTypes(t *testing.T) {

	val := fmt.Sprintf("%t", true)
	if val != "true" { t.Errorf("TestDataTypes is broken - true != true") }

	val = fmt.Sprintf("%t", false)
	if val != "false" { t.Errorf("TestDataTypes is broken - false != false") }
}

// Confirm the way range behaves.
func TestRange(t *testing.T) {

	var test map[string]string

	// This should not panic
	for _, _ = range test { }

	// Just to be clear again
	test = nil

	// This should not panic
	for _, _ = range test { }
}

// Confirm the way maps behave.
func TestMaps(t *testing.T) {

	mapTest := make(map[string]string)
	mapTest["one"] = "one"
	mapTest["two"] = "two"
	mapTest["three"] = "three"

	if _, found := mapTest["four"]; found { t.Errorf("TestMaps is broken - something found that does not exist") }

	if _, found := mapTest["one"]; !found { t.Errorf("TestMaps is broken - something not found that should be found") }

	// A missing key, should not panic.
	emptyStr := mapTest["four"]

	if len(emptyStr) != 0 { t.Errorf("TestMaps is broken - the empty value has something") }

	var testMap map[string]string

	// Make sure a var map is nil
	if testMap != nil { t.Errorf("TestMaps is broken - uninitiated map should be nil") }

	// This should not panic.
	for _, v := range testMap { if v == "" { } }
}

<|endoftext|>


<commit_before>/**
 * Package graph implements a Graph that can be either a King's graph
 * or a Grid graph. It can generate a graph from a given image.
 */
package graph

import (
	"image"
	"image/color"
	"math"
)

/**
 * Used to compute the weight of an edge when generating a graph
 * from an image
 */
type Pixel struct {
	X, Y  int
	Color color.Color
}

/**
 * Type of the functions that are used to compute the weight of
 * an edge when generating a graph from an image
 */
type WeightFn func(Pixel, Pixel) float64

/**
 * Represents a graph edge. It contains the ids of the two vertices
 * that it connects and the weight of the edge between them
 */
type Edge struct {
	u, v   int
	weight float64
}

/**
 * Return the id of one of the vertices that Edge e connects
 */
func (e *Edge) U() int {
	return e.u
}

/**
 * Return the id of one of the vertices that Edge e connects
 */
func (e *Edge) V() int {
	return e.v
}

/**
 * Return the weight of Edge e
 */
func (e *Edge) Weight() float64 {
	return e.weight
}

/**
 * Used to store all the edges that the graph contains.
 * It can be used with sort.Sort
 */
type EdgeList []Edge

/**
 * Return the number of edges that the EdgeList edges stores
 */
func (edges EdgeList) Len() int {
	return len(edges)
}

/**
 * Returns true if the weight of the edge i is less than the weight
 * of the edge j
 */
func (edges EdgeList) Less(i, j int) bool {
	return edges[i].weight < edges[j].weight
}

/**
 * In place swap of two edges i and j in the edge list
 */
func (edges EdgeList) Swap(i, j int) {
	edges[i], edges[j] = edges[j], edges[i]
}

/**
 * Used to recongise which type of graph to generate
 */
type GraphType int

const (
	GRIDGRAPH  GraphType = iota
	KINGSGRAPH GraphType = iota
)

/**
 * Graph datatype. Contains a list of edges, the graph width and height and
 * if it's a King's graph or a Grid graph
 */
type Graph struct {
	edges         EdgeList
	width, height int
	graphType     GraphType
}

/**
 * Returns a new width x height King's or Grid graph. It assigns a weight of Infinity
 * to all edges
 */
func New(width, height int, graphType GraphType) *Graph {
	g := new(Graph)
	g.width = width
	g.height = height
	g.graphType = graphType
	g.edges = make(EdgeList, 0, g.TotalEdges())

	for y := 0; y < g.height; y++ {
		for x := 0; x < g.width; x++ {
			p := x + y*g.width
			for n := range g.Neighbors(p) {
				g.edges = append(g.edges, Edge{u: p, v: n, weight: math.Inf(1)})
			}
		}
	}
	return g
}

/**
 * Returns a new graph that represents the image img. The graph will be either
 * a King's grph or a Grid graph. It will compute the edge weights using the
 * provided function weight.
 */
func FromImage(img image.Image, weight WeightFn, graphType GraphType) *Graph {
	g := new(Graph)
	g.height = img.Bounds().Max.Y
	g.width = img.Bounds().Max.X
	g.graphType = graphType
	g.edges = make(EdgeList, 0, g.TotalEdges())

	for y := 0; y < g.height; y++ {
		for x := 0; x < g.width; x++ {
			p := x + y*g.width
			pixel := Pixel{X: x, Y: y, Color: img.At(x, y)}
			for n := range g.Neighbors(p) {
				x2, y2 := n%g.width, n/g.width
				pixel2 := Pixel{X: x2, Y: x2, Color: img.At(x2, y2)}
				w := weight(pixel, pixel2)
				g.edges = append(g.edges, Edge{u: p, v: n, weight: w})
			}
		}
	}
	return g
}

/**
 * Return the ids of the vertices to which v is adjacent
 */
func (g *Graph) Neighbors(v int) <-chan int {
	ch := make(chan int)
	go func() {
		x, y := v%g.width, v/g.width
		if x+1 < g.width {
			ch <- v + 1
		}
		if y+1 < g.height {
			ch <- v + g.width
		}
		if g.graphType == KINGSGRAPH {
			if y-1 >= 0 && x+1 < g.width {
				ch <- v - g.width + 1
			}
			if y+1 < g.height && x+1 < g.width {
				ch <- v + g.width + 1
			}
		}
		close(ch)
	}()
	return ch
}

/**
 * Returns the width of a graph
 */
func (g *Graph) Width() int {
	return g.width
}

/**
 * Returns the height of a graph
 */
func (g *Graph) Height() int {
	return g.height
}

/**
 * Returns the total number of edges that the graph has
 */
func (g *Graph) TotalEdges() int {
	if g.graphType == KINGSGRAPH {
		return 4*g.width*g.height - 3*(g.width+g.height) + 2
	}
	return (g.width-1)*g.height + g.width*(g.height-1)
}

/**
 * Returns the total number of vertices that the graph has
 */
func (g *Graph) TotalVertices() int {
	return g.width * g.height
}

/**
 * Returns all the edges that the graph has
 */
func (g *Graph) Edges() EdgeList {
	return g.edges
}
<commit_msg>Graph now can return the weight of some edge uv<commit_after>/**
 * Package graph implements a Graph that can be either a King's graph
 * or a Grid graph. It can generate a graph from a given image.
 */
package graph

import (
	"github.com/miguelfrde/image-segmentation/utils"
	"image"
	"image/color"
	"math"
)

/**
 * Used to compute the weight of an edge when generating a graph
 * from an image
 */
type Pixel struct {
	X, Y  int
	Color color.Color
}

/**
 * Type of the functions that are used to compute the weight of
 * an edge when generating a graph from an image
 */
type WeightFn func(Pixel, Pixel) float64

/**
 * Represents a graph edge. It contains the ids of the two vertices
 * that it connects and the weight of the edge between them
 */
type Edge struct {
	u, v   int
	weight float64
}

/**
 * Return the id of one of the vertices that Edge e connects
 */
func (e *Edge) U() int {
	return e.u
}

/**
 * Return the id of one of the vertices that Edge e connects
 */
func (e *Edge) V() int {
	return e.v
}

/**
 * Return the weight of Edge e
 */
func (e *Edge) Weight() float64 {
	return e.weight
}

/**
 * Used to store all the edges that the graph contains.
 * It can be used with sort.Sort
 */
type EdgeList []Edge

/**
 * Return the number of edges that the EdgeList edges stores
 */
func (edges EdgeList) Len() int {
	return len(edges)
}

/**
 * Returns true if the weight of the edge i is less than the weight
 * of the edge j
 */
func (edges EdgeList) Less(i, j int) bool {
	return edges[i].weight < edges[j].weight
}

/**
 * In place swap of two edges i and j in the edge list
 */
func (edges EdgeList) Swap(i, j int) {
	edges[i], edges[j] = edges[j], edges[i]
}

/**
 * Used to recongise which type of graph to generate
 */
type GraphType int

const (
	GRIDGRAPH  GraphType = iota
	KINGSGRAPH GraphType = iota
)

/**
 * Graph datatype. Contains a list of edges, the graph width and height and
 * if it's a King's graph or a Grid graph
 */
type Graph struct {
	edges         EdgeList
	width, height int
	graphType     GraphType
	weights       [][]float64
}

/**
 * Returns a new width x height King's or Grid graph. It assigns a weight of Infinity
 * to all edges
 */
func New(width, height int, graphType GraphType) *Graph {
	g := new(Graph)
	g.width = width
	g.height = height
	g.graphType = graphType
	g.edges = make(EdgeList, 0, g.TotalEdges())
	size := 4
	if graphType == KINGSGRAPH {
		size = 8
	}
	g.weights = make([][]float64, g.TotalVertices(), g.TotalVertices())
	for y := 0; y < g.height; y++ {
		for x := 0; x < g.width; x++ {
			p := x + y*g.width
			g.weights[p] = make([]float64, size/2, size/2)
			for n := range g.Neighbors(p) {
				g.edges = append(g.edges, Edge{u: p, v: n, weight: math.Inf(1)})
				g.weights[p][g.weightIndex(p, n)] = math.Inf(1)
			}
		}
	}
	return g
}

func (g *Graph) weightIndex(from, to int) int {
	if to == from+1 {
		return 0
	} else if to == from+g.width {
		return 1
	} else if to == from-g.width+1 {
		return 2
	} else {
		return 3
	}
}

/**
 * Returns a new graph that represents the image img. The graph will be either
 * a King's grph or a Grid graph. It will compute the edge weights using the
 * provided function weight.
 */
func FromImage(img image.Image, weight WeightFn, graphType GraphType) *Graph {
	g := new(Graph)
	g.height = img.Bounds().Max.Y
	g.width = img.Bounds().Max.X
	g.graphType = graphType
	g.edges = make(EdgeList, 0, g.TotalEdges())
	size := 4
	if graphType == KINGSGRAPH {
		size = 8
	}
	g.weights = make([][]float64, g.TotalVertices(), g.TotalVertices())

	for y := 0; y < g.height; y++ {
		for x := 0; x < g.width; x++ {
			p := x + y*g.width
			pixel := Pixel{X: x, Y: y, Color: img.At(x, y)}
			g.weights[p] = make([]float64, size/2, size/2)
			for n := range g.Neighbors(p) {
				x2, y2 := n%g.width, n/g.width
				pixel2 := Pixel{X: x2, Y: x2, Color: img.At(x2, y2)}
				w := weight(pixel, pixel2)
				g.edges = append(g.edges, Edge{u: p, v: n, weight: w})
				g.weights[p][g.weightIndex(p, n)] = w
			}
		}
	}
	return g
}

func (g *Graph) Weight(u, v int) float64 {
	if u == utils.MinI(u, v) || v == u-g.width+1 {
		return g.weights[u][g.weightIndex(u, v)]
	}
	return g.weights[v][g.weightIndex(v, u)]
}

/**
 * Return the ids of the vertices to which v is adjacent
 */
func (g *Graph) Neighbors(v int) <-chan int {
	ch := make(chan int, 4)
	go func() {
		x, y := v%g.width, v/g.width
		if x+1 < g.width {
			ch <- v + 1
		}
		if y+1 < g.height {
			ch <- v + g.width
		}
		if g.graphType == KINGSGRAPH {
			if y-1 >= 0 && x+1 < g.width {
				ch <- v - g.width + 1
			}
			if y+1 < g.height && x+1 < g.width {
				ch <- v + g.width + 1
			}
		}
		close(ch)
	}()
	return ch
}

/**
 * Returns the width of a graph
 */
func (g *Graph) Width() int {
	return g.width
}

/**
 * Returns the height of a graph
 */
func (g *Graph) Height() int {
	return g.height
}

/**
 * Returns the total number of edges that the graph has
 */
func (g *Graph) TotalEdges() int {
	if g.graphType == KINGSGRAPH {
		return 4*g.width*g.height - 3*(g.width+g.height) + 2
	}
	return (g.width-1)*g.height + g.width*(g.height-1)
}

/**
 * Returns the total number of vertices that the graph has
 */
func (g *Graph) TotalVertices() int {
	return g.width * g.height
}

/**
 * Returns all the edges that the graph has
 */
func (g *Graph) Edges() EdgeList {
	return g.edges
}
<|endoftext|>


<commit_before>// Copyright 2015-2016 Sevki <s@sevki.org>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package graph parses and generates build graphs
package graph

import (
	"fmt"
	"log"
	"os"

	"sync"

	"bldy.build/build"
	"bldy.build/build/label"
	"bldy.build/build/skylark"
	"github.com/pkg/errors"

	"bldy.build/build/postprocessor"
	bldytrg "bldy.build/build/rules/build"
)

var (
	l = log.New(os.Stdout, "graph: ", 0)
)

// Node encapsulates a target and represents a node in the build graph.
type Node struct {
	IsRoot        bool       `json:"-"`
	Target        build.Rule `json:"-"`
	Type          string
	Parents       map[string]*Node `json:"-"`
	Label         label.Label
	Worker        string
	PriorityCount int
	WG            sync.WaitGroup
	Status        build.Status
	Cached        bool
	Start, End    int64
	Hash          string
	Output        string `json:"-"`
	Once          sync.Once
	sync.Mutex
	Children map[string]*Node
	hash     []byte
}

// Graph represents a build graph
type Graph struct {
	Root  *Node
	vm    build.VM
	Nodes map[string]*Node
}

// New returns a new build graph relatvie to the working directory
func New(wd, target string) (*Graph, error) {
	vm, err := skylark.New(wd)
	if err != nil {
		return nil, errors.Wrap(err, "new graph")
	}
	g := Graph{
		vm:    vm,
		Nodes: make(map[string]*Node),
	}
	label, err := label.Parse(target)
	if err != nil {
		return nil, errors.Wrap(err, "new graph")
	}
	g.Root = g.getTarget(label)
	g.Root.IsRoot = true
	return &g, nil
}

// Priority counts how many nodes directly and indirectly depend on
// this node
func (n *Node) Priority() int {
	if n.PriorityCount < 0 {
		p := 0
		for _, c := range n.Parents {
			p += c.Priority() + 1
		}
		n.PriorityCount = p
	}
	return n.PriorityCount
}

func (g *Graph) getTarget(lbl *label.Label) (n *Node) {
	if gnode, ok := g.Nodes[lbl.String()]; ok {
		return gnode
	}
	t, err := g.vm.GetTarget(lbl)
	if err != nil {
		log.Fatal(err)
	}
	nLbl := label.Label{
		Package: lbl.Package,
		Name:    t.GetName(),
	}

	node := Node{
		Target:        t,
		Type:          fmt.Sprintf("%T", t)[1:],
		Children:      make(map[string]*Node),
		Parents:       make(map[string]*Node),
		Once:          sync.Once{},
		WG:            sync.WaitGroup{},
		Status:        build.Pending,
		Label:         nLbl,
		PriorityCount: -1,
	}

	post := postprocessor.New(nLbl.Package)

	err = post.ProcessDependencies(node.Target)
	if err != nil {
		l.Fatal(err)
	}

	var deps []build.Rule

	//group is a special case
	var group *bldytrg.Group
	switch node.Target.(type) {
	case *bldytrg.Group:
		group = node.Target.(*bldytrg.Group)
		group.Exports = make(map[string]string)
	}
	for _, d := range node.Target.GetDependencies() {
		depLbl, err := label.Parse(d)
		c := g.getTarget(depLbl)
		if err != nil {
			log.Printf("%q is not a valid url", depLbl)
			continue
		}
		node.WG.Add(1)
		if group != nil {
			for dst := range c.Target.Installs() {
				group.Exports[dst] = dst
			}
		}
		deps = append(deps, c.Target)

		node.Children[d] = c
		c.Parents[nLbl.String()] = &node
	}

	if err := post.ProcessPaths(t, deps); err != nil {
		l.Fatalf("path processing: %s", err.Error())
	}

	g.Nodes[nLbl.String()] = &node
	if t.GetName() == lbl.Name {
		n = &node
	} else {
		l.Fatalf("target name %q and url target %q don't match", t.GetName(), lbl.Name)
	}
	return n
}
<commit_msg>graph: fix logging and formatting<commit_after>// Copyright 2015-2016 Sevki <s@sevki.org>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package graph parses and generates build graphs
package graph

import (
	"fmt"
	"log"
	"os"

	"sync"

	"bldy.build/build"
	"bldy.build/build/label"
	"bldy.build/build/skylark"
	"github.com/pkg/errors"

	"bldy.build/build/postprocessor"
	bldytrg "bldy.build/build/rules/build"
)

var (
	l = log.New(os.Stdout, "graph: ", 0)
)

// Node encapsulates a target and represents a node in the build graph.
type Node struct {
	IsRoot        bool       `json:"-"`
	Target        build.Rule `json:"-"`
	Type          string
	Parents       map[string]*Node `json:"-"`
	Label         label.Label
	Worker        string
	PriorityCount int
	WG            sync.WaitGroup
	Status        build.Status
	Cached        bool
	Start, End    int64
	Hash          string
	Output        string `json:"-"`
	Once          sync.Once
	sync.Mutex
	Children map[string]*Node
	hash     []byte
}

// Graph represents a build graph
type Graph struct {
	Root  *Node
	vm    build.VM
	Nodes map[string]*Node
}

// New returns a new build graph relatvie to the working directory
func New(wd, target string) (*Graph, error) {
	vm, err := skylark.New(wd)
	if err != nil {
		return nil, errors.Wrap(err, "new graph")
	}
	g := Graph{
		vm:    vm,
		Nodes: make(map[string]*Node),
	}
	label, err := label.Parse(target)
	if err != nil {
		return nil, errors.Wrap(err, "new graph")
	}
	g.Root = g.getTarget(label)
	g.Root.IsRoot = true
	return &g, nil
}

// Priority counts how many nodes directly and indirectly depend on
// this node
func (n *Node) Priority() int {
	if n.PriorityCount < 0 {
		p := 0
		for _, c := range n.Parents {
			p += c.Priority() + 1
		}
		n.PriorityCount = p
	}
	return n.PriorityCount
}

func (g *Graph) getTarget(lbl *label.Label) (n *Node) {
	if gnode, ok := g.Nodes[lbl.String()]; ok {
		return gnode
	}
	t, err := g.vm.GetTarget(lbl)
	if err != nil {
		l.Fatal(err)
	}
	nLbl := label.Label{
		Package: lbl.Package,
		Name:    t.GetName(),
	}

	node := Node{
		Target:        t,
		Type:          fmt.Sprintf("%T", t)[1:],
		Children:      make(map[string]*Node),
		Parents:       make(map[string]*Node),
		Once:          sync.Once{},
		WG:            sync.WaitGroup{},
		Status:        build.Pending,
		Label:         nLbl,
		PriorityCount: -1,
	}

	post := postprocessor.New(nLbl.Package)

	err = post.ProcessDependencies(node.Target)
	if err != nil {
		l.Fatal(err)
	}

	var deps []build.Rule

	//group is a special case
	var group *bldytrg.Group
	switch node.Target.(type) {
	case *bldytrg.Group:
		group = node.Target.(*bldytrg.Group)
		group.Exports = make(map[string]string)
	}
	for _, d := range node.Target.GetDependencies() {
		depLbl, err := label.Parse(d)
		c := g.getTarget(depLbl)
		if err != nil {
			l.Printf("%q is not a valid url", depLbl)
			continue
		}
		node.WG.Add(1)
		if group != nil {
			for dst := range c.Target.Installs() {
				group.Exports[dst] = dst
			}
		}
		deps = append(deps, c.Target)

		node.Children[d] = c
		c.Parents[nLbl.String()] = &node
	}

	if err := post.ProcessPaths(t, deps); err != nil {
		l.Fatalf("path processing: %s", err.Error())
	}

	g.Nodes[nLbl.String()] = &node
	if t.GetName() == lbl.Name {
		n = &node
	} else {
		l.Fatalf("target name %q and url target %q don't match", t.GetName(), lbl.Name)
	}
	return n
}
<|endoftext|>


<commit_before>package bibtex

import (
	"errors"
	"fmt"
)

type parser struct {
	lexer     *lexer
	lexemes   chan lexeme
	lastToken lexeme
}

// @todo move to Reader

func ParseBibTeXEntry(in string) (BibTeXEntry, error) {
	return parseBibTeXSingle(in)
}

func ParseBibTeXEntries(in string) []BibTeXEntry {
	return parseBibTeXMultiple(in)
}

func parseBibTeXSingle(in string) (BibTeXEntry, error) {
	lexer, lexemes := lexBibTeX(in)
	p := &parser{
		lexer:   lexer,
		lexemes: lexemes,
	}
	return p.parse()
}

func parseBibTeXMultiple(in string) (results []BibTeXEntry) {
	results = make([]BibTeXEntry, 0)

	lexer, lexemes := lexBibTeX(in)
	p := &parser{
		lexer:   lexer,
		lexemes: lexemes,
	}

	for {
		entry, err := p.parse()
		if err == nil {
			results = append(results, entry)
		} else {
			if p.lastToken.typ == tokenEOF {
				break
			}
		}

	}
	return results
}

func (p *parser) parse() (b BibTeXEntry, err error) {
	b = newBibTeXEntry()
	err = p.expect(tokenEntryStart)

	if err != nil {
		return b, err
	}
	b, err = p.entry_type(b)

	err = p.expect(tokenLeftBrace)
	if err != nil {
		return b, err
	}

	b, err = p.entry_body(b)
	if err != nil {
		return b, err
	}
	return b, err
}

func (p *parser) entry_type(b BibTeXEntry) (r BibTeXEntry, err error) {
	r = b
	err = p.expect(tokenIdentifier)
	r.Type = p.lastToken.val
	return r, err
}

func (p *parser) entry_body(b BibTeXEntry) (r BibTeXEntry, err error) {
	r = b
	err = p.expect(tokenIdentifier)
	if err != nil {
		return r, err
	}

	r.Identifier = p.lastToken.val

	for p.lastToken.typ != tokenRightBrace && p.lastToken.typ != tokenEOF && p.lastToken.typ != tokenError {
		p.accept(tokenComma)

		t := p.nextToken()
		if t.typ == tokenRightBrace || t.typ == tokenEOF {
			break
		}

		if t.typ != tokenIdentifier {
			err = errors.New(fmt.Sprintf("error: unexpected token: %s (expected %s)", p.lastToken, tokenIdentifier))
			return r, err
		}
		key := p.lastToken.val

		err = p.expect(tokenEquals)

		t = p.nextToken()
		if t.typ != tokenString && t.typ != tokenNumber {
			err = errors.New(fmt.Sprintf("error: unexpected token: %s (expected string or number)", p.lastToken))
			return r, err
		}

		if err != nil {
			return r, err
		}
		r.addAttribute(key, p.lastToken.Value())
	}

	return r, nil
}

func (p *parser) nextToken() (t lexeme) {
	select {
	case t = <-p.lexemes:
	}
	p.lastToken = t
	return
}

func (p *parser) accept(l tokenType) bool {
	if t := p.nextToken(); t.typ == l {
		return true
	}
	return false
}

func (p *parser) expect(l tokenType) error {
	if !p.accept(l) {
		return errors.New(fmt.Sprintf("error: unexpected token: %s (expected %s)", p.lastToken, l))
	}
	return nil
}
<commit_msg>Update parser to accept identifiers (for unquoted values)<commit_after>package bibtex

import (
	"errors"
	"fmt"
)

type parser struct {
	lexer     *lexer
	lexemes   chan lexeme
	lastToken lexeme
}

// @todo move to Reader

func ParseBibTeXEntry(in string) (BibTeXEntry, error) {
	return parseBibTeXSingle(in)
}

func ParseBibTeXEntries(in string) []BibTeXEntry {
	return parseBibTeXMultiple(in)
}

func parseBibTeXSingle(in string) (BibTeXEntry, error) {
	lexer, lexemes := lexBibTeX(in)
	p := &parser{
		lexer:   lexer,
		lexemes: lexemes,
	}
	return p.parse()
}

func parseBibTeXMultiple(in string) (results []BibTeXEntry) {
	results = make([]BibTeXEntry, 0)

	lexer, lexemes := lexBibTeX(in)
	p := &parser{
		lexer:   lexer,
		lexemes: lexemes,
	}

	for {
		entry, err := p.parse()
		if err == nil {
			results = append(results, entry)
		} else {
			if p.lastToken.typ == tokenEOF || p.lastToken.typ == tokenError {
				break
			}
		}

	}
	return results
}

func (p *parser) parse() (b BibTeXEntry, err error) {
	b = newBibTeXEntry()
	err = p.expect(tokenEntryStart)

	if err != nil {
		return b, err
	}
	b, err = p.entry_type(b)

	err = p.expect(tokenLeftBrace)
	if err != nil {
		return b, err
	}

	b, err = p.entry_body(b)
	if err != nil {
		return b, err
	}
	return b, err
}

func (p *parser) entry_type(b BibTeXEntry) (r BibTeXEntry, err error) {
	r = b
	err = p.expect(tokenIdentifier)
	r.Type = p.lastToken.val
	return r, err
}

func (p *parser) entry_body(b BibTeXEntry) (r BibTeXEntry, err error) {
	r = b
	err = p.expect(tokenIdentifier)
	if err != nil {
		return r, err
	}

	r.Identifier = p.lastToken.val

	for p.lastToken.typ != tokenRightBrace && p.lastToken.typ != tokenEOF && p.lastToken.typ != tokenError {
		p.accept(tokenComma)

		t := p.nextToken()
		if t.typ == tokenRightBrace || t.typ == tokenEOF {
			break
		}

		if t.typ != tokenIdentifier {
			err = errors.New(fmt.Sprintf("error: unexpected token: %s (expected %s)", p.lastToken, tokenIdentifier))
			return r, err
		}
		key := p.lastToken.val
		err = p.expect(tokenEquals)
		if err != nil {
			return r, err
		}

		t = p.nextToken()
		if t.typ != tokenString && t.typ != tokenNumber && t.typ != tokenIdentifier {
			err = errors.New(fmt.Sprintf("error: unexpected token: %s (expected string or number)", p.lastToken))
			return r, err
		}

		if err != nil {
			return r, err
		}
		r.addAttribute(key, p.lastToken.Value())
	}

	return r, nil
}

func (p *parser) nextToken() (t lexeme) {
	select {
	case tok, ok := <-p.lexemes:
		if ok {
			t = tok
		} else {
			t = lexeme{tokenError, "Lexer done providing tokens"}
		}
		p.lastToken = t
	}
	return
}

func (p *parser) accept(l tokenType) bool {
	if t := p.nextToken(); t.typ == l {
		return true
	}
	return false
}

func (p *parser) expect(l tokenType) error {
	if !p.accept(l) {
		return errors.New(fmt.Sprintf("error: unexpected token: %s (expected %s)", p.lastToken, l))
	}
	return nil
}
<|endoftext|>


<commit_before>package narcissus

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// Parse parses a structure pointer and feeds its fields with Augeas data
func (n *Narcissus) Parse(val interface{}) error {
	ref, err := structRef(val)
	if err != nil {
		return fmt.Errorf("invalid interface: %v", err)
	}

	path, err := getPath(ref)
	if err != nil {
		return fmt.Errorf("undefined path: %v", err)
	}

	return n.parseStruct(ref, path)
}

func (n *Narcissus) parseStruct(ref reflect.Value, path string) error {
	refType := ref.Type()
	for i := 0; i < refType.NumField(); i++ {
		if refType.Field(i).Name == "augeasPath" {
			// Ignore the special `augeasPath` field
			continue
		}
		value, err := n.getField(ref.Field(i), refType.Field(i), path)
		// TODO: implement omitempty
		if err == ErrNodeNotFound {
			continue
		}
		if err != nil {
			return fmt.Errorf("failed to retrieve field %s: %v", refType.Field(i).Name, err)
		}
		if value == "" {
			// for now
			continue
		}
		err = setField(ref.Field(i), refType.Field(i), value)
		if err != nil {
			return err
		}
	}

	return nil
}

func (n *Narcissus) getField(field reflect.Value, fieldType reflect.StructField, path string) (interface{}, error) {
	fieldPath := fmt.Sprintf("%s/%s", path, fieldType.Tag.Get("path"))
	if field.Kind() == reflect.Slice {
		return n.getSliceField(field, fieldType, path, fieldPath)
	} else if field.Kind() == reflect.Map {
		return n.getMapField(field, fieldType, fieldPath)
	}
	return n.getSimpleField(fieldType.Type, fieldPath, fieldType.Tag)
}

func (n *Narcissus) getSimpleField(fieldType reflect.Type, fieldPath string, tag reflect.StructTag) (interface{}, error) {
	aug := n.Augeas
	var value string
	var err error
	if tag.Get("value-from") == "label" {
		value, err = aug.Label(fieldPath)
	} else {
		value, err = aug.Get(fieldPath)
	}
	if err != nil && strings.Contains(err.Error(), "No matching node") {
		return nil, ErrNodeNotFound
	}

	switch fieldType.Kind() {
	case reflect.String:
		return value, nil
	case reflect.Bool:
		bvalue, err := strconv.ParseBool(value)
		if err != nil {
			return nil, fmt.Errorf("failed to convert %s to bool: %v", value, err)
		}
		return bvalue, nil
	case reflect.Int:
		intValue, err := strconv.ParseInt(value, 10, 32)
		if err != nil {
			return nil, fmt.Errorf("failed to convert %s to int: %v", value, err)
		}
		return int(intValue), nil
	}
	return nil, fmt.Errorf("unsupported type %s", fieldType.Kind())
}

func (n *Narcissus) getSliceField(field reflect.Value, fieldType reflect.StructField, path, fieldPath string) (interface{}, error) {
	aug := n.Augeas

	if fieldType.Tag.Get("type") == "seq" {
		fieldPath = fmt.Sprintf("%s/*[label()=~regexp('[0-9]*')]", path)
	}
	matches, err := aug.Match(fieldPath)
	if err != nil {
		return nil, err
	}
	values := reflect.MakeSlice(field.Type(), len(matches), len(matches))
	for i, m := range matches {
		value, err := n.getStructOrSimpleField(field, m)
		if err != nil {
			return nil, fmt.Errorf("Failed to get slice element: %v", err)
		}
		values.Index(i).Set(value)
	}
	return values.Interface(), nil
}

func (n *Narcissus) getMapField(field reflect.Value, fieldType reflect.StructField, fieldPath string) (interface{}, error) {
	aug := n.Augeas
	values := reflect.MakeMap(field.Type())
	matches, err := aug.Match(fieldPath)
	if err != nil {
		return nil, err
	}
	for _, m := range matches {
		var label string
		if fieldType.Tag.Get("key") == "label" {
			label, err = aug.Label(m)
		} else {
			label, err = aug.Get(m)
		}
		if err != nil {
			return nil, err
		}
		value, err := n.getStructOrSimpleField(field, m)
		if err != nil {
			return nil, fmt.Errorf("Failed to get map element: %v", err)
		}
		values.SetMapIndex(reflect.ValueOf(label), value)
	}
	return values.Interface(), nil
}

func (n *Narcissus) getStructOrSimpleField(field reflect.Value, path string) (value reflect.Value, err error) {
	vType := field.Type().Elem()
	if vType.Kind() == reflect.Struct {
		vStruct := reflect.New(vType)
		err = n.parseStruct(vStruct.Elem(), path)
		if err != nil {
			err = fmt.Errorf("failed to get slice element: %v", err)
			return
		}
		return vStruct.Elem(), nil
	}
	val, err := n.getSimpleField(vType, path, "")
	if err != nil {
		err = fmt.Errorf("failed to get slice element: %v", err)
		return
	}
	return reflect.ValueOf(val), nil
}

func setField(field reflect.Value, fieldType reflect.StructField, value interface{}) error {
	if !field.CanSet() {
		return fmt.Errorf("cannot set field %s", fieldType.Name)
	}

	v := reflect.ValueOf(value)
	if field.Kind() == v.Kind() {
		field.Set(v)
		return nil
	}

	return fmt.Errorf("Wrong value type (%v for %v)", v.Kind(), field.Kind())
}
<commit_msg>no slice in error<commit_after>package narcissus

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// Parse parses a structure pointer and feeds its fields with Augeas data
func (n *Narcissus) Parse(val interface{}) error {
	ref, err := structRef(val)
	if err != nil {
		return fmt.Errorf("invalid interface: %v", err)
	}

	path, err := getPath(ref)
	if err != nil {
		return fmt.Errorf("undefined path: %v", err)
	}

	return n.parseStruct(ref, path)
}

func (n *Narcissus) parseStruct(ref reflect.Value, path string) error {
	refType := ref.Type()
	for i := 0; i < refType.NumField(); i++ {
		if refType.Field(i).Name == "augeasPath" {
			// Ignore the special `augeasPath` field
			continue
		}
		value, err := n.getField(ref.Field(i), refType.Field(i), path)
		// TODO: implement omitempty
		if err == ErrNodeNotFound {
			continue
		}
		if err != nil {
			return fmt.Errorf("failed to retrieve field %s: %v", refType.Field(i).Name, err)
		}
		if value == "" {
			// for now
			continue
		}
		err = setField(ref.Field(i), refType.Field(i), value)
		if err != nil {
			return err
		}
	}

	return nil
}

func (n *Narcissus) getField(field reflect.Value, fieldType reflect.StructField, path string) (interface{}, error) {
	fieldPath := fmt.Sprintf("%s/%s", path, fieldType.Tag.Get("path"))
	if field.Kind() == reflect.Slice {
		return n.getSliceField(field, fieldType, path, fieldPath)
	} else if field.Kind() == reflect.Map {
		return n.getMapField(field, fieldType, fieldPath)
	}
	return n.getSimpleField(fieldType.Type, fieldPath, fieldType.Tag)
}

func (n *Narcissus) getSimpleField(fieldType reflect.Type, fieldPath string, tag reflect.StructTag) (interface{}, error) {
	aug := n.Augeas
	var value string
	var err error
	if tag.Get("value-from") == "label" {
		value, err = aug.Label(fieldPath)
	} else {
		value, err = aug.Get(fieldPath)
	}
	if err != nil && strings.Contains(err.Error(), "No matching node") {
		return nil, ErrNodeNotFound
	}

	switch fieldType.Kind() {
	case reflect.String:
		return value, nil
	case reflect.Bool:
		bvalue, err := strconv.ParseBool(value)
		if err != nil {
			return nil, fmt.Errorf("failed to convert %s to bool: %v", value, err)
		}
		return bvalue, nil
	case reflect.Int:
		intValue, err := strconv.ParseInt(value, 10, 32)
		if err != nil {
			return nil, fmt.Errorf("failed to convert %s to int: %v", value, err)
		}
		return int(intValue), nil
	}
	return nil, fmt.Errorf("unsupported type %s", fieldType.Kind())
}

func (n *Narcissus) getSliceField(field reflect.Value, fieldType reflect.StructField, path, fieldPath string) (interface{}, error) {
	aug := n.Augeas

	if fieldType.Tag.Get("type") == "seq" {
		fieldPath = fmt.Sprintf("%s/*[label()=~regexp('[0-9]*')]", path)
	}
	matches, err := aug.Match(fieldPath)
	if err != nil {
		return nil, err
	}
	values := reflect.MakeSlice(field.Type(), len(matches), len(matches))
	for i, m := range matches {
		value, err := n.getStructOrSimpleField(field, m)
		if err != nil {
			return nil, fmt.Errorf("Failed to get slice element: %v", err)
		}
		values.Index(i).Set(value)
	}
	return values.Interface(), nil
}

func (n *Narcissus) getMapField(field reflect.Value, fieldType reflect.StructField, fieldPath string) (interface{}, error) {
	aug := n.Augeas
	values := reflect.MakeMap(field.Type())
	matches, err := aug.Match(fieldPath)
	if err != nil {
		return nil, err
	}
	for _, m := range matches {
		var label string
		if fieldType.Tag.Get("key") == "label" {
			label, err = aug.Label(m)
		} else {
			label, err = aug.Get(m)
		}
		if err != nil {
			return nil, err
		}
		value, err := n.getStructOrSimpleField(field, m)
		if err != nil {
			return nil, fmt.Errorf("Failed to get map element: %v", err)
		}
		values.SetMapIndex(reflect.ValueOf(label), value)
	}
	return values.Interface(), nil
}

func (n *Narcissus) getStructOrSimpleField(field reflect.Value, path string) (value reflect.Value, err error) {
	vType := field.Type().Elem()
	if vType.Kind() == reflect.Struct {
		vStruct := reflect.New(vType)
		err = n.parseStruct(vStruct.Elem(), path)
		if err != nil {
			err = fmt.Errorf("failed to get element: %v", err)
			return
		}
		return vStruct.Elem(), nil
	}
	val, err := n.getSimpleField(vType, path, "")
	if err != nil {
		err = fmt.Errorf("failed to get element: %v", err)
		return
	}
	return reflect.ValueOf(val), nil
}

func setField(field reflect.Value, fieldType reflect.StructField, value interface{}) error {
	if !field.CanSet() {
		return fmt.Errorf("cannot set field %s", fieldType.Name)
	}

	v := reflect.ValueOf(value)
	if field.Kind() == v.Kind() {
		field.Set(v)
		return nil
	}

	return fmt.Errorf("Wrong value type (%v for %v)", v.Kind(), field.Kind())
}
<|endoftext|>


<commit_before>package bitmap

// BitMap is a struct containing a slice of bytes,
// being used as a bitmap.
type BitMap struct {
	size int
	vals []byte
}

// New returns a BitMap. It requires a size. A bitmap with a size of
// eight or less will be one byte in size, and so on.
func New(s int) BitMap {
	l := s/8 + 1
	return BitMap{size: s, vals: make([]byte, l, l)}
}

// Size returns the size of a bitmap. This is the number
// of bits.
func (b BitMap) Size() int {
	return b.size
}

// For internal use; drives Set and Unset.
func (b BitMap) toggle(i int) {
	// Position of the byte in b.vals.
	p := i >> 3
	// Position of the bit in the byte.
	remainder := (i - (p * 8))
	// Toggle the bit.
	if remainder == 1 {
		b.vals[p] = b.vals[p] ^ 1
	} else {
		b.vals[p] = b.vals[p] ^ (1 << uint(remainder-1))
	}
}

// Set sets a position in
// the bitmap to 1.
func (b BitMap) Set(i int) {
	// Don't unset.
	if b.Get(i) {
		return
	}
	b.toggle(i)
}

// Unset sets a position in
// the bitmap to 0.
func (b BitMap) Unset(i int) {
	// Don't set.
	if !b.Get(i) {
		return
	}
	b.toggle(i)
}

// Values returns a slice of ints
// represented by the values in the bitmap.
func (b BitMap) Values() []int {
	list := make([]int, 0, b.Size())
	for i := 1; i <= b.Size(); i++ {
		if b.Get(i) {
			list = append(list, i)
		}
	}
	return list
}

// Get returns a boolean indicating whether
// the bit is set for the position in question.
func (b BitMap) Get(i int) bool {
	p := i >> 3
	remainder := i - (p * 8)
	if remainder == 1 {
		return b.vals[p] > b.vals[p]^1
	}
	return b.vals[p] > b.vals[p]^(1<<uint(remainder-1))
}
<commit_msg>Removes redundant parentheses.<commit_after>package bitmap

// BitMap is a struct containing a slice of bytes,
// being used as a bitmap.
type BitMap struct {
	size int
	vals []byte
}

// New returns a BitMap. It requires a size. A bitmap with a size of
// eight or less will be one byte in size, and so on.
func New(s int) BitMap {
	l := s/8 + 1
	return BitMap{size: s, vals: make([]byte, l, l)}
}

// Size returns the size of a bitmap. This is the number
// of bits.
func (b BitMap) Size() int {
	return b.size
}

// For internal use; drives Set and Unset.
func (b BitMap) toggle(i int) {
	// Position of the byte in b.vals.
	p := i >> 3
	// Position of the bit in the byte.
	remainder := i - (p * 8)
	// Toggle the bit.
	if remainder == 1 {
		b.vals[p] = b.vals[p] ^ 1
	} else {
		b.vals[p] = b.vals[p] ^ (1 << uint(remainder-1))
	}
}

// Set sets a position in
// the bitmap to 1.
func (b BitMap) Set(i int) {
	// Don't unset.
	if b.Get(i) {
		return
	}
	b.toggle(i)
}

// Unset sets a position in
// the bitmap to 0.
func (b BitMap) Unset(i int) {
	// Don't set.
	if !b.Get(i) {
		return
	}
	b.toggle(i)
}

// Values returns a slice of ints
// represented by the values in the bitmap.
func (b BitMap) Values() []int {
	list := make([]int, 0, b.Size())
	for i := 1; i <= b.Size(); i++ {
		if b.Get(i) {
			list = append(list, i)
		}
	}
	return list
}

// Get returns a boolean indicating whether
// the bit is set for the position in question.
func (b BitMap) Get(i int) bool {
	p := i >> 3
	remainder := i - (p * 8)
	if remainder == 1 {
		return b.vals[p] > b.vals[p]^1
	}
	return b.vals[p] > b.vals[p]^(1<<uint(remainder-1))
}
<|endoftext|>


<commit_before>package group

import (
	"github.com/taskcluster/taskcluster-cli/extpoints"

	tcclient "github.com/taskcluster/taskcluster-client-go"
)

func init() {
	extpoints.Register("group", cmd{})
}

type cmd struct {
}

func (cmd) ConfigOptions() map[string]extpoints.ConfigOption {
	return nil
}

func (cmd) Summary() string {
	return "Group related actions."
}

func (cmd) Usage() string {
	return `Group related actions.

Usage:
  groupcluster group cancel [--] <groupId>
`
}

func (cmd) Execute(context extpoints.Context) bool {
	args := context.Arguments

	if args["cancel"].(bool) {
		return executeSubCommand(context, runCancel)
	}

	return false
}

// executeSubCommand executes the given SubCommand.
func executeSubCommand(context extpoints.Context, subCommand SubCommand) bool {
	var c *tcclient.Credentials
	if context.Credentials != nil {
		c = context.Credentials.ToClientCredentials()
	}

	return subCommand(c, context.Arguments)
}
<commit_msg>Fix search/replace<commit_after>package group

import (
	"github.com/taskcluster/taskcluster-cli/extpoints"

	tcclient "github.com/taskcluster/taskcluster-client-go"
)

func init() {
	extpoints.Register("group", cmd{})
}

type cmd struct {
}

func (cmd) ConfigOptions() map[string]extpoints.ConfigOption {
	return nil
}

func (cmd) Summary() string {
	return "Group related actions."
}

func (cmd) Usage() string {
	return `Group related actions.

Usage:
  taskcluster group cancel [--] <groupId>
`
}

func (cmd) Execute(context extpoints.Context) bool {
	args := context.Arguments

	if args["cancel"].(bool) {
		return executeSubCommand(context, runCancel)
	}

	return false
}

// executeSubCommand executes the given SubCommand.
func executeSubCommand(context extpoints.Context, subCommand SubCommand) bool {
	var c *tcclient.Credentials
	if context.Credentials != nil {
		c = context.Credentials.ToClientCredentials()
	}

	return subCommand(c, context.Arguments)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/mxk/go-sqlite/sqlite3"
	"log"
	"os"
	"os/user"
	"time"
)

func main() {
	// config
	prog_version := "0.1"
	currentTime := time.Now().Format("02-01-2006, 15:04:05")
	args := os.Args[1:]
	// -----

	// sqlite
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	c, _ := sqlite3.Open(usr.HomeDir + "/.config/todol.db")
	// create a base table
	query := "CREATE TABLE notes(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date VARCHAR(21), text TEXT)"
	c.Exec(query)
	// -----

	if len(args) == 0 {
		fmt.Println("Todol v"+prog_version+" by CubexX\n\n",
			"Usage:\n",
			// help
			"\033[36m add\033[32m <text>\033[0m - add a note to your Todol\n",
			"\033[36m show\033[32m <all/id>\033[0m - show your notes/note by id\n",
			//"\033[36m edit\033[32m <id> <new text>\033[0m - edit your note by id\n",
			"\033[36m del\033[32m <all/id>\033[0m - delete all notes/by id")
	} else {
		switch args[0] {
		// add note
		case "add":
			if len(args[1:]) == 0 { // if not exists text of note
				fmt.Println("Use\033[36m todol add \033[32m<text>\033[0m")
			} else {
				fmt.Println("\033[32m\"" + args[1] + "\"\033[0m added to your Todol")
				// sqlite add note
				values := sqlite3.NamedArgs{"$text": args[1], "$date": currentTime}
				c.Exec("INSERT INTO notes(text, date) VALUES($text, $date)", values)

			}
		// show notes
		case "show":
			if len(args[1:]) == 0 { // if not exists id
				fmt.Println("Use\033[36m todol show \033[32m<all/id>\033[0m")
			} else {
				// show all notes
				if args[1] == "all" {
					sql := "SELECT * FROM notes"
					i := make(sqlite3.RowMap)
					d := make(sqlite3.RowMap)
					t := make(sqlite3.RowMap)
					for s, err := c.Query(sql); err == nil; err = s.Next() {
						var (
							id   int
							date string
							text string
						)
						s.Scan(&id, i)
						s.Scan(&date, d)
						s.Scan(&text, t)
						fmt.Println("\033[31mID:", id, "\033[34m", d["date"], "\033[0m\n", t["text"])
					}
				} else { // show note by id
					sql := "SELECT * FROM notes WHERE id=" + args[1]
					i := make(sqlite3.RowMap)
					d := make(sqlite3.RowMap)
					t := make(sqlite3.RowMap)
					for s, err := c.Query(sql); err == nil; err = s.Next() {
						var (
							id   int
							date string
							text string
						)
						s.Scan(&id, i)
						s.Scan(&date, d)
						s.Scan(&text, t)
						if len(string(id)) != 0 {
							fmt.Println("\033[31mID:", id, "\033[34m", d["date"], "\033[0m\n", t["text"])
						} else {
							fmt.Println("\033[31mNote with this ID doesn't exist!\033[0m")
						}
					}
				}
			}
		case "edit":
			if len(args[1:]) == 0 { // if not exists id
				fmt.Println("Use\033[36m todol edit\033[32m <id> \033[0m<text>")
			} else {
				if len(args[2:]) == 0 { // if not exists text
					fmt.Println("Use\033[36m todol edit\033[0m <id> \033[32m<text>\033[0m")
				} else {
					q := "UPDATE notes SET text='" + args[2] + "' WHERE id=" + args[1]
					c.Exec(q)
					fmt.Println("\033[32mNote with ID \033[31m" + args[1] + "\033[32m was updated\033[0m")
				}
			}
		case "del":
			if len(args[1:]) == 0 { // if not exists id
				fmt.Println("Use\033[36m todol show \033[32m<all/id>\033[0m")
			} else {
				// delete all notes
				if args[1] == "all" {
					q := "DELETE FROM notes"
					c.Exec(q)
					fmt.Println("\033[31mAll notes was deleted\033[0m")
				} else { // show note by id
					q := "DELETE FROM notes WHERE id=" + args[1]
					c.Exec(q)
					fmt.Println("\033[32mNote with ID \033[31m" + args[1] + "\033[32m was deleted\033[0m")
				}
			}
		// if not exists command
		default:
			fmt.Println("\033[31mInvalid command!\033[0m")
		}
	}
}
<commit_msg>edit func<commit_after>package main

import (
	"fmt"
	"github.com/mxk/go-sqlite/sqlite3"
	"log"
	"os"
	"os/user"
	"time"
)

func main() {
	// config
	prog_version := "0.1"
	currentTime := time.Now().Format("02-01-2006, 15:04:05")
	args := os.Args[1:]
	// -----

	// sqlite
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	c, _ := sqlite3.Open(usr.HomeDir + "/.config/todol.db")
	// create a base table
	query := "CREATE TABLE notes(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date VARCHAR(21), text TEXT)"
	c.Exec(query)
	// -----

	if len(args) == 0 {
		fmt.Println("Todol v"+prog_version+" by CubexX\n\n",
			"Usage:\n",
			// help
			"\033[36m add\033[32m <text>\033[0m - add a note to your Todol\n",
			"\033[36m show\033[32m <all/id>\033[0m - show your notes/note by id\n",
			"\033[36m edit\033[32m <id> <new text>\033[0m - edit your note by id\n",
			"\033[36m del\033[32m <all/id>\033[0m - delete all notes/by id")
	} else {
		switch args[0] {
		// add note
		case "add":
			if len(args[1:]) == 0 { // if not exists text of note
				fmt.Println("Use\033[36m todol add \033[32m<text>\033[0m")
			} else {
				fmt.Println("\033[32m\"" + args[1] + "\"\033[0m added to your Todol")
				// sqlite add note
				values := sqlite3.NamedArgs{"$text": args[1], "$date": currentTime}
				c.Exec("INSERT INTO notes(text, date) VALUES($text, $date)", values)

			}
		// show notes
		case "show":
			if len(args[1:]) == 0 { // if not exists id
				fmt.Println("Use\033[36m todol show \033[32m<all/id>\033[0m")
			} else {
				// show all notes
				if args[1] == "all" {
					sql := "SELECT * FROM notes"
					i := make(sqlite3.RowMap)
					d := make(sqlite3.RowMap)
					t := make(sqlite3.RowMap)
					for s, err := c.Query(sql); err == nil; err = s.Next() {
						var (
							id   int
							date string
							text string
						)
						s.Scan(&id, i)
						s.Scan(&date, d)
						s.Scan(&text, t)
						fmt.Println("\033[31mID:", id, "\033[34m", d["date"], "\033[0m\n", t["text"])
					}
				} else { // show note by id
					sql := "SELECT * FROM notes WHERE id=" + args[1]
					i := make(sqlite3.RowMap)
					d := make(sqlite3.RowMap)
					t := make(sqlite3.RowMap)
					for s, err := c.Query(sql); err == nil; err = s.Next() {
						var (
							id   int
							date string
							text string
						)
						s.Scan(&id, i)
						s.Scan(&date, d)
						s.Scan(&text, t)
						if len(string(id)) != 0 {
							fmt.Println("\033[31mID:", id, "\033[34m", d["date"], "\033[0m\n", t["text"])
						} else {
							fmt.Println("\033[31mNote with this ID doesn't exist!\033[0m")
						}
					}
				}
			}
		case "edit":
			if len(args[1:]) == 0 { // if not exists id
				fmt.Println("Use\033[36m todol edit\033[32m <id> \033[0m<text>")
			} else {
				if len(args[2:]) == 0 { // if not exists text
					fmt.Println("Use\033[36m todol edit\033[0m <id> \033[32m<text>\033[0m")
				} else {
					q := "UPDATE notes SET text='" + args[2] + "' WHERE id=" + args[1]
					c.Exec(q)
					fmt.Println("\033[32mNote with ID \033[31m" + args[1] + "\033[32m was updated\033[0m")
				}
			}
		case "del":
			if len(args[1:]) == 0 { // if not exists id
				fmt.Println("Use\033[36m todol show \033[32m<all/id>\033[0m")
			} else {
				// delete all notes
				if args[1] == "all" {
					q := "DELETE FROM notes"
					c.Exec(q)
					fmt.Println("\033[31mAll notes was deleted\033[0m")
				} else { // show note by id
					q := "DELETE FROM notes WHERE id=" + args[1]
					c.Exec(q)
					fmt.Println("\033[32mNote with ID \033[31m" + args[1] + "\033[32m was deleted\033[0m")
				}
			}
		// if not exists command
		default:
			fmt.Println("\033[31mInvalid command!\033[0m")
		}
	}
}
<|endoftext|>


<commit_before>package stripe

// TokenType is the list of allowed values for a token's type.
// Allowed values are "card", "bank_account".
type TokenType string

const (
	CardToken TokenType = "card"
	BankToken TokenType = "bank_account"
)

// TokenParams is the set of parameters that can be used when creating a token.
// For more details see https://stripe.com/docs/api#create_card_token and https://stripe.com/docs/api#create_bank_account_token.
type TokenParams struct {
	Params
	Card     *CardParams
	Bank     *BankAccountParams
	Customer string
}

// Token is the resource representing a Stripe token.
// For more details see https://stripe.com/docs/api#tokens.
type Token struct {
	Id      string       `json:"id"`
	Live    bool         `json:"livemode"`
	Created int64        `json:"created"`
	Type    TokenType    `json:"type"`
	Used    bool         `json:"used"`
	Bank    *BankAccount `json:"bank_account"`
	Card    *Card        `json:"card"`
}
<commit_msg>Include email field and parameter on Tokens<commit_after>package stripe

// TokenType is the list of allowed values for a token's type.
// Allowed values are "card", "bank_account".
type TokenType string

const (
	CardToken TokenType = "card"
	BankToken TokenType = "bank_account"
)

// TokenParams is the set of parameters that can be used when creating a token.
// For more details see https://stripe.com/docs/api#create_card_token and https://stripe.com/docs/api#create_bank_account_token.
type TokenParams struct {
	Params
	Card     *CardParams
	Bank     *BankAccountParams
	Customer string
	// Email is an undocumented parameter used by Stripe Checkout
	// It may be removed from the API without notice.
	Email string
}

// Token is the resource representing a Stripe token.
// For more details see https://stripe.com/docs/api#tokens.
type Token struct {
	Id      string       `json:"id"`
	Live    bool         `json:"livemode"`
	Created int64        `json:"created"`
	Type    TokenType    `json:"type"`
	Used    bool         `json:"used"`
	Bank    *BankAccount `json:"bank_account"`
	Card    *Card        `json:"card"`
	// Email is an undocumented field but included for all tokens created
	// with Stripe Checkout.
	Email string `json:"email,omitempty"`
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

func main() {
	passwrd := []byte("SomeReallyLong Awful String")

	// Hashing the password givn witht he cost of 10
	hashedPassword, err := bcrypt.GenerateFromPassword(passwrd, 10)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(hashedPassword))

	// Compare the password with the hash
	err = bcrypt.CompareHashAndPassword(hashedPassword, passwrd)
	fmt.Println(err) // nil means  it is a match

	r := gin.Default()

	r.GET("/", func(c *gin.Context) {
		c.String(200, "Passr.io")
	})

	r.Run(":3000")
}
<commit_msg>cleaning up the server from my stupid hacks<commit_after>package main

import (
	"github.com/gin-gonic/gin"
)

func main() {

	r := gin.Default()

	r.GET("/", func(c *gin.Context) {
		c.String(200, "Passr.io")
	})

	r.Run(":3000")
}
<|endoftext|>