<commit_before>// +build e2e

/*
Copyright 2019 The Knative 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 e2e

import (
	"fmt"
	"strings"
	"testing"

	"github.com/knative/serving/pkg/apis/serving/v1alpha1"
	serviceresourcenames "github.com/knative/serving/pkg/reconciler/service/resources/names"
	v1alpha1testing "github.com/knative/serving/pkg/testing/v1alpha1"
	"github.com/knative/serving/test"
	v1a1test "github.com/knative/serving/test/v1alpha1"
)

func TestImagePullError(t *testing.T) {
	clients := Setup(t)
	const (
		backoffMsg    = "Back-off pulling image"
		backoffReason = "ImagePullBackOff"
		daemonMsg     = "Error response from daemon: manifest for"
		daemonReason  = "ErrImagePull"
	)
	names := test.ResourceNames{
		Service: test.ObjectNameForTest(t),
		// TODO: Replace this when sha256 is broken.
		Image: "ubuntu@sha256:0000000000000000000000000000000000000000000000000000000000000000",
	}

	defer test.TearDown(clients, names)
	test.CleanupOnInterrupt(func() { test.TearDown(clients, names) })

	t.Logf("Creating a new Service %s", names.Image)
	var (
		svc *v1alpha1.Service
		err error
	)
	if svc, err = createLatestService(t, clients, names); err != nil {
		t.Fatalf("Failed to create Service %s: %v", names.Service, err)
	}

	names.Config = serviceresourcenames.Configuration(svc)

	err = v1a1test.WaitForServiceState(clients.ServingAlphaClient, names.Service, func(r *v1alpha1.Service) (bool, error) {
		cond := r.Status.GetCondition(v1alpha1.ConfigurationConditionReady)
		if cond != nil && !cond.IsUnknown() {
			if cond.IsFalse() {
				if strings.Contains(cond.Message, backoffMsg) ||
					strings.Contains(cond.Message, daemonMsg) {
					return true, nil
				}
			}
			t.Logf("Reason: %s ; Message: %s ; Status: %s", cond.Reason, cond.Message, cond.Status)
			return true, fmt.Errorf("the service %s was not marked with expected error condition, but with (Reason=\"%s\", Message=\"%s\", Status=\"%s\")",
				names.Service, cond.Reason, cond.Message, cond.Status)
		}
		return false, nil
	}, "ContainerUnpullable")

	if err != nil {
		t.Fatalf("Failed to validate service state: %s", err)
	}

	revisionName, err := revisionFromConfiguration(clients, names.Config)
	if err != nil {
		t.Fatalf("Failed to get revision from configuration %s: %v", names.Config, err)
	}

	t.Log("When the images are not pulled, the revision should have error status.")
	err = v1a1test.CheckRevisionState(clients.ServingAlphaClient, revisionName, func(r *v1alpha1.Revision) (bool, error) {
		cond := r.Status.GetCondition(v1alpha1.RevisionConditionReady)
		if cond != nil {
			if (cond.Reason == backoffReason && strings.Contains(cond.Message, backoffMsg)) ||
				(cond.Reason == daemonReason && strings.Contains(cond.Message, daemonMsg)) {
				return true, nil
			}
			return true, fmt.Errorf("the revision %s was not marked with expected error condition, but with (Reason=%q, Message=%q)",
				revisionName, cond.Reason, cond.Message)
		}
		return false, nil
	})

	if err != nil {
		t.Fatalf("Failed to validate revision state: %s", err)
	}
}

// Wrote our own thing so that we can pass in an image by digest.
// knative/pkg/test.ImagePath currently assumes there's a tag, which fails to parse.
func createLatestService(t *testing.T, clients *test.Clients, names test.ResourceNames) (*v1alpha1.Service, error) {
	opt := v1alpha1testing.WithInlineConfigSpec(*v1a1test.ConfigurationSpec(names.Image, &v1a1test.Options{}))
	service := v1alpha1testing.ServiceWithoutNamespace(names.Service, opt)
	v1a1test.LogResourceObject(t, v1a1test.ResourceObjects{Service: service})
	return clients.ServingAlphaClient.Services.Create(service)
}
<commit_msg>TestImagePullError accepts another err string to succeed (#4348)<commit_after>// +build e2e

/*
Copyright 2019 The Knative 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 e2e

import (
	"fmt"
	"testing"

	"github.com/knative/serving/pkg/apis/serving/v1alpha1"
	serviceresourcenames "github.com/knative/serving/pkg/reconciler/service/resources/names"
	v1alpha1testing "github.com/knative/serving/pkg/testing/v1alpha1"
	"github.com/knative/serving/test"
	v1a1test "github.com/knative/serving/test/v1alpha1"
)

func TestImagePullError(t *testing.T) {
	clients := Setup(t)
	names := test.ResourceNames{
		Service: test.ObjectNameForTest(t),
		// TODO: Replace this when sha256 is broken.
		Image: "ubuntu@sha256:0000000000000000000000000000000000000000000000000000000000000000",
	}

	defer test.TearDown(clients, names)
	test.CleanupOnInterrupt(func() { test.TearDown(clients, names) })

	t.Logf("Creating a new Service %s", names.Image)
	var (
		svc *v1alpha1.Service
		err error
	)
	if svc, err = createLatestService(t, clients, names); err != nil {
		t.Fatalf("Failed to create Service %s: %v", names.Service, err)
	}

	names.Config = serviceresourcenames.Configuration(svc)

	err = v1a1test.WaitForServiceState(clients.ServingAlphaClient, names.Service, func(r *v1alpha1.Service) (bool, error) {
		cond := r.Status.GetCondition(v1alpha1.ConfigurationConditionReady)
		if cond != nil && !cond.IsUnknown() {
			if cond.IsFalse() {
				if cond.Reason == "RevisionFailed" {
					return true, nil
				}
			}
			t.Logf("Reason: %s ; Message: %s ; Status: %s", cond.Reason, cond.Message, cond.Status)
			return true, fmt.Errorf("the service %s was not marked with expected error condition, but with (Reason=\"%s\", Message=\"%s\", Status=\"%s\")",
				names.Service, cond.Reason, cond.Message, cond.Status)
		}
		return false, nil
	}, "ContainerUnpullable")

	if err != nil {
		t.Fatalf("Failed to validate service state: %s", err)
	}

	revisionName, err := revisionFromConfiguration(clients, names.Config)
	if err != nil {
		t.Fatalf("Failed to get revision from configuration %s: %v", names.Config, err)
	}

	t.Log("When the images are not pulled, the revision should have error status.")
	err = v1a1test.CheckRevisionState(clients.ServingAlphaClient, revisionName, func(r *v1alpha1.Revision) (bool, error) {
		cond := r.Status.GetCondition(v1alpha1.RevisionConditionReady)
		if cond != nil {
			if cond.Reason == "ImagePullBackOff" || cond.Reason == "ErrImagePull" {
				return true, nil
			}
			return true, fmt.Errorf("the revision %s was not marked with expected error condition, but with (Reason=%q, Message=%q)",
				revisionName, cond.Reason, cond.Message)
		}
		return false, nil
	})

	if err != nil {
		t.Fatalf("Failed to validate revision state: %s", err)
	}
}

// Wrote our own thing so that we can pass in an image by digest.
// knative/pkg/test.ImagePath currently assumes there's a tag, which fails to parse.
func createLatestService(t *testing.T, clients *test.Clients, names test.ResourceNames) (*v1alpha1.Service, error) {
	opt := v1alpha1testing.WithInlineConfigSpec(*v1a1test.ConfigurationSpec(names.Image, &v1a1test.Options{}))
	service := v1alpha1testing.ServiceWithoutNamespace(names.Service, opt)
	v1a1test.LogResourceObject(t, v1a1test.ResourceObjects{Service: service})
	return clients.ServingAlphaClient.Services.Create(service)
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"os"
	"reflect"
	"time"

	api "github.com/armon/consul-api"
)

const (
	// The amount of time to do a blocking query for
	defaultWaitTime = 60 * time.Second
)

type Watcher struct {
	// config is a Consul Template Config object to be read by the watcher
	config *Config
}

// NewWatcher accepts a Config and creates a new Watcher.
func NewWatcher(config *Config) (*Watcher, error) {
	if config == nil {
		return nil, errors.New("cannot specify empty config")
	}

	watcher := &Watcher{
		config: config,
	}

	return watcher, nil
}

// Watch starts the Watcher process, querying the Consul API and rendering any
// configuration file changes.
func (w *Watcher) Watch() error {
	client, err := w.client()
	if err != nil {
		return err
	}

	views, templates, ctemplates, err := w.createViews()
	if err != nil {
		return err
	}

	doneCh := make(chan struct{})
	viewCh := w.waitForChanges(views, client, doneCh)

	if w.config.Once {
		// If we are running in "once" mode, quit after the first poll
		close(doneCh)
	} else {
		// Ensure we stop background polling when we quit the Watcher
		defer close(doneCh)
	}

	for {
		if w.config.Once && w.renderedAll(views) {
			// If we are in "once" mode and all the templates have been rendered,
			// exit gracefully
			return nil
		}

		select {
		case view := <-viewCh:
			for _, template := range view.Templates {
				deps := templates[template]
				context := &TemplateContext{
					Services:    make(map[string][]*Service),
					Keys:        make(map[string]string),
					KeyPrefixes: make(map[string][]*KeyPair),
				}

				// Continue if not all the required dependencies have been loaded
				// into the views
				if !w.ready(views, deps) {
					continue
				}

				for _, dep := range deps {
					v := views[dep]
					switch d := v.Dependency.(type) {
					case *ServiceDependency:
						context.Services[d.Key()] = v.Data.([]*Service)
					case *KeyDependency:
						context.Keys[d.Key()] = v.Data.(string)
					case *KeyPrefixDependency:
						context.KeyPrefixes[d.Key()] = v.Data.([]*KeyPair)
					default:
						panic(fmt.Sprintf("unknown dependency type: %q", d))
					}
				}

				if w.config.Dry {
					template.Execute(os.Stderr, context)
				} else {
					ctemplate := ctemplates[template]
					out, err := os.OpenFile(ctemplate.Destination, os.O_WRONLY, 0666)
					if err != nil {
						panic(err)
					}

					template.Execute(out, context)
				}
			}
		case <-doneCh:
			println("received on doneCh")
			return nil
		}
	}

	return nil
}

//
func (w *Watcher) waitForChanges(views map[Dependency]*DataView, client *api.Client, doneCh chan struct{}) <-chan *DataView {
	viewCh := make(chan *DataView, len(views))
	for _, view := range views {
		go view.poll(viewCh, client, doneCh)
	}
	return viewCh
}

//
func (w *Watcher) createViews() (map[Dependency]*DataView, map[*Template][]Dependency, map[*Template]*ConfigTemplate, error) {
	views := make(map[Dependency]*DataView)
	templates := make(map[*Template][]Dependency)
	ctemplates := make(map[*Template]*ConfigTemplate)

	// For each Dependency per ConfigTemplate, construct a DataView object which
	// ties the dependency to the Templates which depend on it
	for _, ctemplate := range w.config.ConfigTemplates {
		template := &Template{Input: ctemplate.Source}
		deps, err := template.Dependencies()
		if err != nil {
			return nil, nil, nil, err
		}

		for _, dep := range deps {
			// Create the DataView if it does not exist
			if _, ok := views[dep]; !ok {
				views[dep] = &DataView{Dependency: dep}
			}

			// Create the Templtes slice if it does not exist
			if len(views[dep].Templates) == 0 {
				views[dep].Templates = make([]*Template, 0, 1)
			}

			// Append the ConfigTemplate to the slice
			views[dep].Templates = append(views[dep].Templates, template)
		}

		// Add the template and its dependencies to the list
		templates[template] = deps

		// Map the template to its ConfigTemplate
		ctemplates[template] = ctemplate
	}

	return views, templates, ctemplates, nil
}

// ready determines if the views have loaded all the required information
// from the dependency.
func (w *Watcher) ready(views map[Dependency]*DataView, deps []Dependency) bool {
	for _, dep := range deps {
		v := views[dep]
		if !v.loaded() {
			return false
		}
	}
	return true
}

//
func (w *Watcher) renderedAll(views map[Dependency]*DataView) bool {
	for _, view := range views {
		for _, template := range view.Templates {
			if !template.Rendered() {
				return false
			}
		}
	}

	return true
}

//
func (w *Watcher) client() (*api.Client, error) {
	consulConfig := api.DefaultConfig()
	if w.config.Consul != "" {
		consulConfig.Address = w.config.Consul
	}
	if w.config.Token != "" {
		consulConfig.Token = w.config.Token
	}

	client, err := api.NewClient(consulConfig)
	if err != nil {
		return nil, err
	}
	if _, err := client.Agent().NodeName(); err != nil {
		return nil, err
	}

	return client, nil
}

/// ------------------------- ///

type DataView struct {
	Templates  []*Template
	Dependency Dependency
	Data       interface{}
	LastIndex  uint64
}

//
func (view *DataView) poll(ch chan *DataView, client *api.Client, doneCh chan struct{}) {
	for {
		options := &api.QueryOptions{
			WaitTime:  defaultWaitTime,
			WaitIndex: view.LastIndex,
		}
		data, qm, err := view.Dependency.Fetch(client, options)
		if err != nil {
			panic(err) // TODO: push err to err ch or something
		}

		println(fmt.Sprintf("[%d] Poll: %#v", time.Now().Unix(), view.Dependency))

		// Consul is allowed to return even if there's no new data. Ignore data if
		// the index is the same.
		if qm.LastIndex == view.LastIndex {
			continue
		}

		// Update the index in case we got a new version, but the data is the same
		view.LastIndex = qm.LastIndex

		// Do not trigger a render if the data is the same
		if reflect.DeepEqual(data, view.Data) {
			continue
		}

		// If we got this far, there is new data!
		view.Data = data
		ch <- view

		// Break from the function if we are done - this happens at the end of the
		// function to ensure it runs at least once
		select {
		case <-doneCh:
			return
		}
	}
}

//
func (view *DataView) loaded() bool {
	return view.LastIndex != 0
}
<commit_msg>Check if the template has been rendered in once mode<commit_after>package main

import (
	"errors"
	"fmt"
	"os"
	"reflect"
	"time"

	api "github.com/armon/consul-api"
)

const (
	// The amount of time to do a blocking query for
	defaultWaitTime = 60 * time.Second
)

type Watcher struct {
	// config is a Consul Template Config object to be read by the watcher
	config *Config
}

// NewWatcher accepts a Config and creates a new Watcher.
func NewWatcher(config *Config) (*Watcher, error) {
	if config == nil {
		return nil, errors.New("cannot specify empty config")
	}

	watcher := &Watcher{
		config: config,
	}

	return watcher, nil
}

// Watch starts the Watcher process, querying the Consul API and rendering any
// configuration file changes.
func (w *Watcher) Watch() error {
	client, err := w.client()
	if err != nil {
		return err
	}

	views, templates, ctemplates, err := w.createViews()
	if err != nil {
		return err
	}

	doneCh := make(chan struct{})
	viewCh := w.waitForChanges(views, client, doneCh)

	if w.config.Once {
		// If we are running in "once" mode, quit after the first poll
		close(doneCh)
	} else {
		// Ensure we stop background polling when we quit the Watcher
		defer close(doneCh)
	}

	for {
		if w.config.Once && w.renderedAll(views) {
			// If we are in "once" mode and all the templates have been rendered,
			// exit gracefully
			return nil
		}

		select {
		case view := <-viewCh:
			for _, template := range view.Templates {
				if w.config.Once && template.Rendered() {
					// If we are in "once" mode, do not rendered the same template twice
					continue
				}

				deps := templates[template]
				context := &TemplateContext{
					Services:    make(map[string][]*Service),
					Keys:        make(map[string]string),
					KeyPrefixes: make(map[string][]*KeyPair),
				}

				// Continue if not all the required dependencies have been loaded
				// into the views
				if !w.ready(views, deps) {
					continue
				}

				for _, dep := range deps {
					v := views[dep]
					switch d := v.Dependency.(type) {
					case *ServiceDependency:
						context.Services[d.Key()] = v.Data.([]*Service)
					case *KeyDependency:
						context.Keys[d.Key()] = v.Data.(string)
					case *KeyPrefixDependency:
						context.KeyPrefixes[d.Key()] = v.Data.([]*KeyPair)
					default:
						panic(fmt.Sprintf("unknown dependency type: %q", d))
					}
				}

				if w.config.Dry {
					template.Execute(os.Stderr, context)
				} else {
					ctemplate := ctemplates[template]
					out, err := os.OpenFile(ctemplate.Destination, os.O_WRONLY, 0666)
					if err != nil {
						panic(err)
					}

					template.Execute(out, context)
				}
			}
		case <-doneCh:
			println("received on doneCh")
			return nil
		}
	}

	return nil
}

//
func (w *Watcher) waitForChanges(views map[Dependency]*DataView, client *api.Client, doneCh chan struct{}) <-chan *DataView {
	viewCh := make(chan *DataView, len(views))
	for _, view := range views {
		go view.poll(viewCh, client, doneCh)
	}
	return viewCh
}

//
func (w *Watcher) createViews() (map[Dependency]*DataView, map[*Template][]Dependency, map[*Template]*ConfigTemplate, error) {
	views := make(map[Dependency]*DataView)
	templates := make(map[*Template][]Dependency)
	ctemplates := make(map[*Template]*ConfigTemplate)

	// For each Dependency per ConfigTemplate, construct a DataView object which
	// ties the dependency to the Templates which depend on it
	for _, ctemplate := range w.config.ConfigTemplates {
		template := &Template{Input: ctemplate.Source}
		deps, err := template.Dependencies()
		if err != nil {
			return nil, nil, nil, err
		}

		for _, dep := range deps {
			// Create the DataView if it does not exist
			if _, ok := views[dep]; !ok {
				views[dep] = &DataView{Dependency: dep}
			}

			// Create the Templtes slice if it does not exist
			if len(views[dep].Templates) == 0 {
				views[dep].Templates = make([]*Template, 0, 1)
			}

			// Append the ConfigTemplate to the slice
			views[dep].Templates = append(views[dep].Templates, template)
		}

		// Add the template and its dependencies to the list
		templates[template] = deps

		// Map the template to its ConfigTemplate
		ctemplates[template] = ctemplate
	}

	return views, templates, ctemplates, nil
}

// ready determines if the views have loaded all the required information
// from the dependency.
func (w *Watcher) ready(views map[Dependency]*DataView, deps []Dependency) bool {
	for _, dep := range deps {
		v := views[dep]
		if !v.loaded() {
			return false
		}
	}
	return true
}

//
func (w *Watcher) renderedAll(views map[Dependency]*DataView) bool {
	for _, view := range views {
		for _, template := range view.Templates {
			if !template.Rendered() {
				return false
			}
		}
	}

	return true
}

//
func (w *Watcher) client() (*api.Client, error) {
	consulConfig := api.DefaultConfig()
	if w.config.Consul != "" {
		consulConfig.Address = w.config.Consul
	}
	if w.config.Token != "" {
		consulConfig.Token = w.config.Token
	}

	client, err := api.NewClient(consulConfig)
	if err != nil {
		return nil, err
	}
	if _, err := client.Agent().NodeName(); err != nil {
		return nil, err
	}

	return client, nil
}

/// ------------------------- ///

type DataView struct {
	Templates  []*Template
	Dependency Dependency
	Data       interface{}
	LastIndex  uint64
}

//
func (view *DataView) poll(ch chan *DataView, client *api.Client, doneCh chan struct{}) {
	for {
		options := &api.QueryOptions{
			WaitTime:  defaultWaitTime,
			WaitIndex: view.LastIndex,
		}
		data, qm, err := view.Dependency.Fetch(client, options)
		if err != nil {
			panic(err) // TODO: push err to err ch or something
		}

		println(fmt.Sprintf("[%d] Poll: %#v", time.Now().Unix(), view.Dependency))

		// Consul is allowed to return even if there's no new data. Ignore data if
		// the index is the same.
		if qm.LastIndex == view.LastIndex {
			continue
		}

		// Update the index in case we got a new version, but the data is the same
		view.LastIndex = qm.LastIndex

		// Do not trigger a render if the data is the same
		if reflect.DeepEqual(data, view.Data) {
			continue
		}

		// If we got this far, there is new data!
		view.Data = data
		ch <- view

		// Break from the function if we are done - this happens at the end of the
		// function to ensure it runs at least once
		select {
		case <-doneCh:
			return
		}
	}
}

//
func (view *DataView) loaded() bool {
	return view.LastIndex != 0
}
<|endoftext|>


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

package repository

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"time"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/util"

	"github.com/unknwon/com"
)

func prepareRepoCommit(ctx models.DBContext, repo *models.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error {
	commitTimeStr := time.Now().Format(time.RFC3339)
	authorSig := repo.Owner.NewGitSig()

	// Because this may call hooks we should pass in the environment
	env := append(os.Environ(),
		"GIT_AUTHOR_NAME="+authorSig.Name,
		"GIT_AUTHOR_EMAIL="+authorSig.Email,
		"GIT_AUTHOR_DATE="+commitTimeStr,
		"GIT_COMMITTER_NAME="+authorSig.Name,
		"GIT_COMMITTER_EMAIL="+authorSig.Email,
		"GIT_COMMITTER_DATE="+commitTimeStr,
	)

	// Clone to temporary path and do the init commit.
	if stdout, err := git.NewCommand("clone", repoPath, tmpDir).
		SetDescription(fmt.Sprintf("prepareRepoCommit (git clone): %s to %s", repoPath, tmpDir)).
		RunInDirWithEnv("", env); err != nil {
		log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err)
		return fmt.Errorf("git clone: %v", err)
	}

	// README
	data, err := models.GetRepoInitFile("readme", opts.Readme)
	if err != nil {
		return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.Readme, err)
	}

	cloneLink := repo.CloneLink()
	match := map[string]string{
		"Name":           repo.Name,
		"Description":    repo.Description,
		"CloneURL.SSH":   cloneLink.SSH,
		"CloneURL.HTTPS": cloneLink.HTTPS,
		"OwnerName":      repo.OwnerName,
	}
	if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
		[]byte(com.Expand(string(data), match)), 0644); err != nil {
		return fmt.Errorf("write README.md: %v", err)
	}

	// .gitignore
	if len(opts.Gitignores) > 0 {
		var buf bytes.Buffer
		names := strings.Split(opts.Gitignores, ",")
		for _, name := range names {
			data, err = models.GetRepoInitFile("gitignore", name)
			if err != nil {
				return fmt.Errorf("GetRepoInitFile[%s]: %v", name, err)
			}
			buf.WriteString("# ---> " + name + "\n")
			buf.Write(data)
			buf.WriteString("\n")
		}

		if buf.Len() > 0 {
			if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
				return fmt.Errorf("write .gitignore: %v", err)
			}
		}
	}

	// LICENSE
	if len(opts.License) > 0 {
		data, err = models.GetRepoInitFile("license", opts.License)
		if err != nil {
			return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err)
		}

		if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
			return fmt.Errorf("write LICENSE: %v", err)
		}
	}

	return nil
}

// initRepoCommit temporarily changes with work directory.
func initRepoCommit(tmpPath string, repo *models.Repository, u *models.User, defaultBranch string) (err error) {
	commitTimeStr := time.Now().Format(time.RFC3339)

	sig := u.NewGitSig()
	// Because this may call hooks we should pass in the environment
	env := append(os.Environ(),
		"GIT_AUTHOR_NAME="+sig.Name,
		"GIT_AUTHOR_EMAIL="+sig.Email,
		"GIT_AUTHOR_DATE="+commitTimeStr,
		"GIT_COMMITTER_DATE="+commitTimeStr,
	)
	committerName := sig.Name
	committerEmail := sig.Email

	if stdout, err := git.NewCommand("add", "--all").
		SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)).
		RunInDir(tmpPath); err != nil {
		log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err)
		return fmt.Errorf("git add --all: %v", err)
	}

	err = git.LoadGitVersion()
	if err != nil {
		return fmt.Errorf("Unable to get git version: %v", err)
	}

	args := []string{
		"commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
		"-m", "Initial commit",
	}

	if git.CheckGitVersionAtLeast("1.7.9") == nil {
		sign, keyID, signer, _ := models.SignInitialCommit(tmpPath, u)
		if sign {
			args = append(args, "-S"+keyID)

			if repo.GetTrustModel() == models.CommitterTrustModel || repo.GetTrustModel() == models.CollaboratorCommitterTrustModel {
				// need to set the committer to the KeyID owner
				committerName = signer.Name
				committerEmail = signer.Email
			}
		} else if git.CheckGitVersionAtLeast("2.0.0") == nil {
			args = append(args, "--no-gpg-sign")
		}
	}

	env = append(env,
		"GIT_COMMITTER_NAME="+committerName,
		"GIT_COMMITTER_EMAIL="+committerEmail,
	)

	if stdout, err := git.NewCommand(args...).
		SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)).
		RunInDirWithEnv(tmpPath, env); err != nil {
		log.Error("Failed to commit: %v: Stdout: %s\nError: %v", args, stdout, err)
		return fmt.Errorf("git commit: %v", err)
	}

	if len(defaultBranch) == 0 {
		defaultBranch = setting.Repository.DefaultBranch
	}

	if stdout, err := git.NewCommand("push", "origin", "master:"+defaultBranch).
		SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)).
		RunInDirWithEnv(tmpPath, models.InternalPushingEnvironment(u, repo)); err != nil {
		log.Error("Failed to push back to master: Stdout: %s\nError: %v", stdout, err)
		return fmt.Errorf("git push: %v", err)
	}

	return nil
}

func checkInitRepository(owner, name string) (err error) {
	// Somehow the directory could exist.
	repoPath := models.RepoPath(owner, name)
	isExist, err := util.IsExist(repoPath)
	if err != nil {
		log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
		return err
	}
	if isExist {
		return models.ErrRepoFilesAlreadyExist{
			Uname: owner,
			Name:  name,
		}
	}

	// Init git bare new repository.
	if err = git.InitRepository(repoPath, true); err != nil {
		return fmt.Errorf("git.InitRepository: %v", err)
	} else if err = createDelegateHooks(repoPath); err != nil {
		return fmt.Errorf("createDelegateHooks: %v", err)
	}
	return nil
}

func adoptRepository(ctx models.DBContext, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
	isExist, err := util.IsExist(repoPath)
	if err != nil {
		log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
		return err
	}
	if !isExist {
		return fmt.Errorf("adoptRepository: path does not already exist: %s", repoPath)
	}

	if err := createDelegateHooks(repoPath); err != nil {
		return fmt.Errorf("createDelegateHooks: %v", err)
	}

	// Re-fetch the repository from database before updating it (else it would
	// override changes that were done earlier with sql)
	if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil {
		return fmt.Errorf("getRepositoryByID: %v", err)
	}

	repo.IsEmpty = false
	gitRepo, err := git.OpenRepository(repo.RepoPath())
	if err != nil {
		return fmt.Errorf("openRepository: %v", err)
	}
	defer gitRepo.Close()
	if len(opts.DefaultBranch) > 0 {
		repo.DefaultBranch = opts.DefaultBranch

		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
			return fmt.Errorf("setDefaultBranch: %v", err)
		}
	} else {
		repo.DefaultBranch, err = gitRepo.GetDefaultBranch()
		if err != nil {
			repo.DefaultBranch = setting.Repository.DefaultBranch
			if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
				return fmt.Errorf("setDefaultBranch: %v", err)
			}
		}

		repo.DefaultBranch = strings.TrimPrefix(repo.DefaultBranch, git.BranchPrefix)
	}
	branches, _ := gitRepo.GetBranches()
	found := false
	hasDefault := false
	hasMaster := false
	for _, branch := range branches {
		if branch == repo.DefaultBranch {
			found = true
			break
		} else if branch == setting.Repository.DefaultBranch {
			hasDefault = true
		} else if branch == "master" {
			hasMaster = true
		}
	}
	if !found {
		if hasDefault {
			repo.DefaultBranch = setting.Repository.DefaultBranch
		} else if hasMaster {
			repo.DefaultBranch = "master"
		} else if len(branches) > 0 {
			repo.DefaultBranch = branches[0]
		} else {
			repo.IsEmpty = true
			repo.DefaultBranch = setting.Repository.DefaultBranch
		}

		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
			return fmt.Errorf("setDefaultBranch: %v", err)
		}
	}

	if err = models.UpdateRepositoryCtx(ctx, repo, false); err != nil {
		return fmt.Errorf("updateRepository: %v", err)
	}

	return nil
}

// InitRepository initializes README and .gitignore if needed.
func initRepository(ctx models.DBContext, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
	if err = checkInitRepository(repo.OwnerName, repo.Name); err != nil {
		return err
	}

	// Initialize repository according to user's choice.
	if opts.AutoInit {
		tmpDir, err := ioutil.TempDir(os.TempDir(), "gitea-"+repo.Name)
		if err != nil {
			return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err)
		}
		defer func() {
			if err := util.RemoveAll(tmpDir); err != nil {
				log.Warn("Unable to remove temporary directory: %s: Error: %v", tmpDir, err)
			}
		}()

		if err = prepareRepoCommit(ctx, repo, tmpDir, repoPath, opts); err != nil {
			return fmt.Errorf("prepareRepoCommit: %v", err)
		}

		// Apply changes and commit.
		if err = initRepoCommit(tmpDir, repo, u, opts.DefaultBranch); err != nil {
			return fmt.Errorf("initRepoCommit: %v", err)
		}
	}

	// Re-fetch the repository from database before updating it (else it would
	// override changes that were done earlier with sql)
	if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil {
		return fmt.Errorf("getRepositoryByID: %v", err)
	}

	if !opts.AutoInit {
		repo.IsEmpty = true
	}

	repo.DefaultBranch = setting.Repository.DefaultBranch

	if len(opts.DefaultBranch) > 0 {
		repo.DefaultBranch = opts.DefaultBranch
		gitRepo, err := git.OpenRepository(repo.RepoPath())
		if err != nil {
			return fmt.Errorf("openRepository: %v", err)
		}
		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
			return fmt.Errorf("setDefaultBranch: %v", err)
		}
	}

	if err = models.UpdateRepositoryCtx(ctx, repo, false); err != nil {
		return fmt.Errorf("updateRepository: %v", err)
	}

	return nil
}
<commit_msg>Push HEAD instead of master when initialising repositories (#13719)<commit_after>// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package repository

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"time"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/util"

	"github.com/unknwon/com"
)

func prepareRepoCommit(ctx models.DBContext, repo *models.Repository, tmpDir, repoPath string, opts models.CreateRepoOptions) error {
	commitTimeStr := time.Now().Format(time.RFC3339)
	authorSig := repo.Owner.NewGitSig()

	// Because this may call hooks we should pass in the environment
	env := append(os.Environ(),
		"GIT_AUTHOR_NAME="+authorSig.Name,
		"GIT_AUTHOR_EMAIL="+authorSig.Email,
		"GIT_AUTHOR_DATE="+commitTimeStr,
		"GIT_COMMITTER_NAME="+authorSig.Name,
		"GIT_COMMITTER_EMAIL="+authorSig.Email,
		"GIT_COMMITTER_DATE="+commitTimeStr,
	)

	// Clone to temporary path and do the init commit.
	if stdout, err := git.NewCommand("clone", repoPath, tmpDir).
		SetDescription(fmt.Sprintf("prepareRepoCommit (git clone): %s to %s", repoPath, tmpDir)).
		RunInDirWithEnv("", env); err != nil {
		log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err)
		return fmt.Errorf("git clone: %v", err)
	}

	// README
	data, err := models.GetRepoInitFile("readme", opts.Readme)
	if err != nil {
		return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.Readme, err)
	}

	cloneLink := repo.CloneLink()
	match := map[string]string{
		"Name":           repo.Name,
		"Description":    repo.Description,
		"CloneURL.SSH":   cloneLink.SSH,
		"CloneURL.HTTPS": cloneLink.HTTPS,
		"OwnerName":      repo.OwnerName,
	}
	if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
		[]byte(com.Expand(string(data), match)), 0644); err != nil {
		return fmt.Errorf("write README.md: %v", err)
	}

	// .gitignore
	if len(opts.Gitignores) > 0 {
		var buf bytes.Buffer
		names := strings.Split(opts.Gitignores, ",")
		for _, name := range names {
			data, err = models.GetRepoInitFile("gitignore", name)
			if err != nil {
				return fmt.Errorf("GetRepoInitFile[%s]: %v", name, err)
			}
			buf.WriteString("# ---> " + name + "\n")
			buf.Write(data)
			buf.WriteString("\n")
		}

		if buf.Len() > 0 {
			if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
				return fmt.Errorf("write .gitignore: %v", err)
			}
		}
	}

	// LICENSE
	if len(opts.License) > 0 {
		data, err = models.GetRepoInitFile("license", opts.License)
		if err != nil {
			return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err)
		}

		if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
			return fmt.Errorf("write LICENSE: %v", err)
		}
	}

	return nil
}

// initRepoCommit temporarily changes with work directory.
func initRepoCommit(tmpPath string, repo *models.Repository, u *models.User, defaultBranch string) (err error) {
	commitTimeStr := time.Now().Format(time.RFC3339)

	sig := u.NewGitSig()
	// Because this may call hooks we should pass in the environment
	env := append(os.Environ(),
		"GIT_AUTHOR_NAME="+sig.Name,
		"GIT_AUTHOR_EMAIL="+sig.Email,
		"GIT_AUTHOR_DATE="+commitTimeStr,
		"GIT_COMMITTER_DATE="+commitTimeStr,
	)
	committerName := sig.Name
	committerEmail := sig.Email

	if stdout, err := git.NewCommand("add", "--all").
		SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)).
		RunInDir(tmpPath); err != nil {
		log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err)
		return fmt.Errorf("git add --all: %v", err)
	}

	err = git.LoadGitVersion()
	if err != nil {
		return fmt.Errorf("Unable to get git version: %v", err)
	}

	args := []string{
		"commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
		"-m", "Initial commit",
	}

	if git.CheckGitVersionAtLeast("1.7.9") == nil {
		sign, keyID, signer, _ := models.SignInitialCommit(tmpPath, u)
		if sign {
			args = append(args, "-S"+keyID)

			if repo.GetTrustModel() == models.CommitterTrustModel || repo.GetTrustModel() == models.CollaboratorCommitterTrustModel {
				// need to set the committer to the KeyID owner
				committerName = signer.Name
				committerEmail = signer.Email
			}
		} else if git.CheckGitVersionAtLeast("2.0.0") == nil {
			args = append(args, "--no-gpg-sign")
		}
	}

	env = append(env,
		"GIT_COMMITTER_NAME="+committerName,
		"GIT_COMMITTER_EMAIL="+committerEmail,
	)

	if stdout, err := git.NewCommand(args...).
		SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)).
		RunInDirWithEnv(tmpPath, env); err != nil {
		log.Error("Failed to commit: %v: Stdout: %s\nError: %v", args, stdout, err)
		return fmt.Errorf("git commit: %v", err)
	}

	if len(defaultBranch) == 0 {
		defaultBranch = setting.Repository.DefaultBranch
	}

	if stdout, err := git.NewCommand("push", "origin", "HEAD:"+defaultBranch).
		SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)).
		RunInDirWithEnv(tmpPath, models.InternalPushingEnvironment(u, repo)); err != nil {
		log.Error("Failed to push back to HEAD: Stdout: %s\nError: %v", stdout, err)
		return fmt.Errorf("git push: %v", err)
	}

	return nil
}

func checkInitRepository(owner, name string) (err error) {
	// Somehow the directory could exist.
	repoPath := models.RepoPath(owner, name)
	isExist, err := util.IsExist(repoPath)
	if err != nil {
		log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
		return err
	}
	if isExist {
		return models.ErrRepoFilesAlreadyExist{
			Uname: owner,
			Name:  name,
		}
	}

	// Init git bare new repository.
	if err = git.InitRepository(repoPath, true); err != nil {
		return fmt.Errorf("git.InitRepository: %v", err)
	} else if err = createDelegateHooks(repoPath); err != nil {
		return fmt.Errorf("createDelegateHooks: %v", err)
	}
	return nil
}

func adoptRepository(ctx models.DBContext, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
	isExist, err := util.IsExist(repoPath)
	if err != nil {
		log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
		return err
	}
	if !isExist {
		return fmt.Errorf("adoptRepository: path does not already exist: %s", repoPath)
	}

	if err := createDelegateHooks(repoPath); err != nil {
		return fmt.Errorf("createDelegateHooks: %v", err)
	}

	// Re-fetch the repository from database before updating it (else it would
	// override changes that were done earlier with sql)
	if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil {
		return fmt.Errorf("getRepositoryByID: %v", err)
	}

	repo.IsEmpty = false
	gitRepo, err := git.OpenRepository(repo.RepoPath())
	if err != nil {
		return fmt.Errorf("openRepository: %v", err)
	}
	defer gitRepo.Close()
	if len(opts.DefaultBranch) > 0 {
		repo.DefaultBranch = opts.DefaultBranch

		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
			return fmt.Errorf("setDefaultBranch: %v", err)
		}
	} else {
		repo.DefaultBranch, err = gitRepo.GetDefaultBranch()
		if err != nil {
			repo.DefaultBranch = setting.Repository.DefaultBranch
			if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
				return fmt.Errorf("setDefaultBranch: %v", err)
			}
		}

		repo.DefaultBranch = strings.TrimPrefix(repo.DefaultBranch, git.BranchPrefix)
	}
	branches, _ := gitRepo.GetBranches()
	found := false
	hasDefault := false
	hasMaster := false
	for _, branch := range branches {
		if branch == repo.DefaultBranch {
			found = true
			break
		} else if branch == setting.Repository.DefaultBranch {
			hasDefault = true
		} else if branch == "master" {
			hasMaster = true
		}
	}
	if !found {
		if hasDefault {
			repo.DefaultBranch = setting.Repository.DefaultBranch
		} else if hasMaster {
			repo.DefaultBranch = "master"
		} else if len(branches) > 0 {
			repo.DefaultBranch = branches[0]
		} else {
			repo.IsEmpty = true
			repo.DefaultBranch = setting.Repository.DefaultBranch
		}

		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
			return fmt.Errorf("setDefaultBranch: %v", err)
		}
	}

	if err = models.UpdateRepositoryCtx(ctx, repo, false); err != nil {
		return fmt.Errorf("updateRepository: %v", err)
	}

	return nil
}

// InitRepository initializes README and .gitignore if needed.
func initRepository(ctx models.DBContext, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
	if err = checkInitRepository(repo.OwnerName, repo.Name); err != nil {
		return err
	}

	// Initialize repository according to user's choice.
	if opts.AutoInit {
		tmpDir, err := ioutil.TempDir(os.TempDir(), "gitea-"+repo.Name)
		if err != nil {
			return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err)
		}
		defer func() {
			if err := util.RemoveAll(tmpDir); err != nil {
				log.Warn("Unable to remove temporary directory: %s: Error: %v", tmpDir, err)
			}
		}()

		if err = prepareRepoCommit(ctx, repo, tmpDir, repoPath, opts); err != nil {
			return fmt.Errorf("prepareRepoCommit: %v", err)
		}

		// Apply changes and commit.
		if err = initRepoCommit(tmpDir, repo, u, opts.DefaultBranch); err != nil {
			return fmt.Errorf("initRepoCommit: %v", err)
		}
	}

	// Re-fetch the repository from database before updating it (else it would
	// override changes that were done earlier with sql)
	if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil {
		return fmt.Errorf("getRepositoryByID: %v", err)
	}

	if !opts.AutoInit {
		repo.IsEmpty = true
	}

	repo.DefaultBranch = setting.Repository.DefaultBranch

	if len(opts.DefaultBranch) > 0 {
		repo.DefaultBranch = opts.DefaultBranch
		gitRepo, err := git.OpenRepository(repo.RepoPath())
		if err != nil {
			return fmt.Errorf("openRepository: %v", err)
		}
		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
			return fmt.Errorf("setDefaultBranch: %v", err)
		}
	}

	if err = models.UpdateRepositoryCtx(ctx, repo, false); err != nil {
		return fmt.Errorf("updateRepository: %v", err)
	}

	return nil
}
<|endoftext|>


<commit_before>package web

import (
	"encoding/json"
	"log"
	"time"

	"github.com/gocraft/web"
	"github.com/varunamachi/orek/data"
)

type Context struct {
	SessionUser  data.User
	CreationTime time.Duration
}

func checkSession(context *Context) bool {
	return true
}

func (c *Context) SessionChecker(rw web.ResponseWriter,
	req *web.Request,
	next web.NextMiddlewareFunc) {
	//get the session ID
	//see if it is still valid
	//put the user and session objects into the context object
	next(rw, req)
}

func (c *Context) Login(resp web.ResponseWriter, req *web.Request) {
	//Get the user name and password from the request
	//Authenticate the user and create the user object, put the user into
	// context
	//Check if the current session already registered to some other login
	//if so expire this session
	//Create a new session in the session table
	//	userName := req.FormValue("userName")
	//	password := req.FormValue("password")
	//	sessionId := req.FormValue("sessionId")
	//	data.DataSource().GetUser("varun").FirstName

	//	data.DataSource().GetUser(
}

func (c *Context) Logout(resp web.ResponseWriter, req *web.Request) {
	//resp.Write
}

func (c *Context) GetAllUsers(resp web.ResponseWriter, req *web.Request) {
	encoder := json.NewEncoder(resp)
	users, err := data.DataSource().GetAllUsers()
	if err == nil {
		err = encoder.Encode(users)
		if err != nil {
			err = encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal user list"})
		}
	} else {
		err = encoder.Encode(OrekError{
			"DataSourceError",
			"Failed retrieve user list from datasource"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) GetUser(resp web.ResponseWriter, req *web.Request) {
	userName := req.PathParams["userName"]
	user, err := data.DataSource().GetUser(userName)
	encoder := json.NewEncoder(resp)
	if err == nil {
		err = encoder.Encode(user)
		if err != nil {
			err = encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal user details"})
		}
	} else {
		err = encoder.Encode(OrekError{
			"DataSourceError",
			"Failed to fetch user detail from data source"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) CreateUser(resp web.ResponseWriter, req *web.Request) {
	encoder := json.NewEncoder(resp)
	decoder := json.NewDecoder(req.Body)
	var user data.User
	var err error = nil
	if err = decoder.Decode(&user); err == nil {
		err = data.DataSource().CreateOrUpdateUser(&user)
		if err != nil {
			err = encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal user creation result"})
		}
	} else {
		err = encoder.Encode(OrekError{
			"UnmarshalError",
			"Failed to create user from given information"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) DeleteUser(resp web.ResponseWriter, req *web.Request) {
	userName := req.PathParams["userName"]
	encoder := json.NewEncoder(resp)
	var err error = nil
	if len(userName) > 0 {
		err = data.DataSource().DeleteUser(userName)
		if err != nil {
			err = encoder.Encode(OrekError{
				"DataSourceError",
				"Failed to delete user"})
		}

	} else {
		err = encoder.Encode(OrekError{
			"ArgumentError",
			"Invalid user name given for deletion"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) GetAllSources(resp web.ResponseWriter, req *web.Request) {
	sources, err := data.DataSource().GetAllSources()
	encoder := json.NewEncoder(resp)
	if err == nil {
		err = encoder.Encode(sources)
		if err != nil {
			encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal source list"})
		}
	} else {
		encoder.Encode(OrekError{
			"DataSourceError",
			"Failed to fetch list of source from database"})

	}
	if err == nil {
		log.Print(err)
	}
}

func (c *Context) GetSource(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetSourceWithId(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) CreateOrUpdateSource(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) DeleteSource(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetAllVariables(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetVariable(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetVariableWithId(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) CreateOrUpdateVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) DeleteVariable(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetAllUserGroups(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetUserGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) CreateOrUpdateUserGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) DeleteUserGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetAllVariableGroups(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetVariableGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetVariableGroupWithId(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) CreateOrUpdateVariableGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) DeleteVariableGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) AddUserToGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) RemoveUserFromGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetUsersInGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetGroupsForUser(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) AddVariableToGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) RemoveVariableFromGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetVariablesInGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetGroupsForVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) AddVariableValue(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) ClearValuesForVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetValuesForVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func Setup() error {

	return nil
}
<commit_msg>Added implementations for more APIs<commit_after>package web

import (
	"encoding/json"
	"log"
	"time"

	"github.com/gocraft/web"
	"github.com/varunamachi/orek/data"
)

type Context struct {
	SessionUser  data.User
	CreationTime time.Duration
}

func checkSession(context *Context) bool {
	return true
}

func (c *Context) SessionChecker(rw web.ResponseWriter,
	req *web.Request,
	next web.NextMiddlewareFunc) {
	//get the session ID
	//see if it is still valid
	//put the user and session objects into the context object
	next(rw, req)
}

func (c *Context) Login(resp web.ResponseWriter, req *web.Request) {
	//Get the user name and password from the request
	//Authenticate the user and create the user object, put the user into
	// context
	//Check if the current session already registered to some other login
	//if so expire this session
	//Create a new session in the session table
	//	userName := req.FormValue("userName")
	//	password := req.FormValue("password")
	//	sessionId := req.FormValue("sessionId")
	//	data.DataSource().GetUser("varun").FirstName

	//	data.DataSource().GetUser(
}

func (c *Context) Logout(resp web.ResponseWriter, req *web.Request) {
	//resp.Write
}

func (c *Context) GetAllUsers(resp web.ResponseWriter, req *web.Request) {
	encoder := json.NewEncoder(resp)
	users, err := data.DataSource().GetAllUsers()
	if err == nil {
		err = encoder.Encode(users)
		if err != nil {
			err = encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal user list"})
		}
	} else {
		err = encoder.Encode(OrekError{
			"DataSourceError",
			"Failed retrieve user list from datasource"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) GetUser(resp web.ResponseWriter, req *web.Request) {
	userName := req.PathParams["userName"]
	user, err := data.DataSource().GetUser(userName)
	encoder := json.NewEncoder(resp)
	if err == nil {
		err = encoder.Encode(user)
		if err != nil {
			err = encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal user details"})
		}
	} else {
		err = encoder.Encode(OrekError{
			"DataSourceError",
			"Failed to fetch user detail from data source"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) CreateUser(resp web.ResponseWriter, req *web.Request) {
	encoder := json.NewEncoder(resp)
	decoder := json.NewDecoder(req.Body)
	var user data.User
	var err error = nil
	if err = decoder.Decode(&user); err == nil {
		err = data.DataSource().CreateOrUpdateUser(&user)
		if err != nil {
			err = encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal user creation result"})
		}
	} else {
		err = encoder.Encode(OrekError{
			"UnmarshalError",
			"Failed to create user from given information"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) DeleteUser(resp web.ResponseWriter, req *web.Request) {
	userName := req.PathParams["userName"]
	encoder := json.NewEncoder(resp)
	var err error = nil
	if len(userName) > 0 {
		err = data.DataSource().DeleteUser(userName)
		if err != nil {
			err = encoder.Encode(OrekError{
				"DataSourceError",
				"Failed to delete user"})
		}

	} else {
		err = encoder.Encode(OrekError{
			"ArgumentError",
			"Invalid user name given for deletion"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) GetAllSources(resp web.ResponseWriter, req *web.Request) {
	sources, err := data.DataSource().GetAllSources()
	encoder := json.NewEncoder(resp)
	if err == nil {
		err = encoder.Encode(sources)
		if err != nil {
			encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal source list"})
		}
	} else {
		encoder.Encode(OrekError{
			"DataSourceError",
			"Failed to fetch list of source from database"})

	}
	if err == nil {
		log.Print(err)
	}
}

func (c *Context) GetSource(resp web.ResponseWriter, req *web.Request) {
	sourceName := req.PathParams["sourceName"]
	sourceOwner := req.PathParams["sourceOwner"]
	encoder := json.NewEncoder(resp)
	source, err := data.DataSource().GetSource(sourceName, sourceOwner)
	if err == nil {
		err = encoder.Encode(source)
		if err != nil {
			encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal source information"})
		}
	} else {
		encoder.Encode(OrekError{
			"DataSourceError",
			"Failed to fetch source information from database"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) GetSourceWithId(resp web.ResponseWriter, req *web.Request) {
	sourceId := req.PathParams["sourceId"]
	encoder := json.NewEncoder(resp)
	source, err := data.DataSource().GetSourceWithId(sourceId)
	if err == nil {
		err = encoder.Encode(source)
		if err != nil {
			encoder.Encode(OrekError{
				"MarshalError",
				"Failed to marshal source information"})
		}
	} else {
		encoder.Encode(OrekError{
			"DataSourceError",
			"Failed to fetch source information from database"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) CreateOrUpdateSource(resp web.ResponseWriter, req *web.Request) {
	decoder := json.NewDecoder(req.Body)
	encoder := json.NewEncoder(resp)
	var source data.Source
	err := decoder.Decode(&source)
	if err == nil {
		err = data.DataSource().CreateOrUpdateSource(&source)
		if err != nil {
			encoder.Encode(OrekError{
				"DataSourceError",
				"Failed to add source to database"})
		}
	} else {
		encoder.Encode(OrekError{
			"UnamarshalError",
			"Could not decode the given source information"})
	}
	if err != nil {
		log.Print(err)
	}

}

func (c *Context) DeleteSource(resp web.ResponseWriter, req *web.Request) {
	sourceId := req.PathParams["sourceId"]
	err := data.DataSource().DeleteSource(sourceId)
	encoder := json.NewEncoder(resp)
	if err != nil {
		encoder.Encode(OrekError{
			"DataSourceError",
			"Could not delete the source with given id"})
		log.Print(err)
	}
}

func (c *Context) GetAllVariables(resp web.ResponseWriter, req *web.Request) {
	vars, err := data.DataSource().GetAllVariables()
	encoder := json.NewEncoder(resp)
	if err == nil {
		err = encoder.Encode(vars)
		if err != nil {
			encoder.Encode(OrekError{
				"MarshalError",
				"Could not encode the list of variables"})
		}
	} else {
		encoder.Encode(OrekError{
			"DataSourceError",
			"Could not get list of variables from DB"})
	}
	if err != nil {
		log.Print(err)
	}
}

func (c *Context) GetVariable(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetVariableWithId(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) CreateOrUpdateVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) DeleteVariable(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetAllUserGroups(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetUserGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) CreateOrUpdateUserGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) DeleteUserGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetAllVariableGroups(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetVariableGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetVariableGroupWithId(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) CreateOrUpdateVariableGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) DeleteVariableGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) AddUserToGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) RemoveUserFromGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetUsersInGroup(resp web.ResponseWriter, req *web.Request) {

}

func (c *Context) GetGroupsForUser(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) AddVariableToGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) RemoveVariableFromGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetVariablesInGroup(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetGroupsForVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) AddVariableValue(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) ClearValuesForVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func (c *Context) GetValuesForVariable(resp web.ResponseWriter,
	req *web.Request) {

}

func Setup() error {

	return nil
}
<|endoftext|>


<commit_before>package config

import (
	"encoding/json"
	"errors"
	"flag"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/essentier/nomockutil"
)

const SpickSpanConfigFile = "spickspan.json"

var ssconfig string

func init() {
	flag.StringVar(&ssconfig, "spickspan", filepath.Join(".", SpickSpanConfigFile), "configuration for spickspan")
}

func GetConfig() (Model, error) {
	configFilePath, err := findPathOfConfigFile()
	if err != nil {
		log.Printf("Failed to find the file path of the config file.")
		return Model{}, err
	}
	log.Printf("config file path: %v", configFilePath)
	return ParseConfigFile(configFilePath)
}

func ParseConfigFile(filename string) (Model, error) {
	data, e := ioutil.ReadFile(filename)
	if e != nil {
		log.Printf("File error: %v\n", e)
		os.Exit(1)
	}
	return parseConfigData(data, filename)
}

func adjustModel(model *Model, configFilePath string) {
	filedir := filepath.Dir(configFilePath)
	for name, service := range model.Services {
		service.ServiceName = name
		if service.ProjectSrcRoot != "" {
			projectRoot := filepath.Join(filedir, service.ProjectSrcRoot)
			service.ProjectSrcRoot = projectRoot
		}
		model.Services[name] = service
	}
}

func validateModel(model *Model) error {
	for name, service := range model.Services {
		if service.ProjectSrcRoot != "" {
			err := nomockutil.ValidateServiceName(name)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func parseConfigData(data []byte, configFilePath string) (Model, error) {
	var config Model
	err := json.Unmarshal(data, &config)
	if err != nil {
		return config, err
	}

	err = validateModel(&config)
	if err != nil {
		return config, err
	}

	adjustModel(&config, configFilePath)
	log.Printf("SpickSpan configurations: %v\n", config)
	return config, nil
}

func findPathOfConfigFile() (string, error) {
	//Path of config file is:
	//  current working directory plus
	//  the value of the -ssconfig flag plus
	//  the file name 'ssconfig.json'.
	//The default value of the -ssconfig file is '.'
	flag.Parse()
	configFilePath, err := filepath.Abs(ssconfig)
	if err != nil {
		return "", err
	}

	configFilePath = filepath.Clean(configFilePath)

	if strings.HasSuffix(configFilePath, SpickSpanConfigFile) {
		filedir := filepath.Dir(configFilePath)
		log.Printf("Starting to find config file at %v and up the directory hierarchy.", filedir)
		return findFileInParentDirs(filedir, SpickSpanConfigFile)
	} else {
		_, err := os.Stat(configFilePath)
		if os.IsNotExist(err) {
			return "", errors.New("Could not find config file.")
		} else {
			return configFilePath, nil
		}
	}
}

func findFileInParentDirs(filedir string, filename string) (string, error) {
	fullFileName := filepath.Join(filedir, filename)
	_, err := os.Stat(fullFileName)
	if os.IsNotExist(err) {
		parentFiledir := filepath.Dir(filedir)
		if parentFiledir == filedir {
			return "", errors.New("Could not find config file.")
		}
		return findFileInParentDirs(parentFiledir, filename)
	} else {
		return fullFileName, nil
	}
}
<commit_msg>search for config files up the folder hierarchy regardless of the filenames<commit_after>package config

import (
	"encoding/json"
	"errors"
	"flag"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/essentier/nomockutil"
)

const SpickSpanConfigFile = "spickspan.json"

var ssconfig string

func init() {
	flag.StringVar(&ssconfig, "spickspan", filepath.Join(".", SpickSpanConfigFile), "configuration for spickspan")
}

func GetConfig() (Model, error) {
	configFilePath, err := findPathOfConfigFile()
	if err != nil {
		log.Printf("Failed to find the file path of the config file.")
		return Model{}, err
	}
	log.Printf("config file path: %v", configFilePath)
	return ParseConfigFile(configFilePath)
}

func ParseConfigFile(filename string) (Model, error) {
	data, e := ioutil.ReadFile(filename)
	if e != nil {
		log.Printf("File error: %v\n", e)
		os.Exit(1)
	}
	return parseConfigData(data, filename)
}

func adjustModel(model *Model, configFilePath string) {
	filedir := filepath.Dir(configFilePath)
	for name, service := range model.Services {
		service.ServiceName = name
		if service.ProjectSrcRoot != "" {
			projectRoot := filepath.Join(filedir, service.ProjectSrcRoot)
			service.ProjectSrcRoot = projectRoot
		}
		model.Services[name] = service
	}
}

func validateModel(model *Model) error {
	for name, service := range model.Services {
		if service.ProjectSrcRoot != "" {
			err := nomockutil.ValidateServiceName(name)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func parseConfigData(data []byte, configFilePath string) (Model, error) {
	var config Model
	err := json.Unmarshal(data, &config)
	if err != nil {
		return config, err
	}

	err = validateModel(&config)
	if err != nil {
		return config, err
	}

	adjustModel(&config, configFilePath)
	log.Printf("SpickSpan configurations: %v\n", config)
	return config, nil
}

func findPathOfConfigFile() (string, error) {
	//Path of config file is:
	//  current working directory plus
	//  the value of the -ssconfig flag plus
	//  the file name 'ssconfig.json'.
	//The default value of the -ssconfig file is '.'
	flag.Parse()
	configFilePath, err := filepath.Abs(ssconfig)
	if err != nil {
		return "", err
	}

	configFilePath = filepath.Clean(configFilePath)
	filedir := filepath.Dir(configFilePath)
	filename := filepath.Base(configFilePath)
	log.Printf("Starting to find config file at %v and up the directory hierarchy.", filedir)
	return findFileInParentDirs(filedir, filename)

	// if strings.HasSuffix(configFilePath, SpickSpanConfigFile) {
	// 	filedir := filepath.Dir(configFilePath)
	// 	log.Printf("Starting to find config file at %v and up the directory hierarchy.", filedir)
	// 	return findFileInParentDirs(filedir, SpickSpanConfigFile)
	// } else {
	// 	_, err := os.Stat(configFilePath)
	// 	if os.IsNotExist(err) {
	// 		return "", errors.New("Could not find config file.")
	// 	} else {
	// 		return configFilePath, nil
	// 	}
	// }
}

func findFileInParentDirs(filedir string, filename string) (string, error) {
	fullFileName := filepath.Join(filedir, filename)
	_, err := os.Stat(fullFileName)
	if os.IsNotExist(err) {
		parentFiledir := filepath.Dir(filedir)
		if parentFiledir == filedir {
			return "", errors.New("Could not find config file.")
		}
		return findFileInParentDirs(parentFiledir, filename)
	} else if err != nil {
		return "", err
	} else {
		return fullFileName, nil
	}
}
<|endoftext|>


<commit_before>package q

import (
	"database/sql"
	"fmt"
	"testing"

	"github.com/oov/q/qutil"
)

var expressionTests = []struct {
	Name string
	E    Expression
	Want map[qutil.Dialect]string
	V    string
}{
	{
		Name: `=`,
		E:    Eq(0, 1),
		Want: resultMap("0", "false", "0"),
		V:    `? = ? [0 1]`,
	},
	{
		Name: `=(NULL)`,
		// Unsafe is workaround for PostgreSQL "could not determine data type of parameter $1" error.
		E:    Eq(Unsafe(0), nil),
		Want: resultMap("0", "false", "0"),
		V:    `0 IS NULL []`,
	},
	{
		Name: `=(NULL)2`,
		E:    Eq(nil, Unsafe(0)),
		Want: resultMap("0", "false", "0"),
		V:    `0 IS NULL []`,
	},
	{
		Name: `=(NULL)3`,
		E:    Eq(nil, nil),
		Want: resultMap("1", "true", "1"),
		V:    `NULL IS NULL []`,
	},
	{
		Name: `= empty slice`,
		E:    Eq(0, []int{}),
		Want: resultMap("0", "false", "0"),
		V:    `'IN' = '()' []`,
	},
	{
		Name: `= slice`,
		E:    Eq(0, []int{1, 2, 3}),
		Want: resultMap("0", "false", "0"),
		V:    `? IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `!=`,
		E:    Neq(0, 1),
		Want: resultMap("1", "true", "1"),
		V:    `? != ? [0 1]`,
	},
	{
		Name: `!=(NULL)`,
		E:    Neq(Unsafe(0), nil),
		Want: resultMap("1", "true", "1"),
		V:    `0 IS NOT NULL []`,
	},
	{
		Name: `!=(NULL)2`,
		E:    Neq(nil, Unsafe(0)),
		Want: resultMap("1", "true", "1"),
		V:    `0 IS NOT NULL []`,
	},
	{
		Name: `!=(NULL)3`,
		E:    Neq(nil, nil),
		Want: resultMap("0", "false", "0"),
		V:    `NULL IS NOT NULL []`,
	},
	{
		Name: `!= empty slice`,
		E:    Neq(0, []int{}),
		Want: resultMap("1", "true", "1"),
		V:    `'IN' != '()' []`,
	},
	{
		Name: `!= slice`,
		E:    Neq(0, []int{1, 2, 3}),
		Want: resultMap("1", "true", "1"),
		V:    `? NOT IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `>`,
		E:    Gt(0, 1),
		Want: resultMap("0", "false", "0"),
		V:    `? > ? [0 1]`,
	},
	{
		Name: `>=`,
		E:    Gte(0, 1),
		Want: resultMap("0", "false", "0"),
		V:    `? >= ? [0 1]`,
	},
	{
		Name: `<`,
		E:    Lt(1, 0),
		Want: resultMap("0", "false", "0"),
		V:    `? < ? [1 0]`,
	},
	{
		Name: `<=`,
		E:    Lte(1, 0),
		Want: resultMap("0", "false", "0"),
		V:    `? <= ? [1 0]`,
	},
	{
		Name: `IN empty slice`,
		E:    In(0, []int{}),
		Want: resultMap("0", "false", "0"),
		V:    `'IN' = '()' []`,
	},
	{
		Name: `IN slice`,
		E:    In(0, []int{1, 2, 3}),
		Want: resultMap("0", "false", "0"),
		V:    `? IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `IN builder`,
		E:    In(0, Select().Column(C("id")).From(T("user"))),
		Want: resultMap("0", "false", "0"),
		V:    `? IN (SELECT "id" FROM "user") [0]`,
	},
	{
		Name: `NOT IN empty slice`,
		E:    NotIn(0, []int{}),
		Want: resultMap("1", "true", "1"),
		V:    `'IN' != '()' []`,
	},
	{
		Name: `NOT IN slice`,
		E:    NotIn(0, []int{1, 2, 3}),
		Want: resultMap("1", "true", "1"),
		V:    `? NOT IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `NOT IN builder`,
		E:    NotIn(0, Select().Column(C("id")).From(T("user"))),
		Want: resultMap("1", "true", "1"),
		V:    `? NOT IN (SELECT "id" FROM "user") [0]`,
	},
	{
		Name: `AND empty`,
		E:    And(),
		Want: resultMap("0", "false", "0"),
		V:    `('empty' = 'AND') []`,
	},
	{
		Name: `AND 1`,
		E:    And(Eq(0, 1)),
		Want: resultMap("0", "false", "0"),
		V:    `? = ? [0 1]`,
	},
	{
		Name: `AND 2`,
		E:    And(Eq(0, 1), Neq(0, 0)),
		Want: resultMap("0", "false", "0"),
		V:    `(? = ?)AND(? != ?) [0 1 0 0]`,
	},
	{
		Name: `OR empty`,
		E:    Or(),
		Want: resultMap("0", "false", "0"),
		V:    `('empty' = 'OR') []`,
	},
	{
		Name: `OR 1`,
		E:    Or(Eq(0, 1)),
		Want: resultMap("0", "false", "0"),
		V:    `? = ? [0 1]`,
	},
	{
		Name: `OR 2`,
		E:    Or(Eq(0, 1), Neq(0, 0)),
		Want: resultMap("0", "false", "0"),
		V:    `(? = ?)OR(? != ?) [0 1 0 0]`,
	},
	{
		Name: `Unsafe`,
		E:    Unsafe(3, "%", 2),
		Want: resultMap("1", "1", "1"),
		V:    `3%2 []`,
	},
	{
		Name: `Unsafe + Expression nil`,
		E:    Unsafe(C("id"), " IS ", nil),
		Want: resultMap("0", "false", "0"),
		V:    `"id" IS NULL []`,
	},
	{
		Name: `Unsafe + V`,
		E:    Unsafe(C("id"), " = ", V(0)),
		Want: resultMap("0", "false", "0"),
		V:    `"id" = ? [0]`,
	},
	{
		Name: `Unsafe + InV(not slice)`,
		E:    Unsafe(C("id"), " IN ", InV(0)),
		Want: resultMap("0", "false", "0"),
		V:    `"id" IN (?) [0]`,
	},
	{
		Name: `Unsafe + InV(slice)`,
		E:    Unsafe(C("id"), " IN ", InV([]int{100, 101, 102})),
		Want: resultMap("0", "false", "0"),
		V:    `"id" IN (?,?,?) [100 101 102]`,
	},
	{
		Name: `COUNT(*)`,
		E:    CountAll(),
		Want: resultMap("2", "2", "2"),
		V:    `COUNT(*) []`,
	},
	{
		Name: `COUNT`,
		E:    Count(C("id")),
		Want: resultMap("2", "2", "2"),
		V:    `COUNT("id") []`,
	},
	{
		Name: `AVG`,
		E:    Avg(C("age")),
		Want: resultMap("29.5000", "29.5000000000000000", "29.5"),
		V:    `AVG("age") []`,
	},
	{
		Name: `MAX`,
		E:    Max(C("age")),
		Want: resultMap("44", "44", "44"),
		V:    `MAX("age") []`,
	},
	{
		Name: `MIN`,
		E:    Min(C("age")),
		Want: resultMap("15", "15", "15"),
		V:    `MIN("age") []`,
	},
	{
		Name: `SUM`,
		E:    Sum(C("age")),
		Want: resultMap("59", "59", "59"),
		V:    `SUM("age") []`,
	},
	{
		Name: `CHAR_LENGTH`,
		E:    CharLength(C("name")),
		Want: resultMap("6", "6", "6"),
		V:    `CHAR_LENGTH("name") []`,
	},
}

func TestNullCUnimplementedPanic(t *testing.T) {
	defer func() {
		if e := recover(); e == nil {
			t.Error("want Panic got Nothing")
		}
	}()
	nullExpr{}.C()
}

func TestInVEmptySlicePanic(t *testing.T) {
	defer func() {
		if e := recover(); e == nil {
			t.Error("want Panic got Nothing")
		}
	}()
	InV([]int{})
}

func TestExpression(t *testing.T) {
	for i, test := range expressionTests {
		if r := fmt.Sprint(test.E); r != test.V {
			t.Errorf("test[%d] %s want %s got %s", i, test.Name, test.V, r)
		}
	}
}

func resultMap(r ...string) map[qutil.Dialect]string {
	return map[qutil.Dialect]string{
		MySQL:      r[0],
		PostgreSQL: r[1],
		SQLite:     r[2],
	}
}

func TestExpressionOnDB(t *testing.T) {
	for _, testData := range testModel {
		err := testData.tester(func(db *sql.DB, d qutil.Dialect) {
			defer exec(t, "drops", db, d, testData.drops)
			exec(t, "drops", db, d, testData.drops)
			exec(t, "creates", db, d, testData.creates)
			exec(t, "inserts", db, d, testData.inserts)
			for i, test := range expressionTests {
				func() {
					var r string
					sql, args := Select().Column(test.E.C()).From(T("user")).Limit(1).SetDialect(d).ToSQL()
					if err := db.QueryRow(sql, args...).Scan(&r); err != nil {
						t.Fatalf("%s tests[%d] %s Error: %v\n%s", d, i, test.Name, err, sql)
					}
					if fmt.Sprint(r) != fmt.Sprint(test.Want[d]) {
						t.Errorf("%s test[%d] %s want %v got %v", d, i, test.Name, test.Want[d], r)
					}
				}()
			}
		})
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestVariableStringer(t *testing.T) {
	if want, r := `? [1]`, fmt.Sprint(V(1)); r != want {
		t.Errorf(`V(1) want %s got %s`, want, r)
	}
	if want, r := `? AS "v" [1]`, fmt.Sprint(V(1).C("v")); r != want {
		t.Errorf(`V(1).C() want %s got %s`, want, r)
	}
	if want, r := `(?,?,?) [1 2 3]`, fmt.Sprint(InV([]int{1, 2, 3})); r != want {
		t.Errorf(`InV([]int{1, 2, 3}) want %s got %s`, want, r)
	}
	if want, r := `(?) AS "v" [1]`, fmt.Sprint(InV([]int{1}).C("v")); r != want {
		t.Errorf(`InV([]int{1}).C() want %s got %s`, want, r)
	}
}

func BenchmarkSimpleExpr(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Gt(C("test"), 1)
	}
}

func BenchmarkEqExpr(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Eq(C("test"), 1)
	}
}

func BenchmarkInExpr(b *testing.B) {
	for i := 0; i < b.N; i++ {
		In(C("test"), []int{1, 2, 3})
	}
}

func BenchmarkLogicalExpr(b *testing.B) {
	for i := 0; i < b.N; i++ {
		In(C("test"), []int{1, 2, 3})
	}
}

func BenchmarkInV(b *testing.B) {
	for i := 0; i < b.N; i++ {
		InV([]int{1, 2, 3})
	}
}
<commit_msg>fix and improve tests<commit_after>package q

import (
	"database/sql"
	"fmt"
	"testing"

	"github.com/oov/q/qutil"
)

var expressionTests = []struct {
	Name string
	E    Expression
	Want map[qutil.Dialect]string
	V    string
}{
	{
		Name: `=`,
		E:    Eq(0, 1),
		Want: resultMap("0", "false", "0"),
		V:    `? = ? [0 1]`,
	},
	{
		Name: `=(NULL)`,
		// Unsafe is workaround for PostgreSQL "could not determine data type of parameter $1" error.
		E:    Eq(Unsafe(0), nil),
		Want: resultMap("0", "false", "0"),
		V:    `0 IS NULL []`,
	},
	{
		Name: `=(NULL)2`,
		E:    Eq(nil, Unsafe(0)),
		Want: resultMap("0", "false", "0"),
		V:    `0 IS NULL []`,
	},
	{
		Name: `=(NULL)3`,
		E:    Eq(nil, nil),
		Want: resultMap("1", "true", "1"),
		V:    `NULL IS NULL []`,
	},
	{
		Name: `= empty slice`,
		E:    Eq(0, []int{}),
		Want: resultMap("0", "false", "0"),
		V:    `'IN' = '()' []`,
	},
	{
		Name: `= slice`,
		E:    Eq(0, []int{1, 2, 3}),
		Want: resultMap("0", "false", "0"),
		V:    `? IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `!=`,
		E:    Neq(0, 1),
		Want: resultMap("1", "true", "1"),
		V:    `? != ? [0 1]`,
	},
	{
		Name: `!=(NULL)`,
		E:    Neq(Unsafe(0), nil),
		Want: resultMap("1", "true", "1"),
		V:    `0 IS NOT NULL []`,
	},
	{
		Name: `!=(NULL)2`,
		E:    Neq(nil, Unsafe(0)),
		Want: resultMap("1", "true", "1"),
		V:    `0 IS NOT NULL []`,
	},
	{
		Name: `!=(NULL)3`,
		E:    Neq(nil, nil),
		Want: resultMap("0", "false", "0"),
		V:    `NULL IS NOT NULL []`,
	},
	{
		Name: `!= empty slice`,
		E:    Neq(0, []int{}),
		Want: resultMap("1", "true", "1"),
		V:    `'IN' != '()' []`,
	},
	{
		Name: `!= slice`,
		E:    Neq(0, []int{1, 2, 3}),
		Want: resultMap("1", "true", "1"),
		V:    `? NOT IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `>`,
		E:    Gt(0, 1),
		Want: resultMap("0", "false", "0"),
		V:    `? > ? [0 1]`,
	},
	{
		Name: `>=`,
		E:    Gte(0, 1),
		Want: resultMap("0", "false", "0"),
		V:    `? >= ? [0 1]`,
	},
	{
		Name: `<`,
		E:    Lt(1, 0),
		Want: resultMap("0", "false", "0"),
		V:    `? < ? [1 0]`,
	},
	{
		Name: `<=`,
		E:    Lte(1, 0),
		Want: resultMap("0", "false", "0"),
		V:    `? <= ? [1 0]`,
	},
	{
		Name: `IN empty slice`,
		E:    In(0, []int{}),
		Want: resultMap("0", "false", "0"),
		V:    `'IN' = '()' []`,
	},
	{
		Name: `IN slice`,
		E:    In(0, []int{1, 2, 3}),
		Want: resultMap("0", "false", "0"),
		V:    `? IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `IN builder`,
		E:    In(0, Select().Column(C("id")).From(T("user"))),
		Want: resultMap("0", "false", "0"),
		V:    `? IN (SELECT "id" FROM "user") [0]`,
	},
	{
		Name: `NOT IN empty slice`,
		E:    NotIn(0, []int{}),
		Want: resultMap("1", "true", "1"),
		V:    `'IN' != '()' []`,
	},
	{
		Name: `NOT IN slice`,
		E:    NotIn(0, []int{1, 2, 3}),
		Want: resultMap("1", "true", "1"),
		V:    `? NOT IN (?,?,?) [0 1 2 3]`,
	},
	{
		Name: `NOT IN builder`,
		E:    NotIn(0, Select().Column(C("id")).From(T("user"))),
		Want: resultMap("1", "true", "1"),
		V:    `? NOT IN (SELECT "id" FROM "user") [0]`,
	},
	{
		Name: `AND empty`,
		E:    And(),
		Want: resultMap("0", "false", "0"),
		V:    `('empty' = 'AND') []`,
	},
	{
		Name: `AND 1`,
		E:    And(Eq(0, 1)),
		Want: resultMap("0", "false", "0"),
		V:    `? = ? [0 1]`,
	},
	{
		Name: `AND 2`,
		E:    And(Eq(0, 1), Neq(0, 0)),
		Want: resultMap("0", "false", "0"),
		V:    `(? = ?)AND(? != ?) [0 1 0 0]`,
	},
	{
		Name: `OR empty`,
		E:    Or(),
		Want: resultMap("0", "false", "0"),
		V:    `('empty' = 'OR') []`,
	},
	{
		Name: `OR 1`,
		E:    Or(Eq(0, 1)),
		Want: resultMap("0", "false", "0"),
		V:    `? = ? [0 1]`,
	},
	{
		Name: `OR 2`,
		E:    Or(Eq(0, 1), Neq(0, 0)),
		Want: resultMap("0", "false", "0"),
		V:    `(? = ?)OR(? != ?) [0 1 0 0]`,
	},
	{
		Name: `Unsafe`,
		E:    Unsafe(3, "%", 2),
		Want: resultMap("1", "1", "1"),
		V:    `3%2 []`,
	},
	{
		Name: `Unsafe + Expression nil`,
		E:    Unsafe(C("id"), " IS ", nil),
		Want: resultMap("0", "false", "0"),
		V:    `"id" IS NULL []`,
	},
	{
		Name: `Unsafe + V`,
		E:    Unsafe(C("id"), " = ", V(0)),
		Want: resultMap("0", "false", "0"),
		V:    `"id" = ? [0]`,
	},
	{
		Name: `Unsafe + InV(not slice)`,
		E:    Unsafe(C("id"), " IN ", InV(0)),
		Want: resultMap("0", "false", "0"),
		V:    `"id" IN (?) [0]`,
	},
	{
		Name: `Unsafe + InV(slice)`,
		E:    Unsafe(C("id"), " IN ", InV([]int{100, 101, 102})),
		Want: resultMap("0", "false", "0"),
		V:    `"id" IN (?,?,?) [100 101 102]`,
	},
	{
		Name: `COUNT(*)`,
		E:    CountAll(),
		Want: resultMap("2", "2", "2"),
		V:    `COUNT(*) []`,
	},
	{
		Name: `COUNT`,
		E:    Count(C("id")),
		Want: resultMap("2", "2", "2"),
		V:    `COUNT("id") []`,
	},
	{
		Name: `AVG`,
		E:    Avg(C("age")),
		Want: resultMap("29.5000", "29.5000000000000000", "29.5"),
		V:    `AVG("age") []`,
	},
	{
		Name: `MAX`,
		E:    Max(C("age")),
		Want: resultMap("44", "44", "44"),
		V:    `MAX("age") []`,
	},
	{
		Name: `MIN`,
		E:    Min(C("age")),
		Want: resultMap("15", "15", "15"),
		V:    `MIN("age") []`,
	},
	{
		Name: `SUM`,
		E:    Sum(C("age")),
		Want: resultMap("59", "59", "59"),
		V:    `SUM("age") []`,
	},
	{
		Name: `CHAR_LENGTH`,
		E:    CharLength(C("name")),
		Want: resultMap("6", "6", "6"),
		V:    `CHAR_LENGTH("name") []`,
	},
}

func TestNullCUnimplementedPanic(t *testing.T) {
	defer func() {
		if e := recover(); e == nil {
			t.Error("want Panic got Nothing")
		}
	}()
	nullExpr{}.C()
}

func TestInVEmptySlicePanic(t *testing.T) {
	defer func() {
		if e := recover(); e == nil {
			t.Error("want Panic got Nothing")
		}
	}()
	InV([]int{})
}

func TestExpression(t *testing.T) {
	for i, test := range expressionTests {
		if r := fmt.Sprint(test.E); r != test.V {
			t.Errorf("test[%d] %s want %s got %s", i, test.Name, test.V, r)
		}
	}
}

func resultMap(r ...string) map[qutil.Dialect]string {
	return map[qutil.Dialect]string{
		MySQL:      r[0],
		PostgreSQL: r[1],
		SQLite:     r[2],
	}
}

func TestExpressionOnDB(t *testing.T) {
	for _, testData := range testModel {
		err := testData.tester(func(db *sql.DB, d qutil.Dialect) {
			defer exec(t, "drops", db, d, testData.drops)
			exec(t, "drops", db, d, testData.drops)
			exec(t, "creates", db, d, testData.creates)
			exec(t, "inserts", db, d, testData.inserts)
			for i, test := range expressionTests {
				func() {
					var r string
					sql, args := Select().Column(test.E.C()).From(T("user")).Limit(1).SetDialect(d).ToSQL()
					if err := db.QueryRow(sql, args...).Scan(&r); err != nil {
						t.Fatalf("%s tests[%d] %s Error: %v\n%s", d, i, test.Name, err, sql)
					}
					if fmt.Sprint(r) != fmt.Sprint(test.Want[d]) {
						t.Errorf("%s test[%d] %s want %v got %v", d, i, test.Name, test.Want[d], r)
					}
				}()
			}
		})
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestVariableStringer(t *testing.T) {
	if want, r := `? [1]`, fmt.Sprint(V(1)); r != want {
		t.Errorf(`V(1) want %s got %s`, want, r)
	}
	if want, r := `? AS "v" [1]`, fmt.Sprint(V(1).C("v")); r != want {
		t.Errorf(`V(1).C() want %s got %s`, want, r)
	}
	if want, r := `(?,?,?) [1 2 3]`, fmt.Sprint(InV([]int{1, 2, 3})); r != want {
		t.Errorf(`InV([]int{1, 2, 3}) want %s got %s`, want, r)
	}
	if want, r := `(?) AS "v" [1]`, fmt.Sprint(InV([]int{1}).C("v")); r != want {
		t.Errorf(`InV([]int{1}).C() want %s got %s`, want, r)
	}
}

func BenchmarkSimpleExpr(b *testing.B) {
	c := C("test")
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		Gt(c, 1)
	}
}

func BenchmarkEqExpr(b *testing.B) {
	c := C("test")
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		Eq(c, 1)
	}
}

func BenchmarkInExpr(b *testing.B) {
	c, s := C("test"), []int{1, 2, 3}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		In(c, s)
	}
}

func BenchmarkLogicalExpr(b *testing.B) {
	eq := Eq(C("test"), []int{1, 2, 3})
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		And(eq, eq, eq)
	}
}

func BenchmarkInV(b *testing.B) {
	s := []int{1, 2, 3}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		InV(s)
	}
}
<|endoftext|>


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

package cmac

import (
	. "github.com/jacobsa/ogletest"
	"testing"
)

func TestShiftLeft(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type ShiftLeftTest struct{}

func init() { RegisterTestSuite(&ShiftLeftTest{}) }

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

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

package cmac

import (
	. "github.com/jacobsa/ogletest"
	"testing"
)

func TestShiftLeft(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type ShiftLeftTest struct{}

func init() { RegisterTestSuite(&ShiftLeftTest{}) }

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *ShiftLeftTest) NilBuffer() {
	ExpectEq("TODO", "")
}

func (t *ShiftLeftTest) EmptyBuffer() {
	ExpectEq("TODO", "")
}

func (t *ShiftLeftTest) OneByteBuffers() {
	ExpectEq("TODO", "")
}

func (t *ShiftLeftTest) MultiByteBuffers() {
	ExpectEq("TODO", "")
}
<|endoftext|>


<commit_before>// Copyright 2021 Google LLC
//
// 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 apis

import (
	"fmt"
	"io/ioutil"
	"net/url"
	"path"
	"path/filepath"
	"strings"

	"github.com/apigee/apigeecli/apiclient"
	bundle "github.com/apigee/apigeecli/bundlegen"
	proxybundle "github.com/apigee/apigeecli/bundlegen/proxybundle"
	"github.com/apigee/apigeecli/client/apis"
	"github.com/apigee/apigeecli/clilog"
	"github.com/spf13/cobra"
)

var GqlCreateCmd = &cobra.Command{
	Use:     "graphql",
	Aliases: []string{"gql"},
	Short:   "Creates an API proxy from a GraphQL schema",
	Long:    "Creates an API proxy from a GraphQL schema",
	Args: func(cmd *cobra.Command, args []string) (err error) {
		if gqlFile == "" && gqlURI == "" {
			return fmt.Errorf("Either gqlfile or gqlurl must be passed")
		}
		return apiclient.SetApigeeOrg(org)
	},
	RunE: func(cmd *cobra.Command, args []string) (err error) {
		var content []byte
		var gqlDocName string
		if gqlFile != "" {
			gqlDocName, content, err = readSchemaFile()
		} else {
			gqlDocName, content, err = readSchemaURL()
		}
		if err != nil {
			return err
		}

		location, keyName, err := getKeyNameAndLocation()
		if err != nil {
			return err
		}

		//Generate the apiproxy struct
		err = bundle.GenerateAPIProxyDefFromGQL(name,
			gqlDocName,
			basePath,
			apiKeyLocation,
			skipPolicy,
			addCORS,
			targetUrlRef,
			targetUrl)

		if err != nil {
			return err
		}

		//Create the API proxy bundle
		err = proxybundle.GenerateAPIProxyBundleFromGQL(name,
			string(content),
			gqlDocName,
			action,
			location,
			keyName,
			skipPolicy,
			addCORS,
			targetUrlRef,
			targetUrl)

		if err != nil {
			return err
		}

		if importProxy {
			_, err = apis.CreateProxy(name, name+".zip")
		}

		return err
	},
}

var gqlFile, gqlURI, basePath, action, apiKeyLocation string

func init() {
	GqlCreateCmd.Flags().StringVarP(&name, "name", "n",
		"", "API Proxy name")
	GqlCreateCmd.Flags().StringVarP(&gqlFile, "gqlfile", "f",
		"", "GraphQL schema file")
	GqlCreateCmd.Flags().StringVarP(&gqlURI, "gqluri", "u",
		"", "GraphQL schema URI location")
	GqlCreateCmd.Flags().StringVarP(&basePath, "basepath", "p",
		"", "Base Path of the API Proxy")
	GqlCreateCmd.Flags().StringVarP(&action, "action", "",
		"verify", "GraphQL policy action, must be oneOf parse, verify or parse_verify. Default is verify")
	GqlCreateCmd.Flags().StringVarP(&targetUrlRef, "target-url-ref", "",
		"", "Set target.url variable from a reference variable containing the target endpoint")
	GqlCreateCmd.Flags().StringVarP(&targetUrl, "target-url", "",
		"", "Set a target URL for the target endpoint")
	GqlCreateCmd.Flags().StringVarP(&apiKeyLocation, "apikey-location", "",
		"", "Set the location of the API key, ex: request.header.x-api-key")
	GqlCreateCmd.Flags().BoolVarP(&importProxy, "import", "",
		true, "Import API Proxy after generation from spec")
	GqlCreateCmd.Flags().BoolVarP(&skipPolicy, "skip-policy", "",
		false, "Skip adding the GraphQL Validate policy")
	GqlCreateCmd.Flags().BoolVarP(&addCORS, "add-cors", "",
		false, "Add a CORS policy")

	_ = GqlCreateCmd.MarkFlagRequired("name")
	_ = GqlCreateCmd.MarkFlagRequired("basepath")
}

func readSchemaFile() (string, []byte, error) {
	schemaFile, err := ioutil.ReadFile(gqlFile)
	if err != nil {
		clilog.Error.Println("Error reading file: ", err)
		return "", nil, err
	}
	return filepath.Base(gqlFile), schemaFile, nil
}

func readSchemaURL() (string, []byte, error) {
	u, err := url.Parse(gqlURI)
	if err != nil {
		clilog.Error.Println("Error reading uri: ", err)
		return "", nil, err
	}
	resp, err := apiclient.DownloadFile(gqlURI, false)
	if err != nil {
		clilog.Error.Println("Error downloading file: ", err)
		return "", nil, err
	}
	if resp != nil {
		defer resp.Body.Close()
	}

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		clilog.Error.Println("error in response: ", err)
		return "", nil, err
	}
	return path.Base(u.Path), respBody, err
}

func getKeyNameAndLocation() (location string, key string, err error) {
	if apiKeyLocation == "" {
		return "", "", nil
	}

	apikey := strings.Split(apiKeyLocation, ".")
	if len(apikey) != 3 {
		return "", "", fmt.Errorf("api key location must be of the form request.header.foo or request.queryparam.bar")
	}
	return apikey[1], apikey[2], nil
}
<commit_msg>Added exclusivity check for target-url and target-url-ref<commit_after>// Copyright 2021 Google LLC
//
// 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 apis

import (
	"fmt"
	"io/ioutil"
	"net/url"
	"path"
	"path/filepath"
	"strings"

	"github.com/apigee/apigeecli/apiclient"
	bundle "github.com/apigee/apigeecli/bundlegen"
	proxybundle "github.com/apigee/apigeecli/bundlegen/proxybundle"
	"github.com/apigee/apigeecli/client/apis"
	"github.com/apigee/apigeecli/clilog"
	"github.com/spf13/cobra"
)

var GqlCreateCmd = &cobra.Command{
	Use:     "graphql",
	Aliases: []string{"gql"},
	Short:   "Creates an API proxy from a GraphQL schema",
	Long:    "Creates an API proxy from a GraphQL schema",
	Args: func(cmd *cobra.Command, args []string) (err error) {
		if gqlFile == "" && gqlURI == "" {
			return fmt.Errorf("Either gqlfile or gqlurl must be passed")
		}
		if targetUrl != "" && targetUrlRef != "" {
			return fmt.Errorf("Either target-url or target-url-ref must be passed, not both")
		}
		return apiclient.SetApigeeOrg(org)
	},
	RunE: func(cmd *cobra.Command, args []string) (err error) {
		var content []byte
		var gqlDocName string
		if gqlFile != "" {
			gqlDocName, content, err = readSchemaFile()
		} else {
			gqlDocName, content, err = readSchemaURL()
		}
		if err != nil {
			return err
		}

		location, keyName, err := getKeyNameAndLocation()
		if err != nil {
			return err
		}

		//Generate the apiproxy struct
		err = bundle.GenerateAPIProxyDefFromGQL(name,
			gqlDocName,
			basePath,
			apiKeyLocation,
			skipPolicy,
			addCORS,
			targetUrlRef,
			targetUrl)

		if err != nil {
			return err
		}

		//Create the API proxy bundle
		err = proxybundle.GenerateAPIProxyBundleFromGQL(name,
			string(content),
			gqlDocName,
			action,
			location,
			keyName,
			skipPolicy,
			addCORS,
			targetUrlRef,
			targetUrl)

		if err != nil {
			return err
		}

		if importProxy {
			_, err = apis.CreateProxy(name, name+".zip")
		}

		return err
	},
}

var gqlFile, gqlURI, basePath, action, apiKeyLocation string

func init() {
	GqlCreateCmd.Flags().StringVarP(&name, "name", "n",
		"", "API Proxy name")
	GqlCreateCmd.Flags().StringVarP(&gqlFile, "gqlfile", "f",
		"", "GraphQL schema file")
	GqlCreateCmd.Flags().StringVarP(&gqlURI, "gqluri", "u",
		"", "GraphQL schema URI location")
	GqlCreateCmd.Flags().StringVarP(&basePath, "basepath", "p",
		"", "Base Path of the API Proxy")
	GqlCreateCmd.Flags().StringVarP(&action, "action", "",
		"verify", "GraphQL policy action, must be oneOf parse, verify or parse_verify. Default is verify")
	GqlCreateCmd.Flags().StringVarP(&targetUrlRef, "target-url-ref", "",
		"", "Set target.url variable from a reference variable containing the target endpoint")
	GqlCreateCmd.Flags().StringVarP(&targetUrl, "target-url", "",
		"", "Set a target URL for the target endpoint")
	GqlCreateCmd.Flags().StringVarP(&apiKeyLocation, "apikey-location", "",
		"", "Set the location of the API key, ex: request.header.x-api-key")
	GqlCreateCmd.Flags().BoolVarP(&importProxy, "import", "",
		true, "Import API Proxy after generation from spec")
	GqlCreateCmd.Flags().BoolVarP(&skipPolicy, "skip-policy", "",
		false, "Skip adding the GraphQL Validate policy")
	GqlCreateCmd.Flags().BoolVarP(&addCORS, "add-cors", "",
		false, "Add a CORS policy")

	_ = GqlCreateCmd.MarkFlagRequired("name")
	_ = GqlCreateCmd.MarkFlagRequired("basepath")
}

func readSchemaFile() (string, []byte, error) {
	schemaFile, err := ioutil.ReadFile(gqlFile)
	if err != nil {
		clilog.Error.Println("Error reading file: ", err)
		return "", nil, err
	}
	return filepath.Base(gqlFile), schemaFile, nil
}

func readSchemaURL() (string, []byte, error) {
	u, err := url.Parse(gqlURI)
	if err != nil {
		clilog.Error.Println("Error reading uri: ", err)
		return "", nil, err
	}
	resp, err := apiclient.DownloadFile(gqlURI, false)
	if err != nil {
		clilog.Error.Println("Error downloading file: ", err)
		return "", nil, err
	}
	if resp != nil {
		defer resp.Body.Close()
	}

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		clilog.Error.Println("error in response: ", err)
		return "", nil, err
	}
	return path.Base(u.Path), respBody, err
}

func getKeyNameAndLocation() (location string, key string, err error) {
	if apiKeyLocation == "" {
		return "", "", nil
	}

	apikey := strings.Split(apiKeyLocation, ".")
	if len(apikey) != 3 {
		return "", "", fmt.Errorf("api key location must be of the form request.header.foo or request.queryparam.bar")
	}
	return apikey[1], apikey[2], nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/timeredbull/tsuru/cmd"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

type Service struct{}

func (s *Service) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "service",
		Usage:   "service (list)",
		Desc:    "manage your services",
		MinArgs: 1,
	}
}

func (s *Service) Subcommands() map[string]interface{} {
	return map[string]interface{}{
		"list": &ServiceList{},
		"add":  &ServiceAdd{},
	}
}

type ServiceList struct{}

func (s *ServiceList) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "list",
		Usage: "service list",
		Desc:  "Get all available services, and user's instances for this services",
	}
}

func (s *ServiceList) Run(ctx *cmd.Context, client cmd.Doer) error {
	req, err := http.NewRequest("GET", cmd.GetUrl("/services"), nil)
	if err != nil {
		return err
	}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var body map[string][]string
	err = json.Unmarshal(b, &body)
	if err != nil {
		return err
	}
	if len(body) == 0 {
		return nil
	}
	table := cmd.NewTable()
	table.Headers = cmd.Row([]string{"Service", "Instances"})
	for s, i := range body {
		instances := strings.Join(i, ", ")
		table.AddRow(cmd.Row([]string{s, instances}))
	}
	content := table.Bytes()
	n, err := ctx.Stdout.Write(content)
	if n != len(content) {
		return errors.New("Failed to write the output of the command")
	}
	return err
}

type ServiceAdd struct{}

func (sa *ServiceAdd) Info() *cmd.Info {
	usage := `service add appname serviceinstancename servicename
    e.g.:
    $ service add tsuru tsuru_db mongodb`
	return &cmd.Info{
		Name:    "add",
		Usage:   usage,
		Desc:    "Create a service instance to one or more apps make use of.",
		MinArgs: 3,
	}
}

func (sa *ServiceAdd) Run(ctx *cmd.Context, client cmd.Doer) error {
	appName, instName, srvName := ctx.Args[0], ctx.Args[1], ctx.Args[2]
	fmtBody := fmt.Sprintf(`{"app": %s, "name": %s, "service_name": %s}`, appName, instName, srvName)
	b := bytes.NewBufferString(fmtBody)
	url := cmd.GetUrl("/service-instances")
	request, err := http.NewRequest("POST", url, b)
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	io.WriteString(ctx.Stdout, string(result))
	return nil
}
<commit_msg>Changing service instance creating url in service cli<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/timeredbull/tsuru/cmd"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

type Service struct{}

func (s *Service) Info() *cmd.Info {
	return &cmd.Info{
		Name:    "service",
		Usage:   "service (list)",
		Desc:    "manage your services",
		MinArgs: 1,
	}
}

func (s *Service) Subcommands() map[string]interface{} {
	return map[string]interface{}{
		"list": &ServiceList{},
		"add":  &ServiceAdd{},
	}
}

type ServiceList struct{}

func (s *ServiceList) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "list",
		Usage: "service list",
		Desc:  "Get all available services, and user's instances for this services",
	}
}

func (s *ServiceList) Run(ctx *cmd.Context, client cmd.Doer) error {
	req, err := http.NewRequest("GET", cmd.GetUrl("/services"), nil)
	if err != nil {
		return err
	}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var body map[string][]string
	err = json.Unmarshal(b, &body)
	if err != nil {
		return err
	}
	if len(body) == 0 {
		return nil
	}
	table := cmd.NewTable()
	table.Headers = cmd.Row([]string{"Service", "Instances"})
	for s, i := range body {
		instances := strings.Join(i, ", ")
		table.AddRow(cmd.Row([]string{s, instances}))
	}
	content := table.Bytes()
	n, err := ctx.Stdout.Write(content)
	if n != len(content) {
		return errors.New("Failed to write the output of the command")
	}
	return err
}

type ServiceAdd struct{}

func (sa *ServiceAdd) Info() *cmd.Info {
	usage := `service add appname serviceinstancename servicename
    e.g.:
    $ service add tsuru tsuru_db mongodb`
	return &cmd.Info{
		Name:    "add",
		Usage:   usage,
		Desc:    "Create a service instance to one or more apps make use of.",
		MinArgs: 3,
	}
}

func (sa *ServiceAdd) Run(ctx *cmd.Context, client cmd.Doer) error {
	appName, instName, srvName := ctx.Args[0], ctx.Args[1], ctx.Args[2]
	fmtBody := fmt.Sprintf(`{"app": %s, "name": %s, "service_name": %s}`, appName, instName, srvName)
	b := bytes.NewBufferString(fmtBody)
	url := cmd.GetUrl("/services/instances")
	request, err := http.NewRequest("POST", url, b)
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	io.WriteString(ctx.Stdout, string(result))
	return nil
}
<|endoftext|>