<commit_before>package v7_test

import (
	"errors"

	"code.cloudfoundry.org/cli/command/commandfakes"
	. "code.cloudfoundry.org/cli/command/v7"
	"code.cloudfoundry.org/cli/command/v7/v7fakes"
	"code.cloudfoundry.org/cli/util/ui"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
)

var _ = Describe("share-service Command", func() {
	var (
		cmd             ShareServiceCommand
		testUI          *ui.UI
		fakeConfig      *commandfakes.FakeConfig
		fakeSharedActor *commandfakes.FakeSharedActor
		fakeActor       *v7fakes.FakeActor
		executeErr      error
	)

	BeforeEach(func() {
		testUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())
		fakeConfig = new(commandfakes.FakeConfig)
		fakeSharedActor = new(commandfakes.FakeSharedActor)
		fakeActor = new(v7fakes.FakeActor)

		cmd = ShareServiceCommand{
			BaseCommand: BaseCommand{
				UI:          testUI,
				Config:      fakeConfig,
				SharedActor: fakeSharedActor,
				Actor:       fakeActor,
			},
		}
	})

	JustBeforeEach(func() {
		executeErr = cmd.Execute(nil)
	})

	Context("user not targeting space", func() {
		BeforeEach(func() {
			fakeSharedActor.CheckTargetReturns(errors.New("space not targeted"))
		})

		It("checks the user is logged in, and targeting an org and space", func() {
			Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
			orgChecked, spaceChecked := fakeSharedActor.CheckTargetArgsForCall(0)
			Expect(orgChecked).To(BeTrue())
			Expect(spaceChecked).To(BeTrue())
		})

		It("fails the command", func() {
			Expect(executeErr).To(Not(BeNil()))
			Expect(executeErr.Error()).To(ContainSubstring("space not targeted"))
		})
	})

})
<commit_msg>Moved target check outside of context<commit_after>package v7_test

import (
	"errors"

	"code.cloudfoundry.org/cli/command/commandfakes"
	. "code.cloudfoundry.org/cli/command/v7"
	"code.cloudfoundry.org/cli/command/v7/v7fakes"
	"code.cloudfoundry.org/cli/util/ui"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
)

var _ = Describe("share-service Command", func() {
	var (
		cmd             ShareServiceCommand
		testUI          *ui.UI
		fakeConfig      *commandfakes.FakeConfig
		fakeSharedActor *commandfakes.FakeSharedActor
		fakeActor       *v7fakes.FakeActor
		executeErr      error
	)

	BeforeEach(func() {
		testUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())
		fakeConfig = new(commandfakes.FakeConfig)
		fakeSharedActor = new(commandfakes.FakeSharedActor)
		fakeActor = new(v7fakes.FakeActor)

		cmd = ShareServiceCommand{
			BaseCommand: BaseCommand{
				UI:          testUI,
				Config:      fakeConfig,
				SharedActor: fakeSharedActor,
				Actor:       fakeActor,
			},
		}
	})

	JustBeforeEach(func() {
		executeErr = cmd.Execute(nil)
	})

	It("checks the user is logged in, and targeting an org and space", func() {
		Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
		orgChecked, spaceChecked := fakeSharedActor.CheckTargetArgsForCall(0)
		Expect(orgChecked).To(BeTrue())
		Expect(spaceChecked).To(BeTrue())
	})

	Context("user not targeting space", func() {
		BeforeEach(func() {
			fakeSharedActor.CheckTargetReturns(errors.New("space not targeted"))
		})

		It("fails the command", func() {
			Expect(executeErr).To(Not(BeNil()))
			Expect(executeErr.Error()).To(ContainSubstring("space not targeted"))
		})
	})

})
<|endoftext|>


<commit_before>package monico

import (
	"os"
	"time"
)

type Moniter struct {
	path        string
	lastModTime time.Time
}

func NewMoniter(path string) (*Moniter, error) {
	info, err := os.Stat(path)
	if err != nil {
		return nil, err
	}
	return &Moniter{
		path:        path,
		lastModTime: info.ModTime(),
	}, nil
}

func NewMoniterWithWD() (*Moniter, error) {
	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	return NewMoniter(wd)
}

func (m *Moniter) Path() string {
	return m.path
}

func (m *Moniter) Modified() (bool, error) {
	info, err := os.Stat(m.path)
	if err != nil {
		return false, err
	}
	return !m.lastModTime.Equal(info.ModTime()), nil
}

func (m *Moniter) LastModTime() time.Time {
	return m.lastModTime
}

func (m *Moniter) UpdateModTime() error {
	info, err := os.Stat(m.path)
	if err != nil {
		return err
	}
	m.lastModTime = info.ModTime()
	return nil
}
<commit_msg>Remove Path<commit_after>package monico

import (
	"os"
	"time"
)

type Moniter struct {
	path        string
	lastModTime time.Time
}

func NewMoniter(path string) (*Moniter, error) {
	info, err := os.Stat(path)
	if err != nil {
		return nil, err
	}
	return &Moniter{
		path:        path,
		lastModTime: info.ModTime(),
	}, nil
}

func NewMoniterWithWD() (*Moniter, error) {
	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	return NewMoniter(wd)
}

func (m *Moniter) Modified() (bool, error) {
	info, err := os.Stat(m.path)
	if err != nil {
		return false, err
	}
	return !m.lastModTime.Equal(info.ModTime()), nil
}

func (m *Moniter) LastModTime() time.Time {
	return m.lastModTime
}

func (m *Moniter) UpdateModTime() error {
	info, err := os.Stat(m.path)
	if err != nil {
		return err
	}
	m.lastModTime = info.ModTime()
	return nil
}
<|endoftext|>


<commit_before>/*
Copyright 2020 The Kubernetes Authors.

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 logs

import (
	"encoding/json"
	"fmt"
	"testing"
	"time"
)

var record = struct {
	Error   error                  `json:"err"`
	Level   int                    `json:"v"`
	Message string                 `json:"msg"`
	Time    time.Time              `json:"ts"`
	Fields  map[string]interface{} `json:"fields"`
}{
	Error:   fmt.Errorf("test for error:%s", "default"),
	Level:   2,
	Message: "test",
	Time:    time.Unix(0, 123),
	Fields: map[string]interface{}{
		"str":     "foo",
		"int64-1": int64(1),
		"int64-2": int64(1),
		"float64": float64(1.0),
		"string1": "\n",
		"string2": "💩",
		"string3": "🤔",
		"string4": "🙊",
		"bool":    true,
		"request": struct {
			Method  string `json:"method"`
			Timeout int    `json:"timeout"`
			secret  string `json:"secret"`
		}{
			Method:  "GET",
			Timeout: 10,
			secret:  "pony",
		},
	},
}

func BenchmarkInfoLoggerInfo(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			jLogger := NewJSONLogger(nil)
			jLogger.Info("test",
				"str", "foo",
				"int64-1", int64(1),
				"int64-2", int64(1),
				"float64", float64(1.0),
				"string1", "\n",
				"string2", "💩",
				"string3", "🤔",
				"string4", "🙊",
				"bool", true,
				"request", struct {
					Method  string `json:"method"`
					Timeout int    `json:"timeout"`
					secret  string `json:"secret"`
				}{
					Method:  "GET",
					Timeout: 10,
					secret:  "pony",
				},
			)
		}
	})
}

func BenchmarkInfoLoggerInfoStandardJSON(b *testing.B) {
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			json.Marshal(record)
		}
	})
}

func BenchmarkZapLoggerError(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			jLogger := NewJSONLogger(nil)
			jLogger.Error(fmt.Errorf("test for error:%s", "default"),
				"test",
				"str", "foo",
				"int64-1", int64(1),
				"int64-2", int64(1),
				"float64", float64(1.0),
				"string1", "\n",
				"string2", "💩",
				"string3", "🤔",
				"string4", "🙊",
				"bool", true,
				"request", struct {
					Method  string `json:"method"`
					Timeout int    `json:"timeout"`
					secret  string `json:"secret"`
				}{
					Method:  "GET",
					Timeout: 10,
					secret:  "pony",
				},
			)
		}
	})
}
func BenchmarkZapLoggerErrorStandardJSON(b *testing.B) {
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			json.Marshal(record)
		}
	})
}

func BenchmarkZapLoggerV(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			jLogger := NewJSONLogger(nil)
			jLogger.V(1).Info("test",
				"str", "foo",
				"int64-1", int64(1),
				"int64-2", int64(1),
				"float64", float64(1.0),
				"string1", "\n",
				"string2", "💩",
				"string3", "🤔",
				"string4", "🙊",
				"bool", true,
				"request", struct {
					Method  string `json:"method"`
					Timeout int    `json:"timeout"`
					secret  string `json:"secret"`
				}{
					Method:  "GET",
					Timeout: 10,
					secret:  "pony",
				},
			)
		}
	})
}
<commit_msg>Cleanup json logging benchmarks<commit_after>/*
Copyright 2020 The Kubernetes Authors.

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 logs

import (
	"fmt"
	"testing"

	"go.uber.org/zap/zapcore"
)

func BenchmarkInfoLoggerInfo(b *testing.B) {
	logger := NewJSONLogger(zapcore.AddSync(&writeSyncer{}))
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			logger.Info("test",
				"str", "foo",
				"int64-1", int64(1),
				"int64-2", int64(1),
				"float64", float64(1.0),
				"string1", "\n",
				"string2", "💩",
				"string3", "🤔",
				"string4", "🙊",
				"bool", true,
				"request", struct {
					Method  string `json:"method"`
					Timeout int    `json:"timeout"`
					secret  string `json:"secret"`
				}{
					Method:  "GET",
					Timeout: 10,
					secret:  "pony",
				},
			)
		}
	})
}

func BenchmarkZapLoggerError(b *testing.B) {
	logger := NewJSONLogger(zapcore.AddSync(&writeSyncer{}))
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			logger.Error(fmt.Errorf("test for error:%s", "default"),
				"test",
				"str", "foo",
				"int64-1", int64(1),
				"int64-2", int64(1),
				"float64", float64(1.0),
				"string1", "\n",
				"string2", "💩",
				"string3", "🤔",
				"string4", "🙊",
				"bool", true,
				"request", struct {
					Method  string `json:"method"`
					Timeout int    `json:"timeout"`
					secret  string `json:"secret"`
				}{
					Method:  "GET",
					Timeout: 10,
					secret:  "pony",
				},
			)
		}
	})
}

func BenchmarkZapLoggerV(b *testing.B) {
	logger := NewJSONLogger(zapcore.AddSync(&writeSyncer{}))
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			logger.V(1).Info("test",
				"str", "foo",
				"int64-1", int64(1),
				"int64-2", int64(1),
				"float64", float64(1.0),
				"string1", "\n",
				"string2", "💩",
				"string3", "🤔",
				"string4", "🙊",
				"bool", true,
				"request", struct {
					Method  string `json:"method"`
					Timeout int    `json:"timeout"`
					secret  string `json:"secret"`
				}{
					Method:  "GET",
					Timeout: 10,
					secret:  "pony",
				},
			)
		}
	})
}

type writeSyncer struct{}

var _ zapcore.WriteSyncer = (*writeSyncer)(nil)

func (w writeSyncer) Write(p []byte) (n int, err error) {
	return len(p), nil
}

func (w writeSyncer) Sync() error {
	return nil
}
<|endoftext|>


<commit_before>package stemcell

import (
	bosherr "github.com/cloudfoundry/bosh-utils/errors"
	boshlog "github.com/cloudfoundry/bosh-utils/logger"

	"fmt"
	sl "github.com/maximilien/softlayer-go/softlayer"
)

type SoftLayerFinder struct {
	client sl.Client
	logger boshlog.Logger
}

func NewSoftLayerFinder(client sl.Client, logger boshlog.Logger) SoftLayerFinder {
	return SoftLayerFinder{client: client, logger: logger}
}

func (f SoftLayerFinder) FindById(id int) (Stemcell, bool, error) {
	accountService, err := f.client.GetSoftLayer_Account_Service()
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting SoftLayer AccountService")
	}

	stemcell, found, err := f.findByIdInVirtualDiskImages(id, accountService)
	if err != nil {
		return stemcell, found, err
	}

	if found {
		return stemcell, found, nil
	} else {
		stemcell, found, err = f.findByIdInVirtualGuestDeviceTemplateGroups(id, accountService)
		if err != nil {
			return stemcell, found, err
		}
	}

	return stemcell, found, nil
}

func (f SoftLayerFinder) Find(uuid string) (Stemcell, bool, error) {
	accountService, err := f.client.GetSoftLayer_Account_Service()
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting SoftLayer AccountService")
	}

	stemcell, found, err := f.findInVirtualDiskImages(uuid, accountService)
	if err != nil {
		return stemcell, found, err
	}

	if found {
		return stemcell, found, nil
	} else {
		stemcell, found, err = f.findInVirtualGuestDeviceTemplateGroups(uuid, accountService)
		if err != nil {
			return stemcell, found, err
		}
	}

	return stemcell, found, nil
}

func (f SoftLayerFinder) findInVirtualDiskImages(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`{"virtualDiskImages":{"uuid":{"operation":"%s"}}}`, uuid)
	virtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual disk images")
	}

	for _, vdImage := range virtualDiskImages {
		if vdImage.Uuid == uuid {
			return NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}

func (f SoftLayerFinder) findByIdInVirtualDiskImages(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`{"virtualDiskImages":{"id":{"operation":"%d"}}}`, id)
	virtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual disk images")
	}

	for _, vdImage := range virtualDiskImages {
		if vdImage.Id == id {
			return NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}

func (f SoftLayerFinder) findInVirtualGuestDeviceTemplateGroups(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`"blockDeviceTemplateGroups":{"globalIdentifier":{"operation":"%s"}}}`, uuid)
	vgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual guest device template groups")
	}

	for _, vgdtgGroup := range vgdtgGroups {
		if vgdtgGroup.GlobalIdentifier == uuid {
			return NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}

func (f SoftLayerFinder) findByIdInVirtualGuestDeviceTemplateGroups(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`"blockDeviceTemplateGroups":{"accountId":{"operation":"%d"}}}`, id)
	vgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual guest device template groups")
	}

	for _, vgdtgGroup := range vgdtgGroups {
		if vgdtgGroup.Id == id {
			return NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}
<commit_msg>Fixed a bug where to query stemcell with filter<commit_after>package stemcell

import (
	bosherr "github.com/cloudfoundry/bosh-utils/errors"
	boshlog "github.com/cloudfoundry/bosh-utils/logger"

	"fmt"
	sl "github.com/maximilien/softlayer-go/softlayer"
)

type SoftLayerFinder struct {
	client sl.Client
	logger boshlog.Logger
}

func NewSoftLayerFinder(client sl.Client, logger boshlog.Logger) SoftLayerFinder {
	return SoftLayerFinder{client: client, logger: logger}
}

func (f SoftLayerFinder) FindById(id int) (Stemcell, bool, error) {
	accountService, err := f.client.GetSoftLayer_Account_Service()
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting SoftLayer AccountService")
	}

	stemcell, found, err := f.findByIdInVirtualDiskImages(id, accountService)
	if err != nil {
		return stemcell, found, err
	}

	if found {
		return stemcell, found, nil
	} else {
		stemcell, found, err = f.findByIdInVirtualGuestDeviceTemplateGroups(id, accountService)
		if err != nil {
			return stemcell, found, err
		}
	}

	return stemcell, found, nil
}

func (f SoftLayerFinder) Find(uuid string) (Stemcell, bool, error) {
	accountService, err := f.client.GetSoftLayer_Account_Service()
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting SoftLayer AccountService")
	}

	stemcell, found, err := f.findInVirtualDiskImages(uuid, accountService)
	if err != nil {
		return stemcell, found, err
	}

	if found {
		return stemcell, found, nil
	} else {
		stemcell, found, err = f.findInVirtualGuestDeviceTemplateGroups(uuid, accountService)
		if err != nil {
			return stemcell, found, err
		}
	}

	return stemcell, found, nil
}

func (f SoftLayerFinder) findInVirtualDiskImages(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`{"virtualDiskImages":{"uuid":{"operation":"%s"}}}`, uuid)
	virtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual disk images")
	}

	for _, vdImage := range virtualDiskImages {
		if vdImage.Uuid == uuid {
			return NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}

func (f SoftLayerFinder) findByIdInVirtualDiskImages(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`{"virtualDiskImages":{"id":{"operation":"%d"}}}`, id)
	virtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual disk images")
	}

	for _, vdImage := range virtualDiskImages {
		if vdImage.Id == id {
			return NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}

func (f SoftLayerFinder) findInVirtualGuestDeviceTemplateGroups(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`{"blockDeviceTemplateGroups":{"globalIdentifier":{"operation":"%s"}}}`, uuid)
	vgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual guest device template groups")
	}

	for _, vgdtgGroup := range vgdtgGroups {
		if vgdtgGroup.GlobalIdentifier == uuid {
			return NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}

func (f SoftLayerFinder) findByIdInVirtualGuestDeviceTemplateGroups(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {
	filters := fmt.Sprintf(`{"blockDeviceTemplateGroups":{"id":{"operation":"%d"}}}`, id)
	vgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)
	if err != nil {
		return nil, false, bosherr.WrapError(err, "Getting virtual guest device template groups")
	}

	for _, vgdtgGroup := range vgdtgGroups {
		if vgdtgGroup.Id == id {
			return NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil
		}
	}

	return nil, false, nil
}
<|endoftext|>


<commit_before>package ast

import (
	"fmt"
	"reflect"
	"strings"
	"testing"

	"github.com/elliotchance/c2go/util"
)

func formatMultiLine(o interface{}) string {
	s := fmt.Sprintf("%#v", o)
	s = strings.Replace(s, "{", "{\n", -1)
	s = strings.Replace(s, ", ", "\n", -1)

	return s
}

func runNodeTests(t *testing.T, tests map[string]Node) {
	i := 1
	for line, expected := range tests {
		testName := fmt.Sprintf("Example%d", i)
		i++

		t.Run(testName, func(t *testing.T) {
			// Append the name of the struct onto the front. This would make the
			// complete line it would normally be parsing.
			name := reflect.TypeOf(expected).Elem().Name()
			actual := Parse(name + " " + line)

			if !reflect.DeepEqual(expected, actual) {
				t.Errorf("%s", util.ShowDiff(formatMultiLine(expected),
					formatMultiLine(actual)))
			}
		})
	}
}

func TestPrint(t *testing.T) {
	cond := &ConditionalOperator{}
	cond.AddChild(&ImplicitCastExpr{})
	cond.AddChild(&ImplicitCastExpr{})
	s := Atos(cond)
	if len(s) == 0 {
		t.Fatalf("Cannot convert AST tree : %#v", cond)
	}
	lines := strings.Split(s, "\n")
	var amount int
	for _, l := range lines {
		if strings.Contains(l, "ImplicitCastExpr") {
			amount++
		}
	}
	if amount != 2 {
		t.Error("Not correct design of output")
	}
}

var lines = []string{
	// c2go ast sqlite3.c | head -5000 | sed 's/^[ |`-]*//' | sed 's/<<<NULL>>>/NullStmt/g' | gawk 'length > 0 {print "`" $0 "`,"}'
}

func BenchmarkParse(b *testing.B) {
	for n := 0; n < b.N; n++ {
		for _, line := range lines {
			Parse(line)
		}
	}
}
<commit_msg>Revert "gofmt (#751)". Fixes #757 (#758)<commit_after>package ast

import (
	"fmt"
	"reflect"
	"strings"
	"testing"

	"github.com/elliotchance/c2go/util"
)

func formatMultiLine(o interface{}) string {
	s := fmt.Sprintf("%#v", o)
	s = strings.Replace(s, "{", "{\n", -1)
	s = strings.Replace(s, ", ", "\n", -1)

	return s
}

func runNodeTests(t *testing.T, tests map[string]Node) {
	i := 1
	for line, expected := range tests {
		testName := fmt.Sprintf("Example%d", i)
		i++

		t.Run(testName, func(t *testing.T) {
			// Append the name of the struct onto the front. This would make the
			// complete line it would normally be parsing.
			name := reflect.TypeOf(expected).Elem().Name()
			actual := Parse(name + " " + line)

			if !reflect.DeepEqual(expected, actual) {
				t.Errorf("%s", util.ShowDiff(formatMultiLine(expected),
					formatMultiLine(actual)))
			}
		})
	}
}

func TestPrint(t *testing.T) {
	cond := &ConditionalOperator{}
	cond.AddChild(&ImplicitCastExpr{})
	cond.AddChild(&ImplicitCastExpr{})
	s := Atos(cond)
	if len(s) == 0 {
		t.Fatalf("Cannot convert AST tree : %#v", cond)
	}
	lines := strings.Split(s, "\n")
	var amount int
	for _, l := range lines {
		if strings.Contains(l, "ImplicitCastExpr") {
			amount++
		}
	}
	if amount != 2 {
		t.Error("Not correct design of output")
	}
}

var lines = []string{
// c2go ast sqlite3.c | head -5000 | sed 's/^[ |`-]*//' | sed 's/<<<NULL>>>/NullStmt/g' | gawk 'length > 0 {print "`" $0 "`,"}'
}

func BenchmarkParse(b *testing.B) {
	for n := 0; n < b.N; n++ {
		for _, line := range lines {
			Parse(line)
		}
	}
}
<|endoftext|>


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

package context

import (
	"go/build"
	"os"
	"path/filepath"
	"runtime"
	"sync"
)

// A Context specifies the supporting context for a build and embedded
// build.Context type struct.
type Build struct {
	Tool string
	build.Context
}

// GoPath return the new GOPATH estimated from the path p directory structure.
func (ctxt *Build) buildContext(p string) (string, string) {
	tool := "go"

	// Get original $GOPATH path.
	goPath := os.Getenv("GOPATH")

	// Get runtime $GOROOT path and join to goPath.
	r := runtime.GOROOT()
	if r != "" {
		goPath = goPath + string(filepath.ListSeparator) + r
	}

	// Cleanup directory path.
	p = filepath.Clean(p)

	// Check the path p are Gb directory structure.
	// If yes, append gb root and vendor path to the goPath lists.
	if gbpath, yes := ctxt.isGb(p); yes {
		goPath = gbpath + string(filepath.ListSeparator) +
			filepath.Join(gbpath, "vendor") + string(filepath.ListSeparator) +
			goPath
		tool = "gb"
	}

	return goPath, tool
}

// isGb return the gb package root path if p is gb project directory structure.
func (ctxt *Build) isGb(p string) (string, bool) {
	ctxt.Context = build.Default

	var pkgRoot string
	for {
		pkg, err := ctxt.ImportDir(p, build.IgnoreVendor)
		if err != nil {
			return "", err != nil
			break
		}

		if pkg.Name == "main" {
			pkgRoot = pkg.Dir
			break
		}
		p = filepath.Dir(p)
		continue
	}

	// gb project directory is `../../pkgRoot`
	projRoot, src := filepath.Split(filepath.Dir(pkgRoot))

	manifest := filepath.Join(filepath.Clean(projRoot), "vendor/manifest")
	_, err := os.Stat(manifest)

	return filepath.Clean(projRoot), (err == nil && src == "src")
}

// contextMu Mutex lock for SetContext.
var contextMu sync.Mutex

// SetContext sets the go/build Default.GOPATH and $GOPATH to GoPath(p)
// under a mutex.
// The returned function restores Default.GOPATH to its original value and
// unlocks the mutex.
//
// This function intended to be used to the go/build Default.
func (c *Build) SetContext(p string) func() {
	contextMu.Lock()
	original := build.Default.GOPATH

	build.Default.GOPATH, c.Tool = c.buildContext(p)
	os.Setenv("GOPATH", build.Default.GOPATH)

	return func() {
		build.Default.GOPATH = original
		os.Setenv("GOPATH", build.Default.GOPATH)
		contextMu.Unlock()
	}
}
<commit_msg>Fix isGo break timing is pkg.Name == 'main' or rootDir == pkg.Dir<commit_after>// Copyright 2016 Koichi Shiraishi. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package context

import (
	"go/build"
	"os"
	"path/filepath"
	"runtime"
	"sync"
)

// A Context specifies the supporting context for a build and embedded
// build.Context type struct.
type Build struct {
	Tool string
	build.Context
}

// GoPath return the new GOPATH estimated from the path p directory structure.
func (ctxt *Build) buildContext(p string) (string, string) {
	tool := "go"

	// Get original $GOPATH path.
	goPath := os.Getenv("GOPATH")

	// Get runtime $GOROOT path and join to goPath.
	r := runtime.GOROOT()
	if r != "" {
		goPath = goPath + string(filepath.ListSeparator) + r
	}

	// Cleanup directory path.
	p = filepath.Clean(p)

	// Check the path p are Gb directory structure.
	// If yes, append gb root and vendor path to the goPath lists.
	if gbpath, yes := ctxt.isGb(p); yes {
		goPath = gbpath + string(filepath.ListSeparator) +
			filepath.Join(gbpath, "vendor") + string(filepath.ListSeparator) +
			goPath
		tool = "gb"
	}

	return goPath, tool
}

// isGb return the gb package root path if p is gb project directory structure.
func (ctxt *Build) isGb(p string) (string, bool) {
	ctxt.Context = build.Default

	var pkgRoot string
	for {
		pkg, _ := ctxt.ImportDir(p, build.IgnoreVendor)
		rootDir := FindVcsRoot(p)

		if pkg.Name == "main" || rootDir == pkg.Dir {
			pkgRoot = pkg.Dir
			break
		}
		p = filepath.Dir(p)
		continue
	}

	// gb project directory is `../../pkgRoot`
	projRoot, src := filepath.Split(filepath.Dir(pkgRoot))

	manifest := filepath.Join(filepath.Clean(projRoot), "vendor/manifest")
	_, err := os.Stat(manifest)

	return filepath.Clean(projRoot), (err == nil && src == "src")
}

// contextMu Mutex lock for SetContext.
var contextMu sync.Mutex

// SetContext sets the go/build Default.GOPATH and $GOPATH to GoPath(p)
// under a mutex.
// The returned function restores Default.GOPATH to its original value and
// unlocks the mutex.
//
// This function intended to be used to the go/build Default.
func (c *Build) SetContext(p string) func() {
	contextMu.Lock()
	original := build.Default.GOPATH

	build.Default.GOPATH, c.Tool = c.buildContext(p)
	os.Setenv("GOPATH", build.Default.GOPATH)

	return func() {
		build.Default.GOPATH = original
		os.Setenv("GOPATH", build.Default.GOPATH)
		contextMu.Unlock()
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	. "github.com/eaciit/hdc/hive"
	"time"
)

var h *Hive
var q string

type Sample7 struct {
	Code        string `tag_name:"code"`
	Description string `tag_name:"description"`
	Total_emp   int    `tag_name:"total_emp"`
	Salary      int    `tag_name:"salary"`
}

type SampleParse struct {
	Code        string    `tag_name:"code"`
	Description string    `tag_name:"description"`
	Total_emp   int       `tag_name:"total_emp"`
	Salary      int       `tag_name:"salary"`
	Date        time.Time `tag_name:"date"`
}

func main() {
	h = HiveConfig("192.168.0.223:10000", "default", "developer", "b1gD@T@", "")
	q = "select * from sample_07 limit 20;"

	//for now this function just provide  csv type
	TestParseOutput()

	//Exec Query and Process with DoSomething Function PerLine | EXECPERLINE only support for csv or tsv
	h.OutputType = "csv"
	TestExecPerLine()

	// Exec Query and wait until all line fetched | EXEC only support for csv or tsv
	h.OutputType = "tsv"
	TestExec()
}

func DoSomething(res string) {
	tmp := Sample7{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)
}

func TestExec() {
	res, e := h.Exec(q)

	if e != nil {
		fmt.Printf("error: \n%v\n", e)
	} else {
		fmt.Println(res)
	}
}

func TestExecPerLine() {
	e := h.ExecLine(q, DoSomething)

	if e != nil {
		fmt.Printf("error: \n%v\n", e)
	}
}

func TestParseOutput() {
	h.Header = []string{"code", "description", "total_emp", "salary", "Date"}

	h.OutputType = "csv"
	h.DateFormat = "YYYY-MM-DD"
	res := "'00-0000','All Occupations CSV','134354250','40690','2014-05-01'"
	tmp := SampleParse{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)

	h.OutputType = "tsv"
	h.DateFormat = "YYYY-MMM-DD"
	res = "00-0000\tAll Occupations TSV\t134354250\t40690\t2014-Dec-05"
	tmp = SampleParse{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)

	h.OutputType = "json"
	res = "{ \"code\" : \"00-0000\" , \"description\" : \"All Occupations JSON\", \"total_emp\" : 134354, \"salary\" : 40690,\"Date\" : \"2012-04-23T18:25:43Z\" }"
	tmp = SampleParse{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)
}
<commit_msg>detect data type parse out<commit_after>package main

import (
	"fmt"
	. "github.com/eaciit/hdc/hive"
	"time"
)

var h *Hive
var q string

type Sample7 struct {
	Code        string `tag_name:"code"`
	Description string `tag_name:"description"`
	Total_emp   int    `tag_name:"total_emp"`
	Salary      int    `tag_name:"salary"`
}

type SampleParse struct {
	Code        string    `tag_name:"code"`
	Description string    `tag_name:"description"`
	Total_emp   int       `tag_name:"total_emp"`
	Salary      int       `tag_name:"salary"`
	Date        time.Time `tag_name:"date"`
}

func main() {
	h = HiveConfig("192.168.0.223:10000", "default", "developer", "b1gD@T@", "")
	q = "select * from sample_07 limit 20;"

	//for now this function just provide  csv type
	TestParseOutput()

	//Exec Query and Process with DoSomething Function PerLine | EXECPERLINE only support for csv or tsv
	h.OutputType = "csv"
	TestExecPerLine()

	// Exec Query and wait until all line fetched | EXEC only support for csv or tsv
	h.OutputType = "tsv"
	TestExec()
}

func DoSomething(res string) {
	tmp := Sample7{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)
}

func TestExec() {
	res, e := h.Exec(q)

	if e != nil {
		fmt.Printf("error: \n%v\n", e)
	} else {
		fmt.Println(res)
	}
}

func TestExecPerLine() {
	e := h.ExecLine(q, DoSomething)

	if e != nil {
		fmt.Printf("error: \n%v\n", e)
	}
}

func TestParseOutput() {
	h.Header = []string{"code", "description", "total_emp", "salary", "Date"}

	h.OutputType = "csv"
	h.DateFormat = "YYYY-MM-DD"
	res := "'00-0000','All Occupations CSV','134354250','40690','2014-05-01'"
	tmp := SampleParse{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)

	h.OutputType = "tsv"
	h.DateFormat = "YYYY-MMM-DD"
	res = "00-0000\tAll Occupations TSV\t134354250\t40690\t2014-Dec-05"
	tmp = SampleParse{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)

	//try to parse json with different line
	h.OutputType = "json"
	res = "{ \"code\" : \"00-0000\" , \"description\" : \"All Occupations JSON\" "
	tmp = SampleParse{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)

	res = ", \"total_emp\" : 134354, \"salary\" : 40690,\"Date\" : \"2012-04-23T18:25:43Z\" }"
	tmp = SampleParse{}
	h.ParseOutput(res, &tmp)
	fmt.Println(tmp)
}
<|endoftext|>


<commit_before>package libaudit

import (
	"fmt"
	"strconv"
	"syscall"

	"github.com/pkg/errors"
)

// EventCallback is the function signature for any function that wants to receive an AuditEvent as soon as
// it is received from the kernel. Error channel will be used to indicate any error that happens while receiving
// messages.
type EventCallback func(*AuditEvent, chan error, ...interface{})

// RawEventCallback is similar to EventCallback and provides a function signature but the difference is that the function
// will receive only the message string which contains the audit event and not the parsed AuditEvent struct.
type RawEventCallback func(string, chan error, ...interface{})

// AuditEvent holds a parsed audit message.
// Serial holds the serial number for the message.
// Timestamp holds the unix timestamp of the message.
// Type indicates the type of the audit message.
// Data holds a map of field values of audit messages where keys => field names and values => field values.
// Raw string holds the original audit message received from kernel.
type AuditEvent struct {
	Serial    string
	Timestamp string
	Type      string
	Data      map[string]string
	Raw       string
}

//NewAuditEvent takes a NetlinkMessage passed from the netlink connection
//and parses the data from the message header to return an AuditEvent struct.
func NewAuditEvent(msg NetlinkMessage) (*AuditEvent, error) {
	x, err := ParseAuditEvent(string(msg.Data[:]), auditConstant(msg.Header.Type), true)
	if err != nil {
		return nil, err
	}
	if (*x).Type == "auditConstant("+strconv.Itoa(int(msg.Header.Type))+")" {
		return nil, fmt.Errorf("NewAuditEvent failed: unknown message type %d", msg.Header.Type)
	}

	return x, nil
}

// GetAuditEvents receives audit messages from the kernel and parses them to AuditEvent struct.
// It passes them along the callback function and the error channel is used to indicate any error that happens while
// receiving the message. Code that receives the message runs inside a go-routine.
// Please note that error channel is not a buffered one and client should provide a routine on their side that continously
// empties it, otherwise the call will be blocked for eg at : ec <- fmt.Errorf("error receiving events -%d", err)
// and the message recpetion will be blocked
func GetAuditEvents(s *NetlinkConnection, cb EventCallback, ec chan error, args ...interface{}) {
	go func() {
		for {
			select {
			default:
				msgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)
				for _, msg := range msgs {
					if msg.Header.Type == syscall.NLMSG_ERROR {
						err := int32(nativeEndian().Uint32(msg.Data[0:4]))
						if err != 0 {
							ec <- fmt.Errorf("error receiving events -%d", err)
						}
					} else {
						nae, err := NewAuditEvent(msg)
						if err != nil {
							ec <- err
						}
						cb(nae, ec, args...)
					}
				}
			}
		}
	}()
}

// GetRawAuditEvents receives raw audit messages from kernel parses them to AuditEvent struct.
// It passes them along the raw callback function and error channel is to indicate any error that happens while
// receiving the message. Code that receives the message runs inside a go-routine.
// Please note that error channel is not a buffered one and client should provide a routine on their side that continously
// empties it, otherwise the call will be blocked for eg at : ec <- fmt.Errorf("error receiving events -%d", err)
// and the message recpetion will be blocked
func GetRawAuditEvents(s *NetlinkConnection, cb RawEventCallback, ec chan error, args ...interface{}) {
	go func() {
		for {
			select {
			default:
				msgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)
				for _, msg := range msgs {
					m := ""
					if msg.Header.Type == syscall.NLMSG_ERROR {
						err := int32(nativeEndian().Uint32(msg.Data[0:4]))
						if err != 0 {
							ec <- fmt.Errorf("error receiving events -%d", err)
						}
					} else {
						Type := auditConstant(msg.Header.Type)
						if Type.String() == "auditConstant("+strconv.Itoa(int(msg.Header.Type))+")" {
							ec <- errors.New("Unknown Type: " + string(msg.Header.Type))
						} else {
							m = "type=" + Type.String()[6:] + " msg=" + string(msg.Data[:]) + "\n"
						}
					}
					cb(m, ec, args...)
				}
			}
		}
	}()
}

// GetAuditMessages is a blocking function (runs in forever for loop) that
// receives audit messages from kernel and parses them to AuditEvent.
// It passes them along the callback cb and the error channel is used to indicate any error
// that happens while receiving the message.
// It will return when a signal is received on the done channel.
// Please note that error channel is not a buffered one and client should provide a routine on their side that continously
// empties it, otherwise the call will be blocked for eg. at : ec <- fmt.Errorf("error receiving events -%d", err)
// and the message recpetion will be blocked
func GetAuditMessages(s *NetlinkConnection, cb EventCallback, ec *chan error, done *chan bool, args ...interface{}) {
	for {
		select {
		case <-*done:
			return
		default:
			msgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)
			for _, msg := range msgs {
				if msg.Header.Type == syscall.NLMSG_ERROR {
					err := int32(nativeEndian().Uint32(msg.Data[0:4]))
					if err != 0 {
						*ec <- fmt.Errorf("error receiving events -%d", err)
					}
				} else {
					nae, err := NewAuditEvent(msg)
					if err != nil {
						*ec <- err
					}
					cb(nae, *ec, args...)
				}
			}
		}
	}

}
<commit_msg>Change GetAuditEvent API to avoid passing errors through channels Pass directly to the callbacks instead<commit_after>package libaudit

import (
	"fmt"
	"strconv"
	"syscall"

	"github.com/pkg/errors"
)

// EventCallback is the function signature for any function that wants to receive an AuditEvent as soon as
// it is received from the kernel. Error will be set to indicate any error that happens while receiving
// messages.
type EventCallback func(*AuditEvent, error, ...interface{})

// RawEventCallback is similar to EventCallback and provides a function signature but the difference is that the function
// will receive only the message string which contains the audit event and not the parsed AuditEvent struct.
type RawEventCallback func(string, error, ...interface{})

// AuditEvent holds a parsed audit message.
// Serial holds the serial number for the message.
// Timestamp holds the unix timestamp of the message.
// Type indicates the type of the audit message.
// Data holds a map of field values of audit messages where keys => field names and values => field values.
// Raw string holds the original audit message received from kernel.
type AuditEvent struct {
	Serial    string
	Timestamp string
	Type      string
	Data      map[string]string
	Raw       string
}

//NewAuditEvent takes a NetlinkMessage passed from the netlink connection
//and parses the data from the message header to return an AuditEvent struct.
func NewAuditEvent(msg NetlinkMessage) (*AuditEvent, error) {
	x, err := ParseAuditEvent(string(msg.Data[:]), auditConstant(msg.Header.Type), true)
	if err != nil {
		return nil, err
	}
	if (*x).Type == "auditConstant("+strconv.Itoa(int(msg.Header.Type))+")" {
		return nil, fmt.Errorf("NewAuditEvent failed: unknown message type %d", msg.Header.Type)
	}

	return x, nil
}

// GetAuditEvents receives audit messages from the kernel and parses them to AuditEvent struct.
// It passes them along the callback function and if any error occurs while receiving the message,
// the same will be passed in the callback as well.
// Code that receives the message runs inside a go-routine.
func GetAuditEvents(s Netlink, cb EventCallback, args ...interface{}) {
	go func() {
		for {
			select {
			default:
				msgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)
				for _, msg := range msgs {
					if msg.Header.Type == syscall.NLMSG_ERROR {
						err := int32(nativeEndian().Uint32(msg.Data[0:4]))
						if err != 0 {
							cb(nil, fmt.Errorf("error receiving events %d", err), args...)
						}
					} else {
						nae, err := NewAuditEvent(msg)
						cb(nae, err, args...)
					}
				}
			}
		}
	}()
}

// GetRawAuditEvents receives raw audit messages from kernel parses them to AuditEvent struct.
// It passes them along the callback function and if any error occurs while receiving the message,
// the same will be passed in the callback as well.
// Code that receives the message runs inside a go-routine.
func GetRawAuditEvents(s Netlink, cb RawEventCallback, args ...interface{}) {
	go func() {
		for {
			select {
			default:
				msgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)
				for _, msg := range msgs {
					var (
						m   string
						err error
					)
					if msg.Header.Type == syscall.NLMSG_ERROR {
						v := int32(nativeEndian().Uint32(msg.Data[0:4]))
						if v != 0 {
							cb(m, fmt.Errorf("error receiving events %d", v), args...)
						}
					} else {
						Type := auditConstant(msg.Header.Type)
						if Type.String() == "auditConstant("+strconv.Itoa(int(msg.Header.Type))+")" {
							err = errors.New("Unknown Type: " + string(msg.Header.Type))
						} else {
							m = "type=" + Type.String()[6:] + " msg=" + string(msg.Data[:]) + "\n"
						}
					}
					cb(m, err, args...)
				}
			}
		}
	}()
}

// GetAuditMessages is a blocking function (runs in forever for loop) that
// receives audit messages from kernel and parses them to AuditEvent.
// It passes them along the callback function and if any error occurs while receiving the message,
// the same will be passed in the callback as well.
// It will return when a signal is received on the done channel.
func GetAuditMessages(s Netlink, cb EventCallback, done *chan bool, args ...interface{}) {
	for {
		select {
		case <-*done:
			return
		default:
			msgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)
			for _, msg := range msgs {
				if msg.Header.Type == syscall.NLMSG_ERROR {
					v := int32(nativeEndian().Uint32(msg.Data[0:4]))
					if v != 0 {
						cb(nil, fmt.Errorf("error receiving events %d", v), args...)
					}
				} else {
					nae, err := NewAuditEvent(msg)
					cb(nae, err, args...)
				}
			}
		}
	}

}
<|endoftext|>


<commit_before>package bothandlers

import (
	"fmt"
	"github.com/djosephsen/hal"
	"time"
	"strings"
)

var ListChores = &hal.Handler{
	Method:  hal.RESPOND,
	Pattern: `(list chores)|(chore list)`,
	Run: func(res *hal.Response) error {
		var reply string
		if len(res.Robot.Chores) == 0{
			reply=`No chores have been registered (sorry?)`
		}else{
			reply=`Name  :small_blue_diamond:  Schedule  :small_blue_diamond:  Firing in  :small_blue_diamond: Current State`
			for _,c := range res.Robot.Chores{
				reply = fmt.Sprintf("%s\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)
			}
		}
		return res.Reply(reply)
	},
}

var ListRooms = &hal.Handler{
	Method:  hal.RESPOND,
	Pattern: `(what room)|(list *room)|(room *list)`,
	Run: func(res *hal.Response) error {
		room := res.Message.Room
		reply := fmt.Sprintf("Current room is: %s",room)
		return res.Send(reply)
	},
}

var StopChore = &hal.Handler{
	Method:  hal.RESPOND,
	Pattern: `(stop chore)|(chore stop)`,
	Run: func(res *hal.Response) error {
		var reply string
		cname:=strings.SplitAfterN(res.Match[0],` `,3)
		c:=hal.GetChoreByName(cname[2],res.Robot)
		hal.KillChore(c)
		reply = fmt.Sprintf("%s\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)
		return res.Reply(reply)
	},
}
<commit_msg>adding a chore kill command<commit_after>package bothandlers

import (
	"fmt"
	"github.com/djosephsen/hal"
	"time"
	"strings"
)

var ListRooms = &hal.Handler{
	Method:  hal.RESPOND,
	Pattern: `(what room)|(list *room)|(room *list)`,
	Run: func(res *hal.Response) error {
		room := res.Message.Room
		reply := fmt.Sprintf("Current room is: %s",room)
		return res.Send(reply)
	},
}

var ListChores = &hal.Handler{
	Method:  hal.RESPOND,
	Pattern: `(list chores)|(chore list)`,
	Run: func(res *hal.Response) error {
		var reply string
		if len(res.Robot.Chores) == 0{
			reply=`No chores have been registered (sorry?)`
		}else{
			reply=`Name  :small_blue_diamond:  Schedule  :small_blue_diamond:  Firing in  :small_blue_diamond: Current State`
			for _,c := range res.Robot.Chores{
				reply = fmt.Sprintf("%s\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)
			}
		}
		return res.Reply(reply)
	},
}

var StopChore = &hal.Handler{
	Method:  hal.RESPOND,
	Pattern: `(stop chore)|(chore stop)`,
	Run: func(res *hal.Response) error {
		var reply string
		cname:=strings.SplitAfterN(res.Match[0],` `,3)
		c:=hal.GetChoreByName(cname[2],res.Robot)
		hal.KillChore(c)
		reply = fmt.Sprintf("%s\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)
		return res.Reply(reply)
	},
}
<|endoftext|>


<commit_before>package headlessChrome

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/integrii/interactive"
)

// Debug enables debug output for this package to console
var Debug bool

// BrowserStartupTime is how long chrome has to startup the console
// before we consider it a failure
var BrowserStartupTime = time.Second * 20

// ChromePath is the command to execute chrome
var ChromePath = ChromePathMacOS
var ChromePathMacOS = `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`
var ChromePathDocker = `/opt/google/chrome-unstable/chrome`

// Args are the args that will be used to start chrome
var Args = []string{
	"--headless",
	"--disable-gpu",
	"--repl",
	// "--dump-dom",
	// "--window-size=1024,768",
	// "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
	// "--verbose",
}

const expectedFirstLine = `Type a Javascript expression to evaluate or "quit" to exit.`
const promptPrefix = `>>>`

// outputSanitizer puts output coming from the consolw that
// does not begin with the input prompt into the session
// output channel
func (cs *ChromeSession) outputSanitizer() {
	for text := range cs.Session.Output {
		debug("raw output:", text)
		if !strings.HasPrefix(text, promptPrefix) {
			cs.Output <- text
		}
	}
}

// ChromeSession is an interactive console Session with a Chrome
// instance.
type ChromeSession struct {
	Session *interactive.Session
	Output  chan string
	Input   chan string
}

// Exit exits the running command out by ossuing a 'quit'
// to the chrome console
func (cs *ChromeSession) Exit() {
	cs.Session.Write(`;quit`)
	cs.Session.Exit()
}

// Write writes to the Session
func (cs *ChromeSession) Write(s string) {
	debug("write:", s)
	cs.Session.Write(s)
}

// outputPrinter prints all outputs from the output channel to the cli
func (cs *ChromeSession) outputPrinter() {
	for l := range cs.Session.Output {
		debug("read:", l)
		fmt.Println(l)
	}
}

// ForceClose issues a force kill to the command
func (cs *ChromeSession) ForceClose() {
	cs.Session.ForceClose()
}

// ClickSelector calls a click() on the supplied selector
func (cs *ChromeSession) ClickSelector(s string) {
	cs.Write(`document.querySelector("` + s + `").click()`)
}

// ClickItemWithInnerHTML clicks an item that has the matching inner html
func (cs *ChromeSession) ClickItemWithInnerHTML(elementType string, s string, itemIndex int) {
	cs.Write(`var x = $("` + elementType + `").filter(function(idx) { return this.innerHTML == "` + s + `"});x[` + strconv.Itoa(itemIndex) + `].click()`)
}

// GetItemWithInnerHTML fetches the item with the specified innerHTML content
func (cs *ChromeSession) GetItemWithInnerHTML(elementType string, s string, itemIndex int) {
	cs.Write(`var x = $("` + elementType + `").filter(function(idx) { return this.innerHTML == "` + s + `"});x[` + strconv.Itoa(itemIndex) + `]`)
}

// GetContentOfItemWithClasses fetches the content of the element with the specified classes
func (cs *ChromeSession) GetContentOfItemWithClasses(classes string, itemIndex int) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].innerHTML`)
}

// GetValueOfItemWithClasses returns the form value of the specified item
func (cs *ChromeSession) GetValueOfItemWithClasses(classes string, itemIndex int) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].value`)
}

// GetContentOfItemWithSelector gets the content of an element with the specified selector
func (cs *ChromeSession) GetContentOfItemWithSelector(selector string) {
	cs.Write(`document.querySelector("` + selector + `").innerHTML()`)
}

// ClickItemWithClasses clicks on the first item it finds with the provided classes.
// Multiple classes are separated by spaces
func (cs *ChromeSession) ClickItemWithClasses(classes string, itemIndex int) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].click()`)
}

// SetTextByID sets the text on the div with the specified id
func (cs *ChromeSession) SetTextByID(id string, text string) {
	cs.Write(`document.getElementById("` + id + `").innerHTML = "` + text + `"`)
}

// ClickItemWithID clicks an item with the specified id
func (cs *ChromeSession) ClickItemWithID(id string) {
	cs.Write(`document.getElementById("` + id + `").click()`)
}

// SetTextByClasses sets the text on the div with the specified id
func (cs *ChromeSession) SetTextByClasses(classes string, itemIndex int, text string) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].innerHTML = "` + text + `"`)
}

// SetInputTextByClasses sets the input text for an input field
func (cs *ChromeSession) SetInputTextByClasses(classes string, itemIndex int, text string) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].value = "` + text + `"`)
}

// NewBrowserWithTimeout starts a new chrome headless session
// but limits how long it can run before its killed forcefully.
// A time limit of 0 means there is not a time limit
func NewBrowserWithTimeout(url string, timeout time.Duration) (*ChromeSession, error) {
	var err error

	debug("Creating a new browser pointed to", url)

	chromeSession := ChromeSession{}
	chromeSession.Output = make(chan string, 5000)

	// add url as last arg and create new Session
	args := append(Args, url)
	debug(ChromePath, args)
	chromeSession.Session, err = interactive.NewSessionWithTimeout(ChromePath, args, timeout)
	if err != nil {
		return &chromeSession, err
	}

	// map output and input channels for easy use
	chromeSession.Input = chromeSession.Session.Input
	go chromeSession.outputSanitizer()

	// wait for the console ready line from the browser
	// and if it does not start in time, throw an error
	startupTime := time.NewTimer(BrowserStartupTime)
	for {
		select {
		case <-startupTime.C:
			debug("ERROR: Browser failed to start before browser startup time cutoff")
			chromeSession.ForceClose() // force cloe the session because it failed
			err = errors.New("Chrome console failed to init in the alotted time")
			return &chromeSession, err
		case line := <-chromeSession.Output:
			if strings.Contains(line, expectedFirstLine) {
				debug("Chrome console REPL ready")
				return &chromeSession, err
			}
			debug("WARNING: Unespected first line when initializing headless Chrome console:", line)
		}
	}
}

// NewBrowser starts a new chrome headless Session.
func NewBrowser(url string) (*ChromeSession, error) {
	return NewBrowserWithTimeout(url, 0)
}

func debug(s ...interface{}) {
	if Debug {
		fmt.Println(s...)
	}
}
<commit_msg>graceful shutdown when calling exit<commit_after>package headlessChrome

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/integrii/interactive"
)

// Debug enables debug output for this package to console
var Debug bool

// BrowserStartupTime is how long chrome has to startup the console
// before we consider it a failure
var BrowserStartupTime = time.Second * 20

// ChromePath is the command to execute chrome
var ChromePath = ChromePathMacOS

// ChromePathMacOS is where chrome normally lives on MacOS
var ChromePathMacOS = `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`

// ChromePathDocker is where chrome normally lives in the project's docker container
var ChromePathDocker = `/opt/google/chrome-unstable/chrome`

// Args are the args that will be used to start chrome
var Args = []string{
	"--headless",
	"--disable-gpu",
	"--repl",
	// "--dump-dom",
	// "--window-size=1024,768",
	// "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
	// "--verbose",
}

const expectedFirstLine = `Type a Javascript expression to evaluate or "quit" to exit.`
const promptPrefix = `>>>`

// outputSanitizer puts output coming from the consolw that
// does not begin with the input prompt into the session
// output channel
func (cs *ChromeSession) outputSanitizer() {
	for text := range cs.Session.Output {
		debug("raw output:", text)
		if !strings.HasPrefix(text, promptPrefix) {
			cs.Output <- text
		}
	}
}

// ChromeSession is an interactive console Session with a Chrome
// instance.
type ChromeSession struct {
	Session *interactive.Session
	Output  chan string
	Input   chan string
}

// Exit exits the running command out by ossuing a 'quit'
// to the chrome console
func (cs *ChromeSession) Exit() {
	cs.Session.Write(`;quit`)
	cs.Session.Exit()  // exit the process with an interrupt signal
	cs.Session.Close() // close the tty session
}

// Write writes to the Session
func (cs *ChromeSession) Write(s string) {
	debug("write:", s)
	cs.Session.Write(s)
}

// outputPrinter prints all outputs from the output channel to the cli
func (cs *ChromeSession) outputPrinter() {
	for l := range cs.Session.Output {
		debug("read:", l)
		fmt.Println(l)
	}
}

// ForceClose issues a force kill to the command
func (cs *ChromeSession) ForceClose() {
	cs.Session.ForceClose()
}

// ClickSelector calls a click() on the supplied selector
func (cs *ChromeSession) ClickSelector(s string) {
	cs.Write(`document.querySelector("` + s + `").click()`)
}

// ClickItemWithInnerHTML clicks an item that has the matching inner html
func (cs *ChromeSession) ClickItemWithInnerHTML(elementType string, s string, itemIndex int) {
	cs.Write(`var x = $("` + elementType + `").filter(function(idx) { return this.innerHTML == "` + s + `"});x[` + strconv.Itoa(itemIndex) + `].click()`)
}

// GetItemWithInnerHTML fetches the item with the specified innerHTML content
func (cs *ChromeSession) GetItemWithInnerHTML(elementType string, s string, itemIndex int) {
	cs.Write(`var x = $("` + elementType + `").filter(function(idx) { return this.innerHTML == "` + s + `"});x[` + strconv.Itoa(itemIndex) + `]`)
}

// GetContentOfItemWithClasses fetches the content of the element with the specified classes
func (cs *ChromeSession) GetContentOfItemWithClasses(classes string, itemIndex int) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].innerHTML`)
}

// GetValueOfItemWithClasses returns the form value of the specified item
func (cs *ChromeSession) GetValueOfItemWithClasses(classes string, itemIndex int) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].value`)
}

// GetContentOfItemWithSelector gets the content of an element with the specified selector
func (cs *ChromeSession) GetContentOfItemWithSelector(selector string) {
	cs.Write(`document.querySelector("` + selector + `").innerHTML()`)
}

// ClickItemWithClasses clicks on the first item it finds with the provided classes.
// Multiple classes are separated by spaces
func (cs *ChromeSession) ClickItemWithClasses(classes string, itemIndex int) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].click()`)
}

// SetTextByID sets the text on the div with the specified id
func (cs *ChromeSession) SetTextByID(id string, text string) {
	cs.Write(`document.getElementById("` + id + `").innerHTML = "` + text + `"`)
}

// ClickItemWithID clicks an item with the specified id
func (cs *ChromeSession) ClickItemWithID(id string) {
	cs.Write(`document.getElementById("` + id + `").click()`)
}

// SetTextByClasses sets the text on the div with the specified id
func (cs *ChromeSession) SetTextByClasses(classes string, itemIndex int, text string) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].innerHTML = "` + text + `"`)
}

// SetInputTextByClasses sets the input text for an input field
func (cs *ChromeSession) SetInputTextByClasses(classes string, itemIndex int, text string) {
	cs.Write(`document.getElementsByClassName("` + classes + `")[` + strconv.Itoa(itemIndex) + `].value = "` + text + `"`)
}

// NewBrowserWithTimeout starts a new chrome headless session
// but limits how long it can run before its killed forcefully.
// A time limit of 0 means there is not a time limit
func NewBrowserWithTimeout(url string, timeout time.Duration) (*ChromeSession, error) {
	var err error

	debug("Creating a new browser pointed to", url)

	chromeSession := ChromeSession{}
	chromeSession.Output = make(chan string, 5000)

	// add url as last arg and create new Session
	args := append(Args, url)
	debug(ChromePath, args)
	chromeSession.Session, err = interactive.NewSessionWithTimeout(ChromePath, args, timeout)
	if err != nil {
		return &chromeSession, err
	}

	// map output and input channels for easy use
	chromeSession.Input = chromeSession.Session.Input
	go chromeSession.outputSanitizer()

	// wait for the console ready line from the browser
	// and if it does not start in time, throw an error
	startupTime := time.NewTimer(BrowserStartupTime)
	for {
		select {
		case <-startupTime.C:
			debug("ERROR: Browser failed to start before browser startup time cutoff")
			chromeSession.ForceClose() // force cloe the session because it failed
			err = errors.New("Chrome console failed to init in the alotted time")
			return &chromeSession, err
		case line := <-chromeSession.Output:
			if strings.Contains(line, expectedFirstLine) {
				debug("Chrome console REPL ready")
				return &chromeSession, err
			}
			debug("WARNING: Unespected first line when initializing headless Chrome console:", line)
		}
	}
}

// NewBrowser starts a new chrome headless Session.
func NewBrowser(url string) (*ChromeSession, error) {
	return NewBrowserWithTimeout(url, 0)
}

func debug(s ...interface{}) {
	if Debug {
		fmt.Println(s...)
	}
}
<|endoftext|>


<commit_before>package AuthorizeCIM

import (
	"net/http"
	"bytes"
	"io/ioutil"
	"encoding/json"
	"fmt"
	"time"
)

var api_endpoint string
var apiName string
var apiKey string
var testMode string

var CurrentUser User

func SetAPIInfo(name string, key string, mode string) {
	apiKey = key
	apiName = name
	if mode == "test" {
		testMode = "testMode"
		api_endpoint = "https://apitest.authorize.net/xml/v1/request.api"
	} else {
		testMode = "liveMode"
		api_endpoint = "https://api.authorize.net/xml/v1/request.api"
	}
}

func MakeUser (userID string) User {
	CurrentUser = User{ID: "55", Email: userID, ProfileID: "0"}
	return CurrentUser
}

func CreateCustomerProfile(userInfo AuthUser) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := Profile{MerchantCustomerID: userInfo.Uuid, Description: userInfo.Description, Email: userInfo.Email}
	request := CreateCustomerProfileRequest{authToken, profile}
	newprofile := NewCustomerProfile{request}
	jsoned, _ := json.Marshal(newprofile)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	var new_uuid string
	if success {
		new_uuid = outgoing["customerProfileId"].(string)
		CurrentUser.ProfileID = new_uuid
	} else {
		new_uuid = "0"
	}
	// Delay for Authorize.net
	time.Sleep(3 * time.Second)
	return new_uuid, success
}

func GetCustomerProfile(profileID string) (map[string]interface{}, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := getCustomerProfileRequest{authToken, profileID}
	input := CustomerProfile{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ :=SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	fmt.Println(outgoing)
	userProfile := outgoing["profile"].(map[string]interface{})
	fmt.Println(userProfile)
	return outgoing, success
}

func GetAllProfiles() []interface{} {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profilerequest := getCustomerProfileIdsRequest{authToken}
	all := AllCustomerProfileIds{profilerequest}
	jsoned, _ := json.Marshal(all)
	outgoing, _ :=SendRequest(string(jsoned))
	return outgoing["ids"].([]interface{})
}

func DeleteCustomerProfile(profileID string) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := deleteCustomerProfileRequest{authToken, profileID}
	input := deleteCustomerProfile{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func CreateCustomerBillingProfile(profileID string, creditCard CreditCard, address Address) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	paymentProfile := PaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}}
	request := CreateCustomerBillingProfileRequest{authToken, profileID, paymentProfile, testMode}
	newprofile := NewCustomerBillingProfile{request}
	jsoned, _ := json.Marshal(newprofile)
	outgoing, _ :=SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	var new_paymentID string
	if status {
		new_paymentID = outgoing["customerPaymentProfileId"].(string)
	} else {
		new_paymentID = "0"
	}
	// Delay for Authorize.net
	time.Sleep(3 * time.Second)
	return new_paymentID, status
}

func GetCustomerPaymentProfile(profileID string, paymentID string) (map[string]interface{}, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := CustomerPaymentProfileRequest{authToken, profileID, paymentID}
	input := getCustomerPaymentProfileRequest{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	fmt.Println(CurrentUser)
	return outgoing["paymentProfile"].(map[string]interface{}), success
}

func UpdateCustomerPaymentProfile(profileID string, paymentID string, creditCard CreditCard, address Address) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	new_billing := UpdatePaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}, CustomerPaymentProfileId: paymentID}
	profile := updateCustomerPaymentProfileRequest{authToken, profileID, new_billing, testMode}
	input := changeCustomerPaymentProfileRequest{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func DeleteCustomerPaymentProfile(profileID string, paymentID string) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := deleteCustomerPaymentProfile{authToken, profileID, paymentID}
	input := deleteCustomerPaymentProfileRequest{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ :=SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func SendRequest(input string) (map[string]interface{}, interface{}) {
	req, err := http.NewRequest("POST", api_endpoint, bytes.NewBuffer([]byte(input)))
	req.Header.Set("Content-Type", "application/json")
	errors := false
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	body = bytes.TrimPrefix(body, []byte("\xef\xbb\xbf"))
	var dat map[string]interface{}
	//fmt.Printf(string(body))
	err = json.Unmarshal(body, &dat)
	if err!=nil {
		panic(err)
	}
	return dat, errors
}

func CreateTransaction(profileID string, paymentID string, item LineItem, amount string) (map[string]interface{}, bool, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	items := LineItems{LineItem: item}
	subProfile := SubProfile{CustomerPaymentProfileId: paymentID}
	transProfile := TranProfile{CustomerProfileId: profileID, SubProfile: subProfile}
	transaction := TransactionRequest{TransactionType: "authCaptureTransaction", Amount: amount, TranProfile: transProfile, LineItems: items}
	tranxrequest := CreateTransactionRequest{MerchantAuthentication: authToken, RefID: "none33", TransactionRequest: transaction}
	doTranx := DoCreateTransaction{tranxrequest}
	jsoned, _ := json.Marshal(doTranx)
	outgoing, _ := SendRequest(string(jsoned))
	var status, approved bool
	var response map[string]interface{}
	transxResponse := outgoing["transactionResponse"].(map[string]interface{})
	if transxResponse["responseCode"]!=nil {
		if transxResponse["responseCode"].(string) != "1" {
			approved = false
			status = true
			response = transxResponse
		} else {
			status = FindResultCode(outgoing)
			approved = TransactionApproved(outgoing)
			response = outgoing["transactionResponse"].(map[string]interface{})
		}
	} else {
		approved = false
		status = false
		response = map[string]interface{}{}
	}

	return response, approved, status
}

func TestConnection() bool {
	authToken := AuthenticateTestRequest{MerchantAuthentication{Name: apiName, TransactionKey: apiKey}}
	authnettest := AuthorizeNetTest{AuthenticateTestRequest:authToken}
	jsoned, _ := json.Marshal(authnettest)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func CreateShippingAddress(profileID string, address Address) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	customerShipping := CustomerShippingAddress{authToken,profileID,address}
	customerShippingRequest := CustomerShippingAddressRequest{customerShipping}
	jsoned, _ := json.Marshal(customerShippingRequest)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	var new_address_id string
	if !success {
		new_address_id = "0"
	} else {
		new_address_id = outgoing["customerAddressId"].(string)
	}
	// Delay for Authorize.net
	time.Sleep(3 * time.Second)
	return new_address_id, success
}

func GetShippingAddress(profileID string, shippingID string) (map[string]interface{}, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	customerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}
	customerShippingRequest := GetCustomerShippingAddressRequest{customerShipping}
	jsoned, _ := json.Marshal(customerShippingRequest)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	return outgoing["address"].(map[string]interface{}), success
}

func DeleteShippingAddress(profileID string, shippingID string) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	customerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}
	customerShippingRequest := DeleteCustomerShippingAddressRequest{customerShipping}
	jsoned, _ := json.Marshal(customerShippingRequest)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func GetTransactionDetails(tranID string) map[string]interface{} {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	transDetails := TransactionDetails{authToken,tranID}
	transactionRequest := TransactionDetailsRequest{transDetails}
	jsoned, _ := json.Marshal(transactionRequest)
	outgoing, _ := SendRequest(string(jsoned))
	if outgoing["transaction"]!=nil {
		return outgoing["transaction"].(map[string]interface{})
	}
	return map[string]interface{}{}
}

func FindResultCode(incoming map[string]interface{}) bool {
	messages, _ := incoming["messages"].(map[string]interface{})
	if messages!=nil {
		if messages["resultCode"] == "Ok" {
			return true
		}
	}
	return false
}

func TransactionApproved(incoming map[string]interface{}) bool {
	if incoming!=nil {
		messages, _ := incoming["transactionResponse"].(map[string]interface{})
		if messages["responseCode"] == "1" {
			return true
		}
	}
	return false
}

func CreateSubscription(newSubscription Subscription) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	subscriptonSubmit := CreateSubscriptionRequest{ARBCreateSubscription{authToken, newSubscription}}
	jsoned, _ := json.Marshal(subscriptonSubmit)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	if status {
		return outgoing["subscriptionId"].(string), status
	}
	return "0", status
}

func RefundTransactions(){

}

func VoidTransaction(){

}

func DeleteSubscription(){

}

func UpdateSubscription(){

}

func GetSubscriptions(){

}

<commit_msg>rebuild on travis<commit_after>package AuthorizeCIM

import (
	"net/http"
	"bytes"
	"io/ioutil"
	"encoding/json"
	"fmt"
	"time"
)

var api_endpoint string
var apiName string
var apiKey string
var testMode string

var CurrentUser User

func SetAPIInfo(name string, key string, mode string) {
	apiKey = key
	apiName = name
	if mode == "test" {
		testMode = "testMode"
		api_endpoint = "https://apitest.authorize.net/xml/v1/request.api"
	} else {
		testMode = "liveMode"
		api_endpoint = "https://api.authorize.net/xml/v1/request.api"
	}
}

func MakeUser (userID string) User {
	CurrentUser = User{ID: "55", Email: userID, ProfileID: "0"}
	return CurrentUser
}

func CreateCustomerProfile(userInfo AuthUser) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := Profile{MerchantCustomerID: userInfo.Uuid, Description: userInfo.Description, Email: userInfo.Email}
	request := CreateCustomerProfileRequest{authToken, profile}
	newprofile := NewCustomerProfile{request}
	jsoned, _ := json.Marshal(newprofile)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	var new_uuid string
	if success {
		new_uuid = outgoing["customerProfileId"].(string)
		CurrentUser.ProfileID = new_uuid
	} else {
		new_uuid = "0"
	}
	// Delay for Authorize.net
	time.Sleep(3 * time.Second)
	return new_uuid, success
}

func GetCustomerProfile(profileID string) (map[string]interface{}, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := getCustomerProfileRequest{authToken, profileID}
	input := CustomerProfile{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ :=SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	fmt.Println(outgoing)
	userProfile := outgoing["profile"].(map[string]interface{})
	fmt.Println(userProfile)
	return outgoing, success
}

func GetAllProfiles() []interface{} {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profilerequest := getCustomerProfileIdsRequest{authToken}
	all := AllCustomerProfileIds{profilerequest}
	jsoned, _ := json.Marshal(all)
	outgoing, _ :=SendRequest(string(jsoned))
	return outgoing["ids"].([]interface{})
}

func DeleteCustomerProfile(profileID string) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := deleteCustomerProfileRequest{authToken, profileID}
	input := deleteCustomerProfile{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func CreateCustomerBillingProfile(profileID string, creditCard CreditCard, address Address) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	paymentProfile := PaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}}
	request := CreateCustomerBillingProfileRequest{authToken, profileID, paymentProfile, testMode}
	newprofile := NewCustomerBillingProfile{request}
	jsoned, _ := json.Marshal(newprofile)
	outgoing, _ :=SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	var new_paymentID string
	if status {
		new_paymentID = outgoing["customerPaymentProfileId"].(string)
	} else {
		new_paymentID = "0"
	}
	// Delay for Authorize.net
	time.Sleep(3 * time.Second)
	return new_paymentID, status
}

func GetCustomerPaymentProfile(profileID string, paymentID string) (map[string]interface{}, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := CustomerPaymentProfileRequest{authToken, profileID, paymentID}
	input := getCustomerPaymentProfileRequest{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	fmt.Println(CurrentUser)
	return outgoing["paymentProfile"].(map[string]interface{}), success
}

func UpdateCustomerPaymentProfile(profileID string, paymentID string, creditCard CreditCard, address Address) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	new_billing := UpdatePaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}, CustomerPaymentProfileId: paymentID}
	profile := updateCustomerPaymentProfileRequest{authToken, profileID, new_billing, testMode}
	input := changeCustomerPaymentProfileRequest{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func DeleteCustomerPaymentProfile(profileID string, paymentID string) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	profile := deleteCustomerPaymentProfile{authToken, profileID, paymentID}
	input := deleteCustomerPaymentProfileRequest{profile}
	jsoned, _ := json.Marshal(input)
	outgoing, _ :=SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func SendRequest(input string) (map[string]interface{}, interface{}) {
	req, err := http.NewRequest("POST", api_endpoint, bytes.NewBuffer([]byte(input)))
	req.Header.Set("Content-Type", "application/json")
	errors := false
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	body = bytes.TrimPrefix(body, []byte("\xef\xbb\xbf"))
	var dat map[string]interface{}
	//fmt.Printf(string(body))
	err = json.Unmarshal(body, &dat)
	if err!=nil {
		panic(err)
	}
	return dat, errors
}

func CreateTransaction(profileID string, paymentID string, item LineItem, amount string) (map[string]interface{}, bool, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	items := LineItems{LineItem: item}
	subProfile := SubProfile{CustomerPaymentProfileId: paymentID}
	transProfile := TranProfile{CustomerProfileId: profileID, SubProfile: subProfile}
	transaction := TransactionRequest{TransactionType: "authCaptureTransaction", Amount: amount, TranProfile: transProfile, LineItems: items}
	tranxrequest := CreateTransactionRequest{MerchantAuthentication: authToken, RefID: "none33", TransactionRequest: transaction}
	doTranx := DoCreateTransaction{tranxrequest}
	jsoned, _ := json.Marshal(doTranx)
	outgoing, _ := SendRequest(string(jsoned))
	var status, approved bool
	var response map[string]interface{}
	transxResponse := outgoing["transactionResponse"].(map[string]interface{})
	if transxResponse["responseCode"]!=nil {
		if transxResponse["responseCode"].(string) != "1" {
			approved = false
			status = true
			response = transxResponse
		} else {
			status = FindResultCode(outgoing)
			approved = TransactionApproved(outgoing)
			response = outgoing["transactionResponse"].(map[string]interface{})
		}
	} else {
		approved = false
		status = false
		response = map[string]interface{}{}
	}

	return response, approved, status
}

func TestConnection() bool {
	authToken := AuthenticateTestRequest{MerchantAuthentication{Name: apiName, TransactionKey: apiKey}}
	authnettest := AuthorizeNetTest{AuthenticateTestRequest:authToken}
	jsoned, _ := json.Marshal(authnettest)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func CreateShippingAddress(profileID string, address Address) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	customerShipping := CustomerShippingAddress{authToken,profileID,address}
	customerShippingRequest := CustomerShippingAddressRequest{customerShipping}
	jsoned, _ := json.Marshal(customerShippingRequest)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	var new_address_id string
	if !success {
		new_address_id = "0"
	} else {
		new_address_id = outgoing["customerAddressId"].(string)
	}
	// Delay for Authorize.net
	time.Sleep(3 * time.Second)
	return new_address_id, success
}

func GetShippingAddress(profileID string, shippingID string) (map[string]interface{}, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	customerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}
	customerShippingRequest := GetCustomerShippingAddressRequest{customerShipping}
	jsoned, _ := json.Marshal(customerShippingRequest)
	outgoing, _ := SendRequest(string(jsoned))
	success := FindResultCode(outgoing)
	return outgoing["address"].(map[string]interface{}), success
}

func DeleteShippingAddress(profileID string, shippingID string) bool {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	customerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}
	customerShippingRequest := DeleteCustomerShippingAddressRequest{customerShipping}
	jsoned, _ := json.Marshal(customerShippingRequest)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	return status
}

func GetTransactionDetails(tranID string) map[string]interface{} {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	transDetails := TransactionDetails{authToken,tranID}
	transactionRequest := TransactionDetailsRequest{transDetails}
	jsoned, _ := json.Marshal(transactionRequest)
	outgoing, _ := SendRequest(string(jsoned))
	if outgoing["transaction"]!=nil {
		return outgoing["transaction"].(map[string]interface{})
	}
	return map[string]interface{}{}
}

func FindResultCode(incoming map[string]interface{}) bool {
	messages, _ := incoming["messages"].(map[string]interface{})
	if messages!=nil {
		if messages["resultCode"] == "Ok" {
			return true
		}
	}
	return false
}

func TransactionApproved(incoming map[string]interface{}) bool {
	if incoming!=nil {
		messages, _ := incoming["transactionResponse"].(map[string]interface{})
		if messages["responseCode"] == "1" {
			return true
		}
	}
	return false
}

func CreateSubscription(newSubscription Subscription) (string, bool) {
	authToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}
	subscriptonSubmit := CreateSubscriptionRequest{ARBCreateSubscription{authToken, newSubscription}}
	jsoned, _ := json.Marshal(subscriptonSubmit)
	outgoing, _ := SendRequest(string(jsoned))
	status := FindResultCode(outgoing)
	if status {
		return outgoing["subscriptionId"].(string), status
	}
	return "0", status
}

func RefundTransactions(){

}

func VoidTransaction(){

}

func DeleteSubscription(){

}

func UpdateSubscription(){

}

func GetSubscriptions(){

}

<|endoftext|>


<commit_before>package main

import (
	"github.com/Zenika/MARCEL/backend/agenda"
	"github.com/Zenika/MARCEL/backend/auth"
	"github.com/Zenika/MARCEL/backend/weather"
	"github.com/gorilla/mux"
	"github.com/rs/cors"
	"net/http"
)

func main() {

	c := cors.New(cors.Options{
		//AllowedOrigins:   []string{"*"},
		AllowedOrigins:   []string{"http://localhost:*"},
		AllowedMethods:   []string{"GET", "POST", "DELETE", "OPTION", "PUT"},
		AllowCredentials: true,
	})

	r := mux.NewRouter()
	r.HandleFunc("/api/v1/weather/forecast/{nbForecasts:[0-9]+}", weather.GetForecastWeatherHandler)
	r.HandleFunc("/api/v1/agenda/incoming/{nbEvents:[0-9]*}", agenda.GetNextEvents)
	r.HandleFunc("/api/v1/GoogleLogin", auth.HandleGoogleLogin)
	r.HandleFunc("/api/v1/GoogleCallback", auth.HandleGoogleCallback)

	handler := c.Handler(r)
	http.ListenAndServe(":8090", handler)
}
<commit_msg>for dev : allow * for CORS<commit_after>package main

import (
	"github.com/Zenika/MARCEL/backend/agenda"
	"github.com/Zenika/MARCEL/backend/auth"
	"github.com/Zenika/MARCEL/backend/weather"
	"github.com/gorilla/mux"
	"github.com/rs/cors"
	"net/http"
)

func main() {

	c := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		//AllowedOrigins:   []string{"http://localhost:*"},
		AllowedMethods:   []string{"GET", "POST", "DELETE", "OPTION", "PUT"},
		AllowCredentials: true,
	})

	r := mux.NewRouter()
	r.HandleFunc("/api/v1/weather/forecast/{nbForecasts:[0-9]+}", weather.GetForecastWeatherHandler)
	r.HandleFunc("/api/v1/agenda/incoming/{nbEvents:[0-9]*}", agenda.GetNextEvents)
	r.HandleFunc("/api/v1/GoogleLogin", auth.HandleGoogleLogin)
	r.HandleFunc("/api/v1/GoogleCallback", auth.HandleGoogleCallback)

	handler := c.Handler(r)

	http.ListenAndServe(":8090", handler)
}
<|endoftext|>


<commit_before>// Copyright 2014 Paul Jolly <paul@myitcv.org.uk>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package neovim implements support for writing Neovim plugins in Go. It also
implements a tool for generating the MSGPACK-based API against a Neovim instance.

All API methods are supported, as are notifications. See Subscription for an example
of how to register a subscription on a given topic.

Client

Everything starts from Client:

	_, err := neovim.NewUnixClient("unix", nil, &net.UnixAddr{Name: "/tmp/neovim"})
	if err != nil {
		log.Fatalf("Could not create new Unix client: %v", errgo.Details(err))
	}

See the examples for further usage patterns.

Concurrency

A single Client may safely be used by multiple goroutines. Calls to API methods are blocking
by design.

Generating the API

See the github repo for details on re-generating the API.

Compatibility

There are currently no checks to verify a connected Neovim instance exposes the same API
against which the neovim package was generated. This is future work (and probably needs
some work on the Neovim side).

Errors

Errors returned by this package are created using errgo at http://godoc.org/github.com/juju/errgo.
Hence errors may be inspected using functions like errgo.Details for example:

	_, err := client.GetCurrentBuffer()
	if err != nil {
		log.Fatalf("Could not get current buffer: %v", errgo.Details(err))
	}
*/
package neovim

import (
	"io"
	"log"
	"net"
	"os/exec"
	"sync/atomic"

	"github.com/juju/errgo"
	"github.com/juju/errors"
	"github.com/vmihailenco/msgpack"
)

// NewUnixClient is a convenience method for creating a new *Client. Method signature matches
// that of net.DialUnix
func NewUnixClient(_net string, laddr, raddr *net.UnixAddr) (*Client, error) {
	c, err := net.DialUnix(_net, laddr, raddr)
	if err != nil {
		return nil, errgo.Notef(err, "Could not establish connection to Neovim, _net %v, laddr %v, %v", _net, laddr, raddr)
	}
	return NewClient(c)
}

// NewCmdClient creates a new Client that is linked via stdin/stdout to the
// supplied exec.Cmd, which is assumed to launch Neovim. The Neovim flag
// --embedded-mode is added if it is missing, and the exec.Cmd is started
// as part of creating the client. Calling Close() will close stdin on the
// embedded Neovim instance, thereby ending the process
func NewCmdClient(c *exec.Cmd) (*Client, error) {
	stdin, err := c.StdinPipe()
	if err != nil {
		log.Fatalf("Could not get a stdin pipe to embedded nvim: %v\n", err)
	}
	stdout, err := c.StdoutPipe()
	if err != nil {
		log.Fatalf("Could not get a stdout pipe to embedded nvim: %v\n", err)
	}
	wrap := &stdWrapper{stdin: stdin, stdout: stdout}

	// ensure that we have --embedded-mode
	found := false
	for i := range c.Args {
		if c.Args[i] == "--embedded-mode" {
			found = true
		}
	}

	if !found {
		c.Args = append(c.Args, "--embedded-mode")
	}

	err = c.Start()
	if err != nil {
		log.Fatalf("Could not start the cmd: %v\n", err)
	}

	return NewClient(wrap)
}

// NewClient creates a new Client
func NewClient(c io.ReadWriteCloser) (*Client, error) {
	res := &Client{rw: c}
	res.respMap = newSyncMap()
	res.dec = msgpack.NewDecoder(c)
	res.enc = msgpack.NewEncoder(c)
	res.SubChan = make(chan Subscription)
	res.UnsubChan = make(chan Subscription)
	go res.doListen()
	return res, nil
}

// Close cleanly kills the client connection to Neovim
func (c *Client) Close() error {
	err := c.rw.Close()
	if err != nil {
		log.Fatalf("Could not cleanly close client: %v\n", err)
	}
	// TODO improve this
	return nil
}

func (c *Client) doListen() {
	// TODO need kill channel

	// TODO look at the semantics of making this buffered...
	subEvents := make(chan SubscriptionEvent, 10)
	go c.doSubscriptionManager(subEvents)

	dec := c.dec
	for {
		// TODO need better handling of EOF, i.e. client dies
		_, err := dec.DecodeSliceLen()
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			log.Fatalf("Could not decode message slice length: %v", err)
		}

		t, err := dec.DecodeInt()
		if err != nil {
			log.Fatalf("Could not decode message type: %v", err)
		}

		switch t {
		case 1:
			// handle response
			reqID, err := dec.DecodeUint32()
			if err != nil {
				log.Fatalf("Could not decode request id: %v", err)
			}

			// do we have an error?
			re, err := dec.DecodeInterface()
			if err != nil {
				log.Fatalf("Could not decode response error: %v", err)
			}
			if re != nil {
				log.Fatalf("Got a response error: %v", re)
			}

			// no, carry on
			rh, err := c.respMap.Get(reqID)
			if err != nil {
				log.Fatalf("Could not get response holder for %v: %v", reqID, err)
			}

			// we have a valid response, dispatch to our decoder for the response
			res, err := rh.dec()
			if err != nil {
				log.Fatalf("Could not decode response: %v\n", err)
			}

			resp := &response{obj: res, err: nil}
			rh.ch <- resp
		case 2:
			// handle notification
			topic, err := dec.DecodeString()
			if err != nil {
				log.Fatalf("Could not decode topic: %v", err)
			}

			// TODO this could be more efficient?
			obj, err := dec.DecodeInterface()
			if err != nil {
				log.Fatalf("Could not decode obj payload: %v", err)
			}

			ev := SubscriptionEvent{
				Topic: topic,
				Value: obj,
			}

			subEvents <- ev
		default:
			log.Fatalf("Unexpected type of message: %v\n", t)
		}
	}
}

func (c *Client) doSubscriptionManager(se chan SubscriptionEvent) {
	subs := make(map[string]map[chan SubscriptionEvent]struct{})

	sendOrClose := func(c chan error, e error) {
		if c != nil {
			if e != nil {
				c <- e
			} else {
				close(c)
			}
		}
	}

	for {
		select {
		case event := <-se:
			// TODO should we really swallow events on topics for which we have no subs?
			if chans, ok := subs[event.Topic]; ok {
				for k := range chans {
					k <- event
				}
			} else {
				log.Printf("Got an event for which we have no subs on topic %v\n", event.Topic)
			}
		case sub := <-c.SubChan:
			m, ok := subs[sub.Topic]
			if !ok {
				m = make(map[chan SubscriptionEvent]struct{})
				subs[sub.Topic] = m
			}
			if _, ok := m[sub.Events]; ok {
				sendOrClose(sub.Error, errors.Errorf("Already have subscription for topic %v on this channel", sub.Topic))
			}
			m[sub.Events] = struct{}{}
			sendOrClose(sub.Error, nil)
		case unsub := <-c.UnsubChan:
			m, ok := subs[unsub.Topic]
			if !ok {
				sendOrClose(unsub.Error, errors.Errorf("We don't have any subscriptions for topic %v", unsub.Topic))
			}
			if _, ok := m[unsub.Events]; !ok {
				sendOrClose(unsub.Error, errors.Errorf("We don't have a subscription on topic %v on this channel", unsub.Topic))
			}
			delete(m, unsub.Events)
			sendOrClose(unsub.Error, nil)
		}
	}
}

func (c *Client) makeCall(reqMethID neovimMethodID, e encoder, d decoder) (chan *response, error) {
	reqType := 0
	reqID := c.nextReqID()
	enc := c.enc

	res := make(chan *response)
	rh := &responseHolder{dec: d, ch: res}
	err := c.respMap.Put(reqID, rh)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not store response holder")
	}

	err = enc.EncodeSliceLen(4)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request length")
	}

	err = enc.EncodeInt(reqType)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request type")
	}

	err = enc.EncodeUint32(reqID)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request ID")
	}

	err = enc.EncodeUint32(uint32(reqMethID))
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request method ID")
	}

	err = e()
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode method args ")
	}

	// TODO need a flush here?

	return res, nil
}

func (c *Client) nextReqID() uint32 {
	return atomic.AddUint32(&c.nextReq, 1)
}

func (c *Client) panicOrReturn(e error) error {
	if e != nil && c.PanicOnError {
		panic(e)
	}
	return e
}
<commit_msg>Add some debugging for Travis<commit_after>// Copyright 2014 Paul Jolly <paul@myitcv.org.uk>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package neovim implements support for writing Neovim plugins in Go. It also
implements a tool for generating the MSGPACK-based API against a Neovim instance.

All API methods are supported, as are notifications. See Subscription for an example
of how to register a subscription on a given topic.

Client

Everything starts from Client:

	_, err := neovim.NewUnixClient("unix", nil, &net.UnixAddr{Name: "/tmp/neovim"})
	if err != nil {
		log.Fatalf("Could not create new Unix client: %v", errgo.Details(err))
	}

See the examples for further usage patterns.

Concurrency

A single Client may safely be used by multiple goroutines. Calls to API methods are blocking
by design.

Generating the API

See the github repo for details on re-generating the API.

Compatibility

There are currently no checks to verify a connected Neovim instance exposes the same API
against which the neovim package was generated. This is future work (and probably needs
some work on the Neovim side).

Errors

Errors returned by this package are created using errgo at http://godoc.org/github.com/juju/errgo.
Hence errors may be inspected using functions like errgo.Details for example:

	_, err := client.GetCurrentBuffer()
	if err != nil {
		log.Fatalf("Could not get current buffer: %v", errgo.Details(err))
	}
*/
package neovim

import (
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"os/exec"
	"sync/atomic"

	"github.com/juju/errgo"
	"github.com/juju/errors"
	"github.com/vmihailenco/msgpack"
)

// NewUnixClient is a convenience method for creating a new *Client. Method signature matches
// that of net.DialUnix
func NewUnixClient(_net string, laddr, raddr *net.UnixAddr) (*Client, error) {
	c, err := net.DialUnix(_net, laddr, raddr)
	if err != nil {
		return nil, errgo.Notef(err, "Could not establish connection to Neovim, _net %v, laddr %v, %v", _net, laddr, raddr)
	}
	return NewClient(c)
}

// NewCmdClient creates a new Client that is linked via stdin/stdout to the
// supplied exec.Cmd, which is assumed to launch Neovim. The Neovim flag
// --embedded-mode is added if it is missing, and the exec.Cmd is started
// as part of creating the client. Calling Close() will close stdin on the
// embedded Neovim instance, thereby ending the process
func NewCmdClient(c *exec.Cmd) (*Client, error) {
	stdin, err := c.StdinPipe()
	if err != nil {
		log.Fatalf("Could not get a stdin pipe to embedded nvim: %v\n", err)
	}
	stdout, err := c.StdoutPipe()
	if err != nil {
		log.Fatalf("Could not get a stdout pipe to embedded nvim: %v\n", err)
	}
	wrap := &stdWrapper{stdin: stdin, stdout: stdout}

	// ensure that we have --embedded-mode
	found := false
	for i := range c.Args {
		if c.Args[i] == "--embedded-mode" {
			found = true
		}
	}

	if !found {
		c.Args = append(c.Args, "--embedded-mode")
	}

	err = c.Start()
	if err != nil {
		log.Fatalf("Could not start the cmd: %v\n", err)
	}

	return NewClient(wrap)
}

// NewClient creates a new Client
func NewClient(c io.ReadWriteCloser) (*Client, error) {
	res := &Client{rw: c}
	res.respMap = newSyncMap()
	res.dec = msgpack.NewDecoder(c)
	res.enc = msgpack.NewEncoder(c)
	res.SubChan = make(chan Subscription)
	res.UnsubChan = make(chan Subscription)
	go res.doListen()
	return res, nil
}

// Close cleanly kills the client connection to Neovim
func (c *Client) Close() error {
	err := c.rw.Close()
	if err != nil {
		log.Fatalf("Could not cleanly close client: %v\n", err)
	}
	// TODO improve this
	return nil
}

func (c *Client) doListen() {
	// TODO need kill channel

	// TODO look at the semantics of making this buffered...
	subEvents := make(chan SubscriptionEvent, 10)
	go c.doSubscriptionManager(subEvents)

	dec := c.dec
	for {
		// TODO need better handling of EOF, i.e. client dies
		_, err := dec.DecodeSliceLen()
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			log.Fatalf("Could not decode message slice length: %v", err)
		}

		t, err := dec.DecodeInt()
		if err != nil {
			log.Fatalf("Could not decode message type: %v", err)
		}

		switch t {
		case 1:
			// handle response
			reqID, err := dec.DecodeUint32()
			if err != nil {
				log.Fatalf("Could not decode request id: %v", err)
			}

			// do we have an error?
			re, err := dec.DecodeInterface()
			if err != nil {
				log.Fatalf("Could not decode response error: %v", err)
			}
			if re != nil {
				log.Fatalf("Got a response error for request %v: %v", reqID, re)
			}

			// no, carry on
			rh, err := c.respMap.Get(reqID)
			if err != nil {
				log.Fatalf("Could not get response holder for %v: %v", reqID, err)
			}

			// we have a valid response, dispatch to our decoder for the response
			res, err := rh.dec()
			if err != nil {
				log.Fatalf("Could not decode response: %v\n", err)
			}

			resp := &response{obj: res, err: nil}
			rh.ch <- resp
		case 2:
			// handle notification
			topic, err := dec.DecodeString()
			if err != nil {
				log.Fatalf("Could not decode topic: %v", err)
			}

			// TODO this could be more efficient?
			obj, err := dec.DecodeInterface()
			if err != nil {
				log.Fatalf("Could not decode obj payload: %v", err)
			}

			ev := SubscriptionEvent{
				Topic: topic,
				Value: obj,
			}

			subEvents <- ev
		default:
			log.Fatalf("Unexpected type of message: %v\n", t)
		}
	}
}

func (c *Client) doSubscriptionManager(se chan SubscriptionEvent) {
	subs := make(map[string]map[chan SubscriptionEvent]struct{})

	sendOrClose := func(c chan error, e error) {
		if c != nil {
			if e != nil {
				c <- e
			} else {
				close(c)
			}
		}
	}

	for {
		select {
		case event := <-se:
			// TODO should we really swallow events on topics for which we have no subs?
			if chans, ok := subs[event.Topic]; ok {
				for k := range chans {
					k <- event
				}
			} else {
				log.Printf("Got an event for which we have no subs on topic %v\n", event.Topic)
			}
		case sub := <-c.SubChan:
			m, ok := subs[sub.Topic]
			if !ok {
				m = make(map[chan SubscriptionEvent]struct{})
				subs[sub.Topic] = m
			}
			if _, ok := m[sub.Events]; ok {
				sendOrClose(sub.Error, errors.Errorf("Already have subscription for topic %v on this channel", sub.Topic))
			}
			m[sub.Events] = struct{}{}
			sendOrClose(sub.Error, nil)
		case unsub := <-c.UnsubChan:
			m, ok := subs[unsub.Topic]
			if !ok {
				sendOrClose(unsub.Error, errors.Errorf("We don't have any subscriptions for topic %v", unsub.Topic))
			}
			if _, ok := m[unsub.Events]; !ok {
				sendOrClose(unsub.Error, errors.Errorf("We don't have a subscription on topic %v on this channel", unsub.Topic))
			}
			delete(m, unsub.Events)
			sendOrClose(unsub.Error, nil)
		}
	}
}

func (c *Client) makeCall(reqMethID neovimMethodID, e encoder, d decoder) (chan *response, error) {
	reqType := 0
	reqID := c.nextReqID()
	enc := c.enc

	fmt.Fprintf(os.Stderr, "Call id %v: %v\n", reqID, reqMethID)

	res := make(chan *response)
	rh := &responseHolder{dec: d, ch: res}
	err := c.respMap.Put(reqID, rh)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not store response holder")
	}

	err = enc.EncodeSliceLen(4)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request length")
	}

	err = enc.EncodeInt(reqType)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request type")
	}

	err = enc.EncodeUint32(reqID)
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request ID")
	}

	err = enc.EncodeUint32(uint32(reqMethID))
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode request method ID")
	}

	err = e()
	if err != nil {
		return nil, errgo.NoteMask(err, "Could not encode method args ")
	}

	// TODO need a flush here?

	return res, nil
}

func (c *Client) nextReqID() uint32 {
	return atomic.AddUint32(&c.nextReq, 1)
}

func (c *Client) panicOrReturn(e error) error {
	if e != nil && c.PanicOnError {
		panic(e)
	}
	return e
}
<|endoftext|>