<commit_before>/*
Copyright 2018 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 main

import (
	"fmt"

	"gopkg.in/yaml.v2"
)

const (
	executorImage           = "executor-image"
	dockerImage             = "gcr.io/cloud-builders/docker"
	ubuntuImage             = "ubuntu"
	testRepo                = "gcr.io/kaniko-test/"
	dockerPrefix            = "docker-"
	kanikoPrefix            = "kaniko-"
	daemonPrefix            = "daemon://"
	containerDiffOutputFile = "container-diff.json"
	kanikoTestBucket        = "kaniko-test-bucket"
	buildcontextPath        = "/workspace/integration_tests"
	dockerfilesPath         = "/workspace/integration_tests/dockerfiles"
	onbuildBaseImage        = testRepo + "onbuild-base:latest"
)

var fileTests = []struct {
	description         string
	dockerfilePath      string
	configPath          string
	dockerContext       string
	kanikoContext       string
	kanikoContextBucket bool
	repo                string
	snapshotMode        string
}{
	{
		description:    "test extract filesystem",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_extract_fs",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_extract_fs.json",
		dockerContext:  dockerfilesPath,
		kanikoContext:  dockerfilesPath,
		repo:           "extract-filesystem",
		snapshotMode:   "time",
	},
	{
		description:    "test run",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_run",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_run.json",
		dockerContext:  dockerfilesPath,
		kanikoContext:  dockerfilesPath,
		repo:           "test-run",
	},
	{
		description:    "test run no files changed",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_run_2",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_run_2.json",
		dockerContext:  dockerfilesPath,
		kanikoContext:  dockerfilesPath,
		repo:           "test-run-2",
		snapshotMode:   "time",
	},
	{
		description:    "test copy",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_copy",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_copy.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-copy",
		snapshotMode:   "time",
	},
	{
		description:         "test bucket build context",
		dockerfilePath:      "/workspace/integration_tests/dockerfiles/Dockerfile_test_copy",
		configPath:          "/workspace/integration_tests/dockerfiles/config_test_bucket_buildcontext.json",
		dockerContext:       buildcontextPath,
		kanikoContext:       kanikoTestBucket,
		kanikoContextBucket: true,
		repo:                "test-bucket-buildcontext",
	},
	{
		description:    "test workdir",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_workdir",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_workdir.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-workdir",
	},
	{
		description:    "test volume",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_volume",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_volume.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-volume",
	},
	{
		description:    "test add",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_add",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_add.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-add",
	},
	{
		description:    "test mv add",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_mv_add",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_mv_add.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-mv-add",
	},
	{
		description:    "test registry",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_registry",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_registry.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-registry",
	},
	{
		description:    "test onbuild",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_onbuild",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_onbuild.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-onbuild",
	},
	{
		description:    "test multistage",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_multistage",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_multistage.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-multistage",
	},
}

var structureTests = []struct {
	description           string
	dockerfilePath        string
	structureTestYamlPath string
	dockerBuildContext    string
	kanikoContext         string
	repo                  string
}{
	{
		description:           "test env",
		dockerfilePath:        "/workspace/integration_tests/dockerfiles/Dockerfile_test_env",
		repo:                  "test-env",
		dockerBuildContext:    dockerfilesPath,
		kanikoContext:         dockerfilesPath,
		structureTestYamlPath: "/workspace/integration_tests/dockerfiles/test_env.yaml",
	},
	{
		description:           "test metadata",
		dockerfilePath:        "/workspace/integration_tests/dockerfiles/Dockerfile_test_metadata",
		repo:                  "test-metadata",
		dockerBuildContext:    dockerfilesPath,
		kanikoContext:         dockerfilesPath,
		structureTestYamlPath: "/workspace/integration_tests/dockerfiles/test_metadata.yaml",
	},
	{
		description:           "test user command",
		dockerfilePath:        "/workspace/integration_tests/dockerfiles/Dockerfile_test_user_run",
		repo:                  "test-user",
		dockerBuildContext:    dockerfilesPath,
		kanikoContext:         dockerfilesPath,
		structureTestYamlPath: "/workspace/integration_tests/dockerfiles/test_user.yaml",
	},
}

type step struct {
	Name string
	Args []string
	Env  []string
}

type testyaml struct {
	Steps   []step
	Timeout string
}

func main() {

	// First, copy container-diff in
	containerDiffStep := step{
		Name: "gcr.io/cloud-builders/gsutil",
		Args: []string{"cp", "gs://container-diff/latest/container-diff-linux-amd64", "."},
	}
	containerDiffPermissions := step{
		Name: ubuntuImage,
		Args: []string{"chmod", "+x", "container-diff-linux-amd64"},
	}
	structureTestsStep := step{
		Name: "gcr.io/cloud-builders/gsutil",
		Args: []string{"cp", "gs://container-structure-test/latest/container-structure-test", "."},
	}
	structureTestPermissions := step{
		Name: ubuntuImage,
		Args: []string{"chmod", "+x", "container-structure-test"},
	}

	GCSBucketTarBuildContext := step{
		Name: ubuntuImage,
		Args: []string{"tar", "-C", "/workspace/integration_tests/", "-zcvf", "/workspace/context.tar.gz", "."},
	}
	uploadTarBuildContext := step{
		Name: "gcr.io/cloud-builders/gsutil",
		Args: []string{"cp", "/workspace/context.tar.gz", "gs://kaniko-test-bucket/"},
	}

	// Build executor image
	buildExecutorImage := step{
		Name: dockerImage,
		Args: []string{"build", "-t", executorImage, "-f", "deploy/Dockerfile", "."},
	}

	// Build and push onbuild base images
	buildOnbuildImage := step{
		Name: dockerImage,
		Args: []string{"build", "-t", onbuildBaseImage, "-f", "/workspace/integration_tests/dockerfiles/Dockerfile_onbuild_base", "."},
	}
	pushOnbuildBase := step{
		Name: dockerImage,
		Args: []string{"push", onbuildBaseImage},
	}
	y := testyaml{
		Steps: []step{containerDiffStep, containerDiffPermissions, structureTestsStep, structureTestPermissions, GCSBucketTarBuildContext, uploadTarBuildContext, buildExecutorImage,
			buildOnbuildImage, pushOnbuildBase},
		Timeout: "1200s",
	}
	for _, test := range fileTests {
		// First, build the image with docker
		dockerImageTag := testRepo + dockerPrefix + test.repo
		dockerBuild := step{
			Name: dockerImage,
			Args: []string{"build", "-t", dockerImageTag, "-f", test.dockerfilePath, test.dockerContext},
		}

		// Then, buld the image with kaniko
		kanikoImage := testRepo + kanikoPrefix + test.repo
		snapshotMode := ""
		if test.snapshotMode != "" {
			snapshotMode = "--snapshotMode=" + test.snapshotMode
		}
		contextFlag := "--context"
		if test.kanikoContextBucket {
			contextFlag = "--bucket"
		}
		kaniko := step{
			Name: executorImage,
			Args: []string{"--destination", kanikoImage, "--dockerfile", test.dockerfilePath, contextFlag, test.kanikoContext, snapshotMode},
		}

		// Pull the kaniko image
		pullKanikoImage := step{
			Name: dockerImage,
			Args: []string{"pull", kanikoImage},
		}

		daemonDockerImage := daemonPrefix + dockerImageTag
		daemonKanikoImage := daemonPrefix + kanikoImage
		// Run container diff on the images
		args := "container-diff-linux-amd64 diff " + daemonDockerImage + " " + daemonKanikoImage + " --type=file -j >" + containerDiffOutputFile
		containerDiff := step{
			Name: ubuntuImage,
			Args: []string{"sh", "-c", args},
			Env:  []string{"PATH=/workspace:/bin"},
		}

		catContainerDiffOutput := step{
			Name: ubuntuImage,
			Args: []string{"cat", containerDiffOutputFile},
		}
		compareOutputs := step{
			Name: ubuntuImage,
			Args: []string{"cmp", "-b", test.configPath, containerDiffOutputFile},
		}

		y.Steps = append(y.Steps, dockerBuild, kaniko, pullKanikoImage, containerDiff, catContainerDiffOutput, compareOutputs)
	}

	for _, test := range structureTests {

		// First, build the image with docker
		dockerImageTag := testRepo + dockerPrefix + test.repo
		dockerBuild := step{
			Name: dockerImage,
			Args: []string{"build", "-t", dockerImageTag, "-f", test.dockerfilePath, test.dockerBuildContext},
		}

		// Build the image with kaniko
		kanikoImage := testRepo + kanikoPrefix + test.repo
		kaniko := step{
			Name: executorImage,
			Args: []string{"--destination", kanikoImage, "--dockerfile", test.dockerfilePath, "--context", test.kanikoContext},
		}
		// Pull the kaniko image
		pullKanikoImage := step{
			Name: dockerImage,
			Args: []string{"pull", kanikoImage},
		}
		// Run structure tests on the kaniko and docker image
		args := "container-structure-test -image " + kanikoImage + " " + test.structureTestYamlPath
		structureTest := step{
			Name: ubuntuImage,
			Args: []string{"sh", "-c", args},
			Env:  []string{"PATH=/workspace:/bin"},
		}
		args = "container-structure-test -image " + dockerImageTag + " " + test.structureTestYamlPath
		dockerStructureTest := step{
			Name: ubuntuImage,
			Args: []string{"sh", "-c", args},
			Env:  []string{"PATH=/workspace:/bin"},
		}

		y.Steps = append(y.Steps, dockerBuild, kaniko, pullKanikoImage, structureTest, dockerStructureTest)
	}

	d, _ := yaml.Marshal(&y)
	fmt.Println(string(d))
}
<commit_msg>Update to new structure tests<commit_after>/*
Copyright 2018 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 main

import (
	"fmt"

	"gopkg.in/yaml.v2"
)

const (
	executorImage           = "executor-image"
	dockerImage             = "gcr.io/cloud-builders/docker"
	ubuntuImage             = "ubuntu"
	structureTestImage      = "gcr.io/gcp-runtimes/container-structure-test"
	testRepo                = "gcr.io/kaniko-test/"
	dockerPrefix            = "docker-"
	kanikoPrefix            = "kaniko-"
	daemonPrefix            = "daemon://"
	containerDiffOutputFile = "container-diff.json"
	kanikoTestBucket        = "kaniko-test-bucket"
	buildcontextPath        = "/workspace/integration_tests"
	dockerfilesPath         = "/workspace/integration_tests/dockerfiles"
	onbuildBaseImage        = testRepo + "onbuild-base:latest"
)

var fileTests = []struct {
	description         string
	dockerfilePath      string
	configPath          string
	dockerContext       string
	kanikoContext       string
	kanikoContextBucket bool
	repo                string
	snapshotMode        string
}{
	{
		description:    "test extract filesystem",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_extract_fs",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_extract_fs.json",
		dockerContext:  dockerfilesPath,
		kanikoContext:  dockerfilesPath,
		repo:           "extract-filesystem",
		snapshotMode:   "time",
	},
	{
		description:    "test run",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_run",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_run.json",
		dockerContext:  dockerfilesPath,
		kanikoContext:  dockerfilesPath,
		repo:           "test-run",
	},
	{
		description:    "test run no files changed",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_run_2",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_run_2.json",
		dockerContext:  dockerfilesPath,
		kanikoContext:  dockerfilesPath,
		repo:           "test-run-2",
		snapshotMode:   "time",
	},
	{
		description:    "test copy",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_copy",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_copy.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-copy",
		snapshotMode:   "time",
	},
	{
		description:         "test bucket build context",
		dockerfilePath:      "/workspace/integration_tests/dockerfiles/Dockerfile_test_copy",
		configPath:          "/workspace/integration_tests/dockerfiles/config_test_bucket_buildcontext.json",
		dockerContext:       buildcontextPath,
		kanikoContext:       kanikoTestBucket,
		kanikoContextBucket: true,
		repo:                "test-bucket-buildcontext",
	},
	{
		description:    "test workdir",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_workdir",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_workdir.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-workdir",
	},
	{
		description:    "test volume",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_volume",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_volume.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-volume",
	},
	{
		description:    "test add",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_add",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_add.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-add",
	},
	{
		description:    "test mv add",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_mv_add",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_mv_add.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-mv-add",
	},
	{
		description:    "test registry",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_registry",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_registry.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-registry",
	},
	{
		description:    "test onbuild",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_onbuild",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_onbuild.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-onbuild",
	},
	{
		description:    "test multistage",
		dockerfilePath: "/workspace/integration_tests/dockerfiles/Dockerfile_test_multistage",
		configPath:     "/workspace/integration_tests/dockerfiles/config_test_multistage.json",
		dockerContext:  buildcontextPath,
		kanikoContext:  buildcontextPath,
		repo:           "test-multistage",
	},
}

var structureTests = []struct {
	description           string
	dockerfilePath        string
	structureTestYamlPath string
	dockerBuildContext    string
	kanikoContext         string
	repo                  string
}{
	{
		description:           "test env",
		dockerfilePath:        "/workspace/integration_tests/dockerfiles/Dockerfile_test_env",
		repo:                  "test-env",
		dockerBuildContext:    dockerfilesPath,
		kanikoContext:         dockerfilesPath,
		structureTestYamlPath: "/workspace/integration_tests/dockerfiles/test_env.yaml",
	},
	{
		description:           "test metadata",
		dockerfilePath:        "/workspace/integration_tests/dockerfiles/Dockerfile_test_metadata",
		repo:                  "test-metadata",
		dockerBuildContext:    dockerfilesPath,
		kanikoContext:         dockerfilesPath,
		structureTestYamlPath: "/workspace/integration_tests/dockerfiles/test_metadata.yaml",
	},
	{
		description:           "test user command",
		dockerfilePath:        "/workspace/integration_tests/dockerfiles/Dockerfile_test_user_run",
		repo:                  "test-user",
		dockerBuildContext:    dockerfilesPath,
		kanikoContext:         dockerfilesPath,
		structureTestYamlPath: "/workspace/integration_tests/dockerfiles/test_user.yaml",
	},
}

type step struct {
	Name string
	Args []string
	Env  []string
}

type testyaml struct {
	Steps   []step
	Timeout string
}

func main() {

	// First, copy container-diff in
	containerDiffStep := step{
		Name: "gcr.io/cloud-builders/gsutil",
		Args: []string{"cp", "gs://container-diff/latest/container-diff-linux-amd64", "."},
	}
	containerDiffPermissions := step{
		Name: ubuntuImage,
		Args: []string{"chmod", "+x", "container-diff-linux-amd64"},
	}
	GCSBucketTarBuildContext := step{
		Name: ubuntuImage,
		Args: []string{"tar", "-C", "/workspace/integration_tests/", "-zcvf", "/workspace/context.tar.gz", "."},
	}
	uploadTarBuildContext := step{
		Name: "gcr.io/cloud-builders/gsutil",
		Args: []string{"cp", "/workspace/context.tar.gz", "gs://kaniko-test-bucket/"},
	}

	// Build executor image
	buildExecutorImage := step{
		Name: dockerImage,
		Args: []string{"build", "-t", executorImage, "-f", "deploy/Dockerfile", "."},
	}

	// Build and push onbuild base images
	buildOnbuildImage := step{
		Name: dockerImage,
		Args: []string{"build", "-t", onbuildBaseImage, "-f", "/workspace/integration_tests/dockerfiles/Dockerfile_onbuild_base", "."},
	}
	pushOnbuildBase := step{
		Name: dockerImage,
		Args: []string{"push", onbuildBaseImage},
	}
	y := testyaml{
		Steps: []step{containerDiffStep, containerDiffPermissions, GCSBucketTarBuildContext, uploadTarBuildContext, buildExecutorImage,
			buildOnbuildImage, pushOnbuildBase},
		Timeout: "1200s",
	}
	for _, test := range fileTests {
		// First, build the image with docker
		dockerImageTag := testRepo + dockerPrefix + test.repo
		dockerBuild := step{
			Name: dockerImage,
			Args: []string{"build", "-t", dockerImageTag, "-f", test.dockerfilePath, test.dockerContext},
		}

		// Then, buld the image with kaniko
		kanikoImage := testRepo + kanikoPrefix + test.repo
		snapshotMode := ""
		if test.snapshotMode != "" {
			snapshotMode = "--snapshotMode=" + test.snapshotMode
		}
		contextFlag := "--context"
		if test.kanikoContextBucket {
			contextFlag = "--bucket"
		}
		kaniko := step{
			Name: executorImage,
			Args: []string{"--destination", kanikoImage, "--dockerfile", test.dockerfilePath, contextFlag, test.kanikoContext, snapshotMode},
		}

		// Pull the kaniko image
		pullKanikoImage := step{
			Name: dockerImage,
			Args: []string{"pull", kanikoImage},
		}

		daemonDockerImage := daemonPrefix + dockerImageTag
		daemonKanikoImage := daemonPrefix + kanikoImage
		// Run container diff on the images
		args := "container-diff-linux-amd64 diff " + daemonDockerImage + " " + daemonKanikoImage + " --type=file -j >" + containerDiffOutputFile
		containerDiff := step{
			Name: ubuntuImage,
			Args: []string{"sh", "-c", args},
			Env:  []string{"PATH=/workspace:/bin"},
		}

		catContainerDiffOutput := step{
			Name: ubuntuImage,
			Args: []string{"cat", containerDiffOutputFile},
		}
		compareOutputs := step{
			Name: ubuntuImage,
			Args: []string{"cmp", "-b", test.configPath, containerDiffOutputFile},
		}

		y.Steps = append(y.Steps, dockerBuild, kaniko, pullKanikoImage, containerDiff, catContainerDiffOutput, compareOutputs)
	}

	for _, test := range structureTests {

		// First, build the image with docker
		dockerImageTag := testRepo + dockerPrefix + test.repo
		dockerBuild := step{
			Name: dockerImage,
			Args: []string{"build", "-t", dockerImageTag, "-f", test.dockerfilePath, test.dockerBuildContext},
		}

		// Build the image with kaniko
		kanikoImage := testRepo + kanikoPrefix + test.repo
		kaniko := step{
			Name: executorImage,
			Args: []string{"--destination", kanikoImage, "--dockerfile", test.dockerfilePath, "--context", test.kanikoContext},
		}
		// Pull the kaniko image
		pullKanikoImage := step{
			Name: dockerImage,
			Args: []string{"pull", kanikoImage},
		}
		// Run structure tests on the kaniko and docker image
		kanikoStructureTest := step{
			Name: structureTestImage,
			Args: []string{"test", "--image", kanikoImage, "--config", test.structureTestYamlPath},
		}
		dockerStructureTest := step{
			Name: structureTestImage,
			Args: []string{"test", "--image", dockerImageTag, "--config", test.structureTestYamlPath},
		}
		y.Steps = append(y.Steps, dockerBuild, kaniko, pullKanikoImage, kanikoStructureTest, dockerStructureTest)
	}

	d, _ := yaml.Marshal(&y)
	fmt.Println(string(d))
}
<|endoftext|>


<commit_before>package Templates

import (
	"net/http"
	"Utils"
	"io"
	"strconv"
	"os"
	"UserManager"
	"Flags"
	"SessionManager"
	"github.com/pkg/errors"
	"log"
	"path/filepath"
	"mime/multipart"
	"io/ioutil"
	"time"
)

type IndexData struct {
	Name       string
	FolderPath string
	ObjectPath string
	Size       int64
	Date       time.Time
	Image      string
	IsFolder   bool
}

type IndexDaten []IndexData

func IndexHandler(w http.ResponseWriter, r *http.Request, path string) {

	var Data IndexDaten

	userPath := getAbsUserPath(r)
	wantedPath := ""
	wantedPath = r.URL.Query().Get("path")

	fullPath := userPath + wantedPath

	files, _ := ioutil.ReadDir(fullPath)

	for _, f := range files {
		if f.IsDir() {
			Data = append(Data, IndexData{Name:f.Name(), FolderPath: wantedPath, Size:f.Size(), Date:f.ModTime(), Image:"folder", ObjectPath: wantedPath + f.Name(),IsFolder:true})
		} else {
			Data = append(Data, IndexData{Name:f.Name(), FolderPath: wantedPath, Size:f.Size(), Date:f.ModTime(), Image:"file", ObjectPath: wantedPath +"/"+ f.Name(),IsFolder:false})
		}
	}

	RenderTemplate(w, path, &Data)
}

func DeleteDataHandler(w http.ResponseWriter, r *http.Request) {

	path := r.URL.Query().Get("filepath")
	fullPath := getAbsUserPath(r) + path
	Utils.LogDebug("File Deleted by DeleteDataHandler:	" + fullPath)
	os.Remove(fullPath)
	http.StatusText(http.StatusNoContent)

}

func DownloadDataHandler(w http.ResponseWriter, r *http.Request) {

	path := r.URL.Query().Get("filepath")
	fullPath := getAbsUserPath(r) + path
	Utils.LogDebug("File Accessed by DownloadDataHandler:	" + fullPath)
	http.ServeFile(w, r, fullPath)

}

func DownloadBasicAuthDataHandler(w http.ResponseWriter, r *http.Request) {
	email, _, _ := r.BasicAuth()
	usr, present, err := UserManager.ReadUser(email)
	Utils.HandlePrint(err)
	if present {
		path := r.URL.Query().Get("filepath")

		fullPath := Flags.GetWorkDir() + "/" + strconv.Itoa(int(usr.UID)) + "/" + path
		Utils.LogDebug("File Accessed by DownloadBasicAuthDataHandler:	" + fullPath)
		http.ServeFile(w, r, fullPath)
	} else {
		Utils.HandlePanic(errors.New("Inconsistency in User Storage!"))
	}
}

func NewFolderHandler(w http.ResponseWriter, r *http.Request) {
	//Todo tested yet
	//read folderName
	r.ParseForm()
	folderName := r.FormValue("folderName")
	targetPath := r.FormValue("filepath")

	//join Foldername to UserPath
	path := filepath.Join(getAbsUserPath(r)+targetPath, folderName)

	//Try make Dir
	err := os.MkdirAll(path, os.ModePerm)
	if err != nil {
		Utils.LogError("Error creating directory")
		log.Println(err)
		return
	}
}

func UploadDataDataHandler(w http.ResponseWriter, r *http.Request) {

	var (
		status int
		err error
	)
	defer func() {
		if nil != err {
			http.Error(w, err.Error(), status)
		}
	}()
	// parse request
	const _24K = (1 << 20) * 24
	if err = r.ParseMultipartForm(_24K); nil != err {
		status = http.StatusInternalServerError
		return
	}
	for _, fheaders := range r.MultipartForm.File {
		for _, hdr := range fheaders {
			// open uploaded
			var infile multipart.File
			if infile, err = hdr.Open(); nil != err {
				status = http.StatusInternalServerError
				return
			}
			// open destination
			var outfile *os.File
			os.Chdir("/")
			Utils.LogDebug("Uploading File to: 	" + getAbsUserPath(r) + hdr.Filename)
			if outfile, err = os.Create(getAbsUserPath(r) + hdr.Filename); nil != err {
				status = http.StatusInternalServerError
				return
			}
			// 32K buffer copy
			var written int64
			if written, err = io.Copy(outfile, infile); nil != err {
				status = http.StatusInternalServerError
				return
			}
			status = http.StatusCreated
			w.Write([]byte("uploaded file:" + hdr.Filename + ";length:" + strconv.Itoa(int(written))))
		}
	}

}

func getAbsUserPath(r *http.Request) string {
	cookie, err := r.Cookie("Session")
	Utils.HandlePrint(err)
	session, present := SessionManager.GetSessionRecord(cookie.Value)
	if present {
		user, present, err := UserManager.ReadUser(session.Email)
		Utils.HandlePrint(err)
		if present {
			return Flags.GetWorkDir() + "/" + strconv.Itoa(int(user.UID)) + "/"
		} else {
			Utils.HandlePanic(errors.New("Inconsistency in Session to User Storage!"))
		}
	} else {
		Utils.HandlePanic(errors.New("Inconsistency in Session Storage !"))
	}
	return ""
}<commit_msg>Navigieren in nächste Ordnerebene<commit_after>package Templates

import (
	"net/http"
	"Utils"
	"io"
	"strconv"
	"os"
	"UserManager"
	"Flags"
	"SessionManager"
	"github.com/pkg/errors"
	"log"
	"path/filepath"
	"mime/multipart"
	"io/ioutil"
	"time"
)

type IndexData struct {
	Name       string
	FolderPath string
	ObjectPath string
	Size       int64
	Date       time.Time
	Image      string
	IsFolder   bool
}

type IndexDaten []IndexData

func IndexHandler(w http.ResponseWriter, r *http.Request, path string) {

	var Data IndexDaten

	userPath := getAbsUserPath(r)
	wantedPath := ""
	wantedPath = r.URL.Query().Get("path")

	fullPath := userPath + wantedPath

	files, _ := ioutil.ReadDir(fullPath)

	for _, f := range files {
		if f.IsDir() {
			Data = append(Data, IndexData{Name:f.Name(), FolderPath: wantedPath, Size:f.Size(), Date:f.ModTime(), Image:"folder", ObjectPath: wantedPath +"/"+ f.Name(),IsFolder:true})
		} else {
			Data = append(Data, IndexData{Name:f.Name(), FolderPath: wantedPath, Size:f.Size(), Date:f.ModTime(), Image:"file", ObjectPath: wantedPath +"/"+ f.Name(),IsFolder:false})
		}
	}

	RenderTemplate(w, path, &Data)
}

func DeleteDataHandler(w http.ResponseWriter, r *http.Request) {

	path := r.URL.Query().Get("filepath")
	fullPath := getAbsUserPath(r) + path
	Utils.LogDebug("File Deleted by DeleteDataHandler:	" + fullPath)
	os.Remove(fullPath)
	http.StatusText(http.StatusNoContent)

}

func DownloadDataHandler(w http.ResponseWriter, r *http.Request) {

	path := r.URL.Query().Get("filepath")
	fullPath := getAbsUserPath(r) + path
	Utils.LogDebug("File Accessed by DownloadDataHandler:	" + fullPath)
	http.ServeFile(w, r, fullPath)

}

func DownloadBasicAuthDataHandler(w http.ResponseWriter, r *http.Request) {
	email, _, _ := r.BasicAuth()
	usr, present, err := UserManager.ReadUser(email)
	Utils.HandlePrint(err)
	if present {
		path := r.URL.Query().Get("filepath")

		fullPath := Flags.GetWorkDir() + "/" + strconv.Itoa(int(usr.UID)) + "/" + path
		Utils.LogDebug("File Accessed by DownloadBasicAuthDataHandler:	" + fullPath)
		http.ServeFile(w, r, fullPath)
	} else {
		Utils.HandlePanic(errors.New("Inconsistency in User Storage!"))
	}
}

func NewFolderHandler(w http.ResponseWriter, r *http.Request) {
	//Todo tested yet
	//read folderName
	r.ParseForm()
	folderName := r.FormValue("folderName")
	targetPath := r.FormValue("filepath")

	//join Foldername to UserPath
	path := filepath.Join(getAbsUserPath(r)+targetPath, folderName)

	//Try make Dir
	err := os.MkdirAll(path, os.ModePerm)
	if err != nil {
		Utils.LogError("Error creating directory")
		log.Println(err)
		return
	}
}

func UploadDataDataHandler(w http.ResponseWriter, r *http.Request) {

	var (
		status int
		err error
	)
	defer func() {
		if nil != err {
			http.Error(w, err.Error(), status)
		}
	}()
	// parse request
	const _24K = (1 << 20) * 24
	if err = r.ParseMultipartForm(_24K); nil != err {
		status = http.StatusInternalServerError
		return
	}
	for _, fheaders := range r.MultipartForm.File {
		for _, hdr := range fheaders {
			// open uploaded
			var infile multipart.File
			if infile, err = hdr.Open(); nil != err {
				status = http.StatusInternalServerError
				return
			}
			// open destination
			var outfile *os.File
			os.Chdir("/")
			Utils.LogDebug("Uploading File to: 	" + getAbsUserPath(r) + hdr.Filename)
			if outfile, err = os.Create(getAbsUserPath(r) + hdr.Filename); nil != err {
				status = http.StatusInternalServerError
				return
			}
			// 32K buffer copy
			var written int64
			if written, err = io.Copy(outfile, infile); nil != err {
				status = http.StatusInternalServerError
				return
			}
			status = http.StatusCreated
			w.Write([]byte("uploaded file:" + hdr.Filename + ";length:" + strconv.Itoa(int(written))))
		}
	}

}

func getAbsUserPath(r *http.Request) string {
	cookie, err := r.Cookie("Session")
	Utils.HandlePrint(err)
	session, present := SessionManager.GetSessionRecord(cookie.Value)
	if present {
		user, present, err := UserManager.ReadUser(session.Email)
		Utils.HandlePrint(err)
		if present {
			return Flags.GetWorkDir() + "/" + strconv.Itoa(int(user.UID)) + "/"
		} else {
			Utils.HandlePanic(errors.New("Inconsistency in Session to User Storage!"))
		}
	} else {
		Utils.HandlePanic(errors.New("Inconsistency in Session Storage !"))
	}
	return ""
}<|endoftext|>


<commit_before>package of10

import "net"

type Match struct {
	Wildcards    uint32
	InPort       PortNumber
	EthSrc       net.HardwareAddr
	EthDst       net.HardwareAddr
	VlanId       VlanId
	VlanPriority VlanPriority
	pad1         [1]uint8
	EtherType    EtherType
	IpTos        Dscp
	IpProtocol   ProtocolNumber
	pad2         [2]uint8
	IpSrc        net.IP
	IpDst        net.IP
	NetworkSrc   NetworkPort
	NetworkDst   NetworkPort
}

type VlanId uint16
type VlanPriority uint8
type EtherType uint16
type Dscp uint8
type ProtocolNumber uint8
type NetworkPort uint16
<commit_msg>Declare constant related to wildcard<commit_after>package of10

import "net"

type Match struct {
	Wildcards    Wildcard
	InPort       PortNumber
	EthSrc       net.HardwareAddr
	EthDst       net.HardwareAddr
	VlanId       VlanId
	VlanPriority VlanPriority
	pad1         [1]uint8
	EtherType    EtherType
	IpTos        Dscp
	IpProtocol   ProtocolNumber
	pad2         [2]uint8
	IpSrc        net.IP
	IpDst        net.IP
	NetworkSrc   NetworkPort
	NetworkDst   NetworkPort
}

type Wildcard uint32
type VlanId uint16
type VlanPriority uint8
type EtherType uint16
type Dscp uint8
type ProtocolNumber uint8
type NetworkPort uint16

const (
	OFPFW_IN_PORT Wildcard = 1 << iota
	OFPFW_DL_VLAN
	OFPFW_DL_SRC
	OFPFW_DL_DST
	OFPFW_DL_TYPE
	OFPFW_NW_PROTO
	OFPFW_TP_SRC
	OFPFW_TP_DST

	OFPFW_NW_SRC_SHIFT Wildcard = 8
	OFPFW_NW_SRC_BITS  Wildcard = 6
	OFPFW_NW_SRC_MASK  Wildcard = ((1 << OFPFW_NW_SRC_BITS) - 1) << OFPFW_NW_SRC_SHIFT

	OFPFW_NW_DST_SHIFT Wildcard = 16
	OFPFW_NW_DST_BITS  Wildcard = 6
	OFPFW_NW_DST_MASK  Wildcard = ((1 << OFPFW_NW_DST_BITS) - 1) << OFPFW_NW_DST_SHIFT
	OFPFW_NW_DST_ALL   Wildcard = 32 << OFPFW_NW_DST_SHIFT

	OFPFW_DL_VLAN_PCP Wildcard = 1 << 20
	OFPFW_NW_TOS      Wildcard = 1 << 21

	OFPFW_ALL Wildcard = ((1 << 22) - 1)
)
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"strconv"
	"encoding/json"
	"encoding/base64"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/util"
)

type Chaincode struct { }

type ChaincodeFunctions struct {
	stub shim.ChaincodeStubInterface
}

func main() {
	err := shim.Start(new(Chaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

// Init resets all the things
func (t Chaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	_ = stub.PutState("dealStatus", []byte("draft")) // Possible Values [draft, open, closed, allocated]
	_ = stub.PutState("orderbook", []byte("{}"))
	return nil, nil
}

func (t Chaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "addOrder" {
		investor := args[0]
		ioi, err := strconv.ParseFloat(args[1], 64)
		if err != nil {
	        return nil, errors.New("Failed to parse " + args[1] + " as a float64")
    	}
		return fns.AddOrder(investor, ioi)
	} else if function == "allocateOrder" {
		investor := args[0]
		alloc, err := strconv.ParseFloat(args[1], 64)
		if err != nil {
	        return nil, errors.New("Failed to parse " + args[1] + " as a float64")
    	}
		return fns.AllocateOrder(investor, alloc)
	} else if function == "updateDealStatus" {
		status := args[0]
		return fns.UpdateDealStatus(status)
	}
	fmt.Println("invoke did not find func: " + function)

	return nil, errors.New("Received unknown function invocation: " + function)
}

func (t Chaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "getRole" {
		return fns.GetRole()
	} else if function == "getOrder" {
		investor := args[0]
		return fns.GetOrder(investor)
	} else if function == "getOrderbook" {
		return fns.GetOrderbook()
	} else if function == "echo" {
		address := args[0]
		f := "echo"
		arg := args[1]
		return fns.Echo(address, f, arg)
	} else if function == "getDealStatus" {
		return fns.GetDealStatus()
	}
	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query: " + function)
}

type Order struct {
	Investor	string 		`json:"investor"`
	Ioi 		float64 	`json:"ioi"`
	Alloc 		float64		`json:"alloc"`
}

// Public Functions

func (c ChaincodeFunctions) GetRole() ([]byte, error) {
    role, err := c.stub.ReadCertAttribute("username")
    if err != nil { return nil, errors.New("Couldn't get attribute 'role'. Error: " + err.Error()) }
    str := base64.StdEncoding.EncodeToString(role)
	return []byte(str), nil
}

func (c ChaincodeFunctions) GetDealStatus() ([]byte, error)  {
	dealStatus, _ := c.stub.GetState("dealStatus")
	return dealStatus, nil
}

func (c ChaincodeFunctions) UpdateDealStatus(dealStatus string) ([]byte, error)  {
	_ = c.stub.PutState("dealStatus", []byte(dealStatus))
	c.stub.SetEvent("Book Status Change", []byte("{\"status\":\"" + dealStatus + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) AddOrder(investor string, ioi float64) ([]byte, error)  {
	dealStatus, _ := c.GetDealStatus()
	if(string(dealStatus) != "open") {
		c.stub.SetEvent("Permission Denied", []byte("{\"reason\":\"book is not open\"}"))
		return nil, errors.New("Orders cannot be placed unless deal status is 'Open'")
	}
	order := Order{Investor: investor, Ioi: ioi, Alloc: 0.0}
	c.saveOrderToBlockChain(order)
	c.stub.SetEvent("Order Added", []byte("{\"investor\":\"" + investor + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) GetOrder(investor string) ([]byte, error) {
	orderJson := c.getOrderAsJsonFromBlockchain(investor)
	return []byte(orderJson), nil
}

func (c ChaincodeFunctions) GetOrderbook() ([]byte, error) {
	orderbookJson, _ := c.stub.GetState("orderbook")
	return []byte(orderbookJson), nil
}

func (c ChaincodeFunctions) AllocateOrder(investor string, alloc float64) ([]byte, error) {
	order := c.getOrderFromBlockChain(investor)
	order.Alloc = alloc
	c.saveOrderToBlockChain(order)
	c.stub.SetEvent("Order Allocated", []byte("{\"investor\":\"" + investor + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) Echo(address string, f string, arg string) ([]byte, error) {
	invokeArgs := util.ToChaincodeArgs(f, arg)
	return c.stub.QueryChaincode(address, invokeArgs)
}

// Private Functions

func (c ChaincodeFunctions) getOrderAsJsonFromBlockchain(investor string) string {
	order := c.getOrderFromBlockChain(investor)
	orderJson, _ := json.Marshal(order)
	return string(orderJson)
}

func (c ChaincodeFunctions) getOrderFromBlockChain(investor string) Order {
	orderbook := c.getOrderbookFromBlockChain()
	return orderbook[investor]
}

func (c ChaincodeFunctions) saveOrderToBlockChain(order Order) {
	orderbook := c.getOrderbookFromBlockChain()
	orderbook[order.Investor] = order
	c.saveOrderbookToBlockChain(orderbook)
}

func (c ChaincodeFunctions) getOrderbookFromBlockChain() map[string]Order {
	orderbookJson, _ := c.stub.GetState("orderbook")
	var orderbook map[string]Order
	_ = json.Unmarshal(orderbookJson, &orderbook)
	return orderbook
}

func (c ChaincodeFunctions) saveOrderbookToBlockChain(orderbook map[string]Order) {
	orderbookJson, _ := json.Marshal(orderbook)
	_ = c.stub.PutState("orderbook", []byte(orderbookJson))
}<commit_msg>batch check-in<commit_after>package main

import (
	"errors"
	"fmt"
	"strconv"
	"encoding/json"
	"encoding/base64"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/util"
)

type Chaincode struct { }

type ChaincodeFunctions struct {
	stub shim.ChaincodeStubInterface
}

func main() {
	err := shim.Start(new(Chaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

// Init resets all the things
func (t Chaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	_ = stub.PutState("dealStatus", []byte("draft")) // Possible Values [draft, open, closed, allocated]
	_ = stub.PutState("orderbook", []byte("{}"))
	return nil, nil
}

func (t Chaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "addOrder" {
		investor := args[0]
		ioi, err := strconv.ParseFloat(args[1], 64)
		if err != nil {
	        return nil, errors.New("Failed to parse " + args[1] + " as a float64")
    	}
		return fns.AddOrder(investor, ioi)
	} else if function == "allocateOrder" {
		investor := args[0]
		alloc, err := strconv.ParseFloat(args[1], 64)
		if err != nil {
	        return nil, errors.New("Failed to parse " + args[1] + " as a float64")
    	}
		return fns.AllocateOrder(investor, alloc)
	} else if function == "updateDealStatus" {
		status := args[0]
		return fns.UpdateDealStatus(status)
	}
	fmt.Println("invoke did not find func: " + function)

	return nil, errors.New("Received unknown function invocation: " + function)
}

func (t Chaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)
	fns := ChaincodeFunctions{stub}
	if function == "getRole" {
		return fns.GetRole()
	} else if function == "getOrder" {
		investor := args[0]
		return fns.GetOrder(investor)
	} else if function == "getOrderbook" {
		return fns.GetOrderbook()
	} else if function == "echo" {
		address := args[0]
		f := "echo"
		arg := args[1]
		return fns.Echo(address, f, arg)
	} else if function == "getDealStatus" {
		return fns.GetDealStatus()
	}
	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query: " + function)
}

type Order struct {
	Investor	string 		`json:"investor"`
	Ioi 		float64 	`json:"ioi"`
	Alloc 		float64		`json:"alloc"`
}

// Public Functions

func (c ChaincodeFunctions) GetRole() ([]byte, error) {
    role, err := c.stub.ReadCertAttribute("account")
    if err != nil { return nil, errors.New("Couldn't get attribute 'role'. Error: " + err.Error()) }
    str := base64.StdEncoding.EncodeToString(role)
	return []byte(str), nil
}

func (c ChaincodeFunctions) GetDealStatus() ([]byte, error)  {
	dealStatus, _ := c.stub.GetState("dealStatus")
	return dealStatus, nil
}

func (c ChaincodeFunctions) UpdateDealStatus(dealStatus string) ([]byte, error)  {
	_ = c.stub.PutState("dealStatus", []byte(dealStatus))
	c.stub.SetEvent("Book Status Change", []byte("{\"status\":\"" + dealStatus + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) AddOrder(investor string, ioi float64) ([]byte, error)  {
	dealStatus, _ := c.GetDealStatus()
	if(string(dealStatus) != "open") {
		c.stub.SetEvent("Permission Denied", []byte("{\"reason\":\"book is not open\"}"))
		return nil, errors.New("Orders cannot be placed unless deal status is 'Open'")
	}
	order := Order{Investor: investor, Ioi: ioi, Alloc: 0.0}
	c.saveOrderToBlockChain(order)
	c.stub.SetEvent("Order Added", []byte("{\"investor\":\"" + investor + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) GetOrder(investor string) ([]byte, error) {
	orderJson := c.getOrderAsJsonFromBlockchain(investor)
	return []byte(orderJson), nil
}

func (c ChaincodeFunctions) GetOrderbook() ([]byte, error) {
	orderbookJson, _ := c.stub.GetState("orderbook")
	return []byte(orderbookJson), nil
}

func (c ChaincodeFunctions) AllocateOrder(investor string, alloc float64) ([]byte, error) {
	order := c.getOrderFromBlockChain(investor)
	order.Alloc = alloc
	c.saveOrderToBlockChain(order)
	c.stub.SetEvent("Order Allocated", []byte("{\"investor\":\"" + investor + "\"}"))
	return nil, nil
}

func (c ChaincodeFunctions) Echo(address string, f string, arg string) ([]byte, error) {
	invokeArgs := util.ToChaincodeArgs(f, arg)
	return c.stub.QueryChaincode(address, invokeArgs)
}

// Private Functions

func (c ChaincodeFunctions) getOrderAsJsonFromBlockchain(investor string) string {
	order := c.getOrderFromBlockChain(investor)
	orderJson, _ := json.Marshal(order)
	return string(orderJson)
}

func (c ChaincodeFunctions) getOrderFromBlockChain(investor string) Order {
	orderbook := c.getOrderbookFromBlockChain()
	return orderbook[investor]
}

func (c ChaincodeFunctions) saveOrderToBlockChain(order Order) {
	orderbook := c.getOrderbookFromBlockChain()
	orderbook[order.Investor] = order
	c.saveOrderbookToBlockChain(orderbook)
}

func (c ChaincodeFunctions) getOrderbookFromBlockChain() map[string]Order {
	orderbookJson, _ := c.stub.GetState("orderbook")
	var orderbook map[string]Order
	_ = json.Unmarshal(orderbookJson, &orderbook)
	return orderbook
}

func (c ChaincodeFunctions) saveOrderbookToBlockChain(orderbook map[string]Order) {
	orderbookJson, _ := json.Marshal(orderbook)
	_ = c.stub.PutState("orderbook", []byte(orderbookJson))
}<|endoftext|>


<commit_before>package fake_connection

import (
	"io"
	"sync"

	"github.com/cloudfoundry-incubator/garden/warden"
)

type FakeConnection struct {
	lock *sync.RWMutex

	closed bool

	disconnected chan struct{}

	WhenGettingCapacity func() (warden.Capacity, error)

	created      []warden.ContainerSpec
	WhenCreating func(spec warden.ContainerSpec) (string, error)

	listedProperties []warden.Properties
	WhenListing      func(props warden.Properties) ([]string, error)

	destroyed      []string
	WhenDestroying func(handle string) error

	stopped      map[string][]StopSpec
	WhenStopping func(handle string, background, kill bool) error

	WhenGettingInfo func(handle string) (warden.ContainerInfo, error)

	copiedIn      map[string][]CopyInSpec
	WhenCopyingIn func(handle string, src, dst string) error

	copiedOut      map[string][]CopyOutSpec
	WhenCopyingOut func(handle string, src, dst, owner string) error

	streamedIn      map[string][]StreamInSpec
	WhenStreamingIn func(handle string, dst string) (io.WriteCloser, error)

	streamedOut      map[string][]StreamOutSpec
	WhenStreamingOut func(handle string, src string) (io.Reader, error)

	limitedBandwidth      map[string][]warden.BandwidthLimits
	WhenLimitingBandwidth func(handle string, limits warden.BandwidthLimits) (warden.BandwidthLimits, error)

	limitedCPU      map[string][]warden.CPULimits
	WhenLimitingCPU func(handle string, limits warden.CPULimits) (warden.CPULimits, error)

	limitedDisk      map[string][]warden.DiskLimits
	WhenLimitingDisk func(handle string, limits warden.DiskLimits) (warden.DiskLimits, error)

	limitedMemory      map[string][]warden.MemoryLimits
	WhenLimitingMemory func(handle string, limit warden.MemoryLimits) (warden.MemoryLimits, error)

	spawnedProcesses map[string][]warden.ProcessSpec
	WhenRunning      func(handle string, spec warden.ProcessSpec) (uint32, <-chan warden.ProcessStream, error)

	attachedProcesses map[string][]uint32
	WhenAttaching     func(handle string, processID uint32) (<-chan warden.ProcessStream, error)

	netInned      map[string][]NetInSpec
	WhenNetInning func(handle string, hostPort, containerPort uint32) (uint32, uint32, error)

	netOuted      map[string][]NetOutSpec
	WhenNetOuting func(handle string, network string, port uint32) error
}

type StopSpec struct {
	Background bool
	Kill       bool
}

type CopyInSpec struct {
	Source      string
	Destination string
}

type CopyOutSpec struct {
	Source      string
	Destination string
	Owner       string
}

type StreamInSpec struct {
	Destination string
}

type StreamOutSpec struct {
	Source      string
	Destination io.Writer
}

type NetInSpec struct {
	HostPort      uint32
	ContainerPort uint32
}

type NetOutSpec struct {
	Network string
	Port    uint32
}

func New() *FakeConnection {
	return &FakeConnection{
		lock: &sync.RWMutex{},

		disconnected: make(chan struct{}),

		stopped: make(map[string][]StopSpec),

		copiedIn:  make(map[string][]CopyInSpec),
		copiedOut: make(map[string][]CopyOutSpec),

		streamedIn:  make(map[string][]StreamInSpec),
		streamedOut: make(map[string][]StreamOutSpec),

		limitedBandwidth: make(map[string][]warden.BandwidthLimits),
		limitedCPU:       make(map[string][]warden.CPULimits),
		limitedDisk:      make(map[string][]warden.DiskLimits),
		limitedMemory:    make(map[string][]warden.MemoryLimits),

		spawnedProcesses:  make(map[string][]warden.ProcessSpec),
		attachedProcesses: make(map[string][]uint32),

		netInned: make(map[string][]NetInSpec),
		netOuted: make(map[string][]NetOutSpec),
	}
}

func (connection *FakeConnection) Close() {
	connection.lock.Lock()
	connection.closed = true
	connection.lock.Unlock()
}

func (connection *FakeConnection) IsClosed() bool {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.closed
}

func (connection *FakeConnection) Disconnected() <-chan struct{} {
	return connection.disconnected
}

func (connection *FakeConnection) NotifyDisconnected() {
	close(connection.disconnected)
}

func (connection *FakeConnection) Capacity() (warden.Capacity, error) {
	if connection.WhenGettingCapacity != nil {
		return connection.WhenGettingCapacity()
	}

	return warden.Capacity{}, nil
}

func (connection *FakeConnection) Create(spec warden.ContainerSpec) (string, error) {
	connection.lock.Lock()
	connection.created = append(connection.created, spec)
	connection.lock.Unlock()

	if connection.WhenCreating != nil {
		return connection.WhenCreating(spec)
	}

	return spec.Handle, nil
}

func (connection *FakeConnection) Created() []warden.ContainerSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.created
}

func (connection *FakeConnection) List(properties warden.Properties) ([]string, error) {
	connection.lock.Lock()
	connection.listedProperties = append(connection.listedProperties, properties)
	connection.lock.Unlock()

	if connection.WhenListing != nil {
		return connection.WhenListing(properties)
	}

	return nil, nil
}

func (connection *FakeConnection) ListedProperties() []warden.Properties {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.listedProperties
}

func (connection *FakeConnection) Destroy(handle string) error {
	connection.lock.Lock()
	connection.destroyed = append(connection.destroyed, handle)
	connection.lock.Unlock()

	if connection.WhenDestroying != nil {
		return connection.WhenDestroying(handle)
	}

	return nil
}

func (connection *FakeConnection) Destroyed() []string {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.destroyed
}

func (connection *FakeConnection) Stop(handle string, background, kill bool) error {
	connection.lock.Lock()
	connection.stopped[handle] = append(connection.stopped[handle], StopSpec{
		Background: background,
		Kill:       kill,
	})
	connection.lock.Unlock()

	if connection.WhenStopping != nil {
		return connection.WhenStopping(handle, background, kill)
	}

	return nil
}

func (connection *FakeConnection) Stopped(handle string) []StopSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.stopped[handle]
}

func (connection *FakeConnection) Info(handle string) (warden.ContainerInfo, error) {
	if connection.WhenGettingInfo != nil {
		return connection.WhenGettingInfo(handle)
	}

	return warden.ContainerInfo{}, nil
}

func (connection *FakeConnection) CopyIn(handle string, src, dst string) error {
	connection.lock.Lock()
	connection.copiedIn[handle] = append(connection.copiedIn[handle], CopyInSpec{
		Source:      src,
		Destination: dst,
	})
	connection.lock.Unlock()

	if connection.WhenCopyingIn != nil {
		return connection.WhenCopyingIn(handle, src, dst)
	}

	return nil
}

func (connection *FakeConnection) CopiedIn(handle string) []CopyInSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.copiedIn[handle]
}

func (connection *FakeConnection) CopyOut(handle string, src, dst, owner string) error {
	connection.lock.Lock()
	connection.copiedOut[handle] = append(connection.copiedOut[handle], CopyOutSpec{
		Source:      src,
		Destination: dst,
		Owner:       owner,
	})
	connection.lock.Unlock()

	if connection.WhenCopyingOut != nil {
		return connection.WhenCopyingOut(handle, src, dst, owner)
	}

	return nil
}

func (connection *FakeConnection) CopiedOut(handle string) []CopyOutSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.copiedOut[handle]
}

func (connection *FakeConnection) StreamIn(handle string, dstPath string) (io.WriteCloser, error) {
	connection.lock.Lock()
	connection.streamedIn[handle] = append(connection.streamedIn[handle], StreamInSpec{
		Destination: dstPath,
	})
	connection.lock.Unlock()

	if connection.WhenStreamingIn != nil {
		return connection.WhenStreamingIn(handle, dstPath)
	}

	return nil, nil
}

func (connection *FakeConnection) StreamedIn(handle string) []StreamInSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.streamedIn[handle]
}

func (connection *FakeConnection) StreamOut(handle string, srcPath string) (io.Reader, error) {
	connection.lock.Lock()
	connection.streamedOut[handle] = append(connection.streamedOut[handle], StreamOutSpec{
		Source: srcPath,
	})
	connection.lock.Unlock()

	if connection.WhenStreamingOut != nil {
		return connection.WhenStreamingOut(handle, srcPath)
	}

	return nil, nil
}

func (connection *FakeConnection) StreamedOut(handle string) []StreamOutSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.streamedOut[handle]
}

func (connection *FakeConnection) LimitBandwidth(handle string, limits warden.BandwidthLimits) (warden.BandwidthLimits, error) {
	connection.lock.Lock()
	connection.limitedBandwidth[handle] = append(connection.limitedBandwidth[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingBandwidth != nil {
		return connection.WhenLimitingBandwidth(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedBandwidth(handle string) []warden.BandwidthLimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedBandwidth[handle]
}

func (connection *FakeConnection) LimitCPU(handle string, limits warden.CPULimits) (warden.CPULimits, error) {
	connection.lock.Lock()
	connection.limitedCPU[handle] = append(connection.limitedCPU[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingCPU != nil {
		return connection.WhenLimitingCPU(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedCPU(handle string) []warden.CPULimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedCPU[handle]
}

func (connection *FakeConnection) LimitDisk(handle string, limits warden.DiskLimits) (warden.DiskLimits, error) {
	connection.lock.Lock()
	connection.limitedDisk[handle] = append(connection.limitedDisk[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingDisk != nil {
		return connection.WhenLimitingDisk(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedDisk(handle string) []warden.DiskLimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedDisk[handle]
}

func (connection *FakeConnection) LimitMemory(handle string, limits warden.MemoryLimits) (warden.MemoryLimits, error) {
	connection.lock.Lock()
	connection.limitedMemory[handle] = append(connection.limitedMemory[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingMemory != nil {
		return connection.WhenLimitingMemory(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedMemory(handle string) []warden.MemoryLimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedMemory[handle]
}

func (connection *FakeConnection) Run(handle string, spec warden.ProcessSpec) (uint32, <-chan warden.ProcessStream, error) {
	connection.lock.Lock()
	connection.spawnedProcesses[handle] = append(connection.spawnedProcesses[handle], spec)
	connection.lock.Unlock()

	if connection.WhenRunning != nil {
		return connection.WhenRunning(handle, spec)
	}

	return 0, make(chan warden.ProcessStream), nil
}

func (connection *FakeConnection) SpawnedProcesses(handle string) []warden.ProcessSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.spawnedProcesses[handle]
}

func (connection *FakeConnection) Attach(handle string, processID uint32) (<-chan warden.ProcessStream, error) {
	connection.lock.Lock()
	connection.attachedProcesses[handle] = append(connection.attachedProcesses[handle], processID)
	connection.lock.Unlock()

	if connection.WhenAttaching != nil {
		return connection.WhenAttaching(handle, processID)
	}

	return make(chan warden.ProcessStream), nil
}

func (connection *FakeConnection) AttachedProcesses(handle string) []uint32 {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.attachedProcesses[handle]
}

func (connection *FakeConnection) NetIn(handle string, hostPort, containerPort uint32) (uint32, uint32, error) {
	connection.lock.Lock()
	connection.netInned[handle] = append(connection.netInned[handle], NetInSpec{
		HostPort:      hostPort,
		ContainerPort: containerPort,
	})
	connection.lock.Unlock()

	if connection.WhenNetInning != nil {
		return connection.WhenNetInning(handle, hostPort, containerPort)
	}

	return 0, 0, nil
}

func (connection *FakeConnection) NetInned(handle string) []NetInSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.netInned[handle]
}

func (connection *FakeConnection) NetOut(handle string, network string, port uint32) error {
	connection.lock.Lock()
	connection.netOuted[handle] = append(connection.netOuted[handle], NetOutSpec{
		Network: network,
		Port:    port,
	})
	connection.lock.Unlock()

	if connection.WhenNetOuting != nil {
		return connection.WhenNetOuting(handle, network, port)
	}

	return nil
}

func (connection *FakeConnection) NetOuted(handle string) []NetOutSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.netOuted[handle]
}
<commit_msg>fake: always return a reader/writer in streams<commit_after>package fake_connection

import (
	"bytes"
	"io"
	"sync"

	"github.com/cloudfoundry-incubator/garden/warden"
	"github.com/onsi/gomega/gbytes"
)

type FakeConnection struct {
	lock *sync.RWMutex

	closed bool

	disconnected chan struct{}

	WhenGettingCapacity func() (warden.Capacity, error)

	created      []warden.ContainerSpec
	WhenCreating func(spec warden.ContainerSpec) (string, error)

	listedProperties []warden.Properties
	WhenListing      func(props warden.Properties) ([]string, error)

	destroyed      []string
	WhenDestroying func(handle string) error

	stopped      map[string][]StopSpec
	WhenStopping func(handle string, background, kill bool) error

	WhenGettingInfo func(handle string) (warden.ContainerInfo, error)

	copiedIn      map[string][]CopyInSpec
	WhenCopyingIn func(handle string, src, dst string) error

	copiedOut      map[string][]CopyOutSpec
	WhenCopyingOut func(handle string, src, dst, owner string) error

	streamedIn      map[string][]StreamInSpec
	WhenStreamingIn func(handle string, dst string) (io.WriteCloser, error)

	streamedOut      map[string][]StreamOutSpec
	WhenStreamingOut func(handle string, src string) (io.Reader, error)

	limitedBandwidth      map[string][]warden.BandwidthLimits
	WhenLimitingBandwidth func(handle string, limits warden.BandwidthLimits) (warden.BandwidthLimits, error)

	limitedCPU      map[string][]warden.CPULimits
	WhenLimitingCPU func(handle string, limits warden.CPULimits) (warden.CPULimits, error)

	limitedDisk      map[string][]warden.DiskLimits
	WhenLimitingDisk func(handle string, limits warden.DiskLimits) (warden.DiskLimits, error)

	limitedMemory      map[string][]warden.MemoryLimits
	WhenLimitingMemory func(handle string, limit warden.MemoryLimits) (warden.MemoryLimits, error)

	spawnedProcesses map[string][]warden.ProcessSpec
	WhenRunning      func(handle string, spec warden.ProcessSpec) (uint32, <-chan warden.ProcessStream, error)

	attachedProcesses map[string][]uint32
	WhenAttaching     func(handle string, processID uint32) (<-chan warden.ProcessStream, error)

	netInned      map[string][]NetInSpec
	WhenNetInning func(handle string, hostPort, containerPort uint32) (uint32, uint32, error)

	netOuted      map[string][]NetOutSpec
	WhenNetOuting func(handle string, network string, port uint32) error
}

type StopSpec struct {
	Background bool
	Kill       bool
}

type CopyInSpec struct {
	Source      string
	Destination string
}

type CopyOutSpec struct {
	Source      string
	Destination string
	Owner       string
}

type StreamInSpec struct {
	Destination string
	WriteBuffer *gbytes.Buffer
}

type StreamOutSpec struct {
	Source     string
	ReadBuffer *bytes.Buffer
}

type NetInSpec struct {
	HostPort      uint32
	ContainerPort uint32
}

type NetOutSpec struct {
	Network string
	Port    uint32
}

func New() *FakeConnection {
	return &FakeConnection{
		lock: &sync.RWMutex{},

		disconnected: make(chan struct{}),

		stopped: make(map[string][]StopSpec),

		copiedIn:  make(map[string][]CopyInSpec),
		copiedOut: make(map[string][]CopyOutSpec),

		streamedIn:  make(map[string][]StreamInSpec),
		streamedOut: make(map[string][]StreamOutSpec),

		limitedBandwidth: make(map[string][]warden.BandwidthLimits),
		limitedCPU:       make(map[string][]warden.CPULimits),
		limitedDisk:      make(map[string][]warden.DiskLimits),
		limitedMemory:    make(map[string][]warden.MemoryLimits),

		spawnedProcesses:  make(map[string][]warden.ProcessSpec),
		attachedProcesses: make(map[string][]uint32),

		netInned: make(map[string][]NetInSpec),
		netOuted: make(map[string][]NetOutSpec),
	}
}

func (connection *FakeConnection) Close() {
	connection.lock.Lock()
	connection.closed = true
	connection.lock.Unlock()
}

func (connection *FakeConnection) IsClosed() bool {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.closed
}

func (connection *FakeConnection) Disconnected() <-chan struct{} {
	return connection.disconnected
}

func (connection *FakeConnection) NotifyDisconnected() {
	close(connection.disconnected)
}

func (connection *FakeConnection) Capacity() (warden.Capacity, error) {
	if connection.WhenGettingCapacity != nil {
		return connection.WhenGettingCapacity()
	}

	return warden.Capacity{}, nil
}

func (connection *FakeConnection) Create(spec warden.ContainerSpec) (string, error) {
	connection.lock.Lock()
	connection.created = append(connection.created, spec)
	connection.lock.Unlock()

	if connection.WhenCreating != nil {
		return connection.WhenCreating(spec)
	}

	return spec.Handle, nil
}

func (connection *FakeConnection) Created() []warden.ContainerSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.created
}

func (connection *FakeConnection) List(properties warden.Properties) ([]string, error) {
	connection.lock.Lock()
	connection.listedProperties = append(connection.listedProperties, properties)
	connection.lock.Unlock()

	if connection.WhenListing != nil {
		return connection.WhenListing(properties)
	}

	return nil, nil
}

func (connection *FakeConnection) ListedProperties() []warden.Properties {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.listedProperties
}

func (connection *FakeConnection) Destroy(handle string) error {
	connection.lock.Lock()
	connection.destroyed = append(connection.destroyed, handle)
	connection.lock.Unlock()

	if connection.WhenDestroying != nil {
		return connection.WhenDestroying(handle)
	}

	return nil
}

func (connection *FakeConnection) Destroyed() []string {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.destroyed
}

func (connection *FakeConnection) Stop(handle string, background, kill bool) error {
	connection.lock.Lock()
	connection.stopped[handle] = append(connection.stopped[handle], StopSpec{
		Background: background,
		Kill:       kill,
	})
	connection.lock.Unlock()

	if connection.WhenStopping != nil {
		return connection.WhenStopping(handle, background, kill)
	}

	return nil
}

func (connection *FakeConnection) Stopped(handle string) []StopSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.stopped[handle]
}

func (connection *FakeConnection) Info(handle string) (warden.ContainerInfo, error) {
	if connection.WhenGettingInfo != nil {
		return connection.WhenGettingInfo(handle)
	}

	return warden.ContainerInfo{}, nil
}

func (connection *FakeConnection) CopyIn(handle string, src, dst string) error {
	connection.lock.Lock()
	connection.copiedIn[handle] = append(connection.copiedIn[handle], CopyInSpec{
		Source:      src,
		Destination: dst,
	})
	connection.lock.Unlock()

	if connection.WhenCopyingIn != nil {
		return connection.WhenCopyingIn(handle, src, dst)
	}

	return nil
}

func (connection *FakeConnection) CopiedIn(handle string) []CopyInSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.copiedIn[handle]
}

func (connection *FakeConnection) CopyOut(handle string, src, dst, owner string) error {
	connection.lock.Lock()
	connection.copiedOut[handle] = append(connection.copiedOut[handle], CopyOutSpec{
		Source:      src,
		Destination: dst,
		Owner:       owner,
	})
	connection.lock.Unlock()

	if connection.WhenCopyingOut != nil {
		return connection.WhenCopyingOut(handle, src, dst, owner)
	}

	return nil
}

func (connection *FakeConnection) CopiedOut(handle string) []CopyOutSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.copiedOut[handle]
}

func (connection *FakeConnection) StreamIn(handle string, dstPath string) (io.WriteCloser, error) {
	buffer := gbytes.NewBuffer()

	connection.lock.Lock()
	connection.streamedIn[handle] = append(connection.streamedIn[handle], StreamInSpec{
		Destination: dstPath,
		WriteBuffer: buffer,
	})
	connection.lock.Unlock()

	if connection.WhenStreamingIn != nil {
		return connection.WhenStreamingIn(handle, dstPath)
	}

	return buffer, nil
}

func (connection *FakeConnection) StreamedIn(handle string) []StreamInSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.streamedIn[handle]
}

func (connection *FakeConnection) StreamOut(handle string, srcPath string) (io.Reader, error) {
	buffer := new(bytes.Buffer)
	connection.lock.Lock()
	connection.streamedOut[handle] = append(connection.streamedOut[handle], StreamOutSpec{
		Source:     srcPath,
		ReadBuffer: buffer,
	})
	connection.lock.Unlock()

	if connection.WhenStreamingOut != nil {
		return connection.WhenStreamingOut(handle, srcPath)
	}

	return buffer, nil
}

func (connection *FakeConnection) StreamedOut(handle string) []StreamOutSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.streamedOut[handle]
}

func (connection *FakeConnection) LimitBandwidth(handle string, limits warden.BandwidthLimits) (warden.BandwidthLimits, error) {
	connection.lock.Lock()
	connection.limitedBandwidth[handle] = append(connection.limitedBandwidth[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingBandwidth != nil {
		return connection.WhenLimitingBandwidth(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedBandwidth(handle string) []warden.BandwidthLimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedBandwidth[handle]
}

func (connection *FakeConnection) LimitCPU(handle string, limits warden.CPULimits) (warden.CPULimits, error) {
	connection.lock.Lock()
	connection.limitedCPU[handle] = append(connection.limitedCPU[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingCPU != nil {
		return connection.WhenLimitingCPU(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedCPU(handle string) []warden.CPULimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedCPU[handle]
}

func (connection *FakeConnection) LimitDisk(handle string, limits warden.DiskLimits) (warden.DiskLimits, error) {
	connection.lock.Lock()
	connection.limitedDisk[handle] = append(connection.limitedDisk[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingDisk != nil {
		return connection.WhenLimitingDisk(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedDisk(handle string) []warden.DiskLimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedDisk[handle]
}

func (connection *FakeConnection) LimitMemory(handle string, limits warden.MemoryLimits) (warden.MemoryLimits, error) {
	connection.lock.Lock()
	connection.limitedMemory[handle] = append(connection.limitedMemory[handle], limits)
	connection.lock.Unlock()

	if connection.WhenLimitingMemory != nil {
		return connection.WhenLimitingMemory(handle, limits)
	}

	return limits, nil
}

func (connection *FakeConnection) LimitedMemory(handle string) []warden.MemoryLimits {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.limitedMemory[handle]
}

func (connection *FakeConnection) Run(handle string, spec warden.ProcessSpec) (uint32, <-chan warden.ProcessStream, error) {
	connection.lock.Lock()
	connection.spawnedProcesses[handle] = append(connection.spawnedProcesses[handle], spec)
	connection.lock.Unlock()

	if connection.WhenRunning != nil {
		return connection.WhenRunning(handle, spec)
	}

	return 0, make(chan warden.ProcessStream), nil
}

func (connection *FakeConnection) SpawnedProcesses(handle string) []warden.ProcessSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.spawnedProcesses[handle]
}

func (connection *FakeConnection) Attach(handle string, processID uint32) (<-chan warden.ProcessStream, error) {
	connection.lock.Lock()
	connection.attachedProcesses[handle] = append(connection.attachedProcesses[handle], processID)
	connection.lock.Unlock()

	if connection.WhenAttaching != nil {
		return connection.WhenAttaching(handle, processID)
	}

	return make(chan warden.ProcessStream), nil
}

func (connection *FakeConnection) AttachedProcesses(handle string) []uint32 {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.attachedProcesses[handle]
}

func (connection *FakeConnection) NetIn(handle string, hostPort, containerPort uint32) (uint32, uint32, error) {
	connection.lock.Lock()
	connection.netInned[handle] = append(connection.netInned[handle], NetInSpec{
		HostPort:      hostPort,
		ContainerPort: containerPort,
	})
	connection.lock.Unlock()

	if connection.WhenNetInning != nil {
		return connection.WhenNetInning(handle, hostPort, containerPort)
	}

	return 0, 0, nil
}

func (connection *FakeConnection) NetInned(handle string) []NetInSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.netInned[handle]
}

func (connection *FakeConnection) NetOut(handle string, network string, port uint32) error {
	connection.lock.Lock()
	connection.netOuted[handle] = append(connection.netOuted[handle], NetOutSpec{
		Network: network,
		Port:    port,
	})
	connection.lock.Unlock()

	if connection.WhenNetOuting != nil {
		return connection.WhenNetOuting(handle, network, port)
	}

	return nil
}

func (connection *FakeConnection) NetOuted(handle string) []NetOutSpec {
	connection.lock.RLock()
	defer connection.lock.RUnlock()

	return connection.netOuted[handle]
}
<|endoftext|>


<commit_before>package handler

import (
	"fmt"
	"github.com/realglobe-Inc/go-lib-rg/rglog/level"
	"os"
	"strings"
	"time"
)

type Formatter interface {
	Format(date time.Time, file string, line int, lv level.Level, v ...interface{}) []byte
}

type simpleFormatter struct {
}

func (formatter simpleFormatter) Format(date time.Time, file string, line int, lv level.Level, v ...interface{}) []byte {
	year, month, day := date.Date()
	hour, min, sec := date.Clock()
	microSec := date.Nanosecond() / 1000

	// コンパイル環境の ${GOPATH}/src/ を取り除く。
	// os.Getenv("GOPATH") して得られるのは実行環境の値なので、不完全な方法を取る。
	srcDir := string(os.PathSeparator) + "src" + string(os.PathSeparator)
	pos := strings.Index(file, srcDir)
	if pos >= 0 {
		file = file[pos+len(srcDir):]
	}

	// Level は固定幅で左寄せ。見た目はいいけど cut では後ろが分けられない。
	msg := fmt.Sprintf("%04d/%02d/%02d %02d:%02d:%02d.%06d %-5v %s:%d ", year, int(month), day, hour, min, sec, microSec, lv, file, line) +
		fmt.Sprint(v...) +
		"\n"

	return []byte(msg)
}
<commit_msg>表示する意味の無い部分の除去精度を上げた<commit_after>package handler

import (
	"fmt"
	"github.com/realglobe-Inc/go-lib-rg/rglog/level"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

type Formatter interface {
	Format(date time.Time, file string, line int, lv level.Level, v ...interface{}) []byte
}

type simpleFormatter struct {
}

func (formatter simpleFormatter) Format(date time.Time, file string, line int, lv level.Level, v ...interface{}) []byte {
	year, month, day := date.Date()
	hour, min, sec := date.Clock()
	microSec := date.Nanosecond() / 1000

	if strings.HasPrefix(file, uselessPrefix) { // 違う環境でコンパイルした後、リンクすることは可能だと思うので。
		file = file[len(uselessPrefix):]
	} else {
		// /src/ の前までを GOPATH とみなす。
		// GOPATH 自体に /src/ が含まれていると、そこまでしか除去できない。
		srcDir := string(os.PathSeparator) + "src" + string(os.PathSeparator)
		pos := strings.Index(file, srcDir)
		if pos >= 0 {
			file = file[pos+len(srcDir):]
		}
	}

	// Level は固定幅で左寄せ。見た目はいいけど cut では後ろが分けられない。
	msg := fmt.Sprintf("%04d/%02d/%02d %02d:%02d:%02d.%06d %-5v %s:%d ",
		year, int(month), day, hour, min, sec, microSec, lv, file, line) +
		fmt.Sprint(v...) + "\n"

	return []byte(msg)
}

// ${GOPATH}/src/ の部分。
var uselessPrefix string

func init() {
	// このファイルの名前から ${GOPATH}/src/ を逆算する。

	_, file, _, ok := runtime.Caller(0)
	if !ok {
		return
	}

	suffix := filepath.Join("github.com", "realglobe-Inc", "go-lib-rg", "rglog", "handler", "formatter.go")
	if !strings.HasSuffix(file, suffix) {
		return
	}

	uselessPrefix = file[:len(file)-len(suffix)]
}
<|endoftext|>


<commit_before>/*
Expression based request router, supports functions and combinations of functions in form

<What to match><Matching verb> and || and && operators.

*/
package exproute

import (
	"fmt"
	"github.com/mailgun/vulcan/location"
	"github.com/mailgun/vulcan/request"
	"sync"
)

type ExpRouter struct {
	mutex    *sync.RWMutex
	matchers []matcher
	routes   map[string]location.Location
}

func NewExpRouter() *ExpRouter {
	return &ExpRouter{
		mutex:  &sync.RWMutex{},
		routes: make(map[string]location.Location),
	}
}

func (e *ExpRouter) GetLocationByExpression(expr string) location.Location {
	e.mutex.RLock()
	defer e.mutex.RUnlock()

	return e.routes[expr]
}

func (e *ExpRouter) AddLocation(expr string, l location.Location) error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	if _, ok := e.routes[expr]; ok {
		return fmt.Errorf("Expression '%s' already exists", expr)
	}
	if _, err := parseExpression(expr, l); err != nil {
		return err
	}
	e.routes[expr] = l
	if err := e.compile(); err != nil {
		delete(e.routes, expr)
		return err
	}
	return nil
}

func (e *ExpRouter) compile() error {
	matchers := []matcher{}
	i := 0
	for expr, location := range e.routes {
		matcher, err := parseExpression(expr, location)
		if err != nil {
			return err
		}

		// Merge the previous and new matcher if that's possible
		if i > 0 && matchers[i-1].canMerge(matcher) {
			m, err := matchers[i-1].merge(matcher)
			if err != nil {
				return err
			}
			matchers[i-1] = m
		} else {
			matchers = append(matchers, matcher)
			i += 1
		}
	}

	e.matchers = matchers
	return nil
}

func (e *ExpRouter) RemoveLocationByExpression(expr string) error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	delete(e.routes, expr)
	return e.compile()
}

func (e *ExpRouter) RemoveLocationById(id string) error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	for expr, l := range e.routes {
		if l.GetId() == id {
			delete(e.routes, expr)
		}
	}
	return e.compile()
}

func (e *ExpRouter) GetLocationById(id string) location.Location {
	e.mutex.RLock()
	defer e.mutex.RUnlock()

	for _, l := range e.routes {
		if l.GetId() == id {
			return l
		}
	}
	return nil
}

func (e *ExpRouter) Route(req request.Request) (location.Location, error) {
	e.mutex.RLock()
	defer e.mutex.RUnlock()

	if len(e.matchers) == 0 {
		return nil, nil
	}

	for _, m := range e.matchers {
		if l := m.match(req); l != nil {
			return l, nil
		}
	}
	return nil, nil
}
<commit_msg>Sort routes before compile into matchers<commit_after>/*
Expression based request router, supports functions and combinations of functions in form

<What to match><Matching verb> and || and && operators.

*/
package exproute

import (
	"fmt"
	"sort"
	"sync"

	"github.com/mailgun/vulcan/location"
	"github.com/mailgun/vulcan/request"
)

type ExpRouter struct {
	mutex    *sync.RWMutex
	matchers []matcher
	routes   map[string]location.Location
}

func NewExpRouter() *ExpRouter {
	return &ExpRouter{
		mutex:  &sync.RWMutex{},
		routes: make(map[string]location.Location),
	}
}

func (e *ExpRouter) GetLocationByExpression(expr string) location.Location {
	e.mutex.RLock()
	defer e.mutex.RUnlock()

	return e.routes[expr]
}

func (e *ExpRouter) AddLocation(expr string, l location.Location) error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	if _, ok := e.routes[expr]; ok {
		return fmt.Errorf("Expression '%s' already exists", expr)
	}
	if _, err := parseExpression(expr, l); err != nil {
		return err
	}
	e.routes[expr] = l
	if err := e.compile(); err != nil {
		delete(e.routes, expr)
		return err
	}
	return nil
}

func (e *ExpRouter) compile() error {
	var exprs = []string{}
	for expr, _ := range e.routes {
		exprs = append(exprs, expr)
	}
	sort.Sort(sort.Reverse(sort.StringSlice(exprs)))

	matchers := []matcher{}
	i := 0
	for _, expr := range exprs {
		location := e.routes[expr]
		matcher, err := parseExpression(expr, location)
		if err != nil {
			return err
		}

		// Merge the previous and new matcher if that's possible
		if i > 0 && matchers[i-1].canMerge(matcher) {
			m, err := matchers[i-1].merge(matcher)
			if err != nil {
				return err
			}
			matchers[i-1] = m
		} else {
			matchers = append(matchers, matcher)
			i += 1
		}
	}

	e.matchers = matchers
	return nil
}

func (e *ExpRouter) RemoveLocationByExpression(expr string) error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	delete(e.routes, expr)
	return e.compile()
}

func (e *ExpRouter) RemoveLocationById(id string) error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	for expr, l := range e.routes {
		if l.GetId() == id {
			delete(e.routes, expr)
		}
	}
	return e.compile()
}

func (e *ExpRouter) GetLocationById(id string) location.Location {
	e.mutex.RLock()
	defer e.mutex.RUnlock()

	for _, l := range e.routes {
		if l.GetId() == id {
			return l
		}
	}
	return nil
}

func (e *ExpRouter) Route(req request.Request) (location.Location, error) {
	e.mutex.RLock()
	defer e.mutex.RUnlock()

	if len(e.matchers) == 0 {
		return nil, nil
	}

	for _, m := range e.matchers {
		if l := m.match(req); l != nil {
			return l, nil
		}
	}
	return nil, nil
}
<|endoftext|>


<commit_before>package flow

import (
	"log"
	"reflect"
)

func _getLessThanComparatorByKeyValue(key reflect.Value) (funcPointer interface{}) {
	dt := key.Type()
	if key.Kind() == reflect.Interface {
		dt = reflect.TypeOf(key.Interface())
	}
	switch dt.Kind() {
	case reflect.Int:
		funcPointer = func(a, b int) bool { return a < b }
	case reflect.Int8:
		funcPointer = func(a, b int8) bool { return a < b }
	case reflect.Int16:
		funcPointer = func(a, b int16) bool { return a < b }
	case reflect.Int32:
		funcPointer = func(a, b int32) bool { return a < b }
	case reflect.Int64:
		funcPointer = func(a, b int64) bool { return a < b }
	case reflect.Uint:
		funcPointer = func(a, b uint) bool { return a < b }
	case reflect.Uint8:
		funcPointer = func(a, b uint8) bool { return a < b }
	case reflect.Uint16:
		funcPointer = func(a, b uint16) bool { return a < b }
	case reflect.Uint32:
		funcPointer = func(a, b uint32) bool { return a < b }
	case reflect.Uint64:
		funcPointer = func(a, b uint64) bool { return a < b }
	case reflect.Float32:
		funcPointer = func(a, b float32) bool { return a < b }
	case reflect.Float64:
		funcPointer = func(a, b float64) bool { return a < b }
	case reflect.String:
		funcPointer = func(a, b string) bool { return a < b }
	default:
		log.Panicf("No default less than comparator for type:%s, kind:%s", dt.String(), dt.Kind().String())
	}
	return
}

func getLessThanComparator(datasetType reflect.Type, key reflect.Value,
	functionPointer interface{}) func(a interface{}, b interface{}) bool {
	lessThanFuncValue := reflect.ValueOf(functionPointer)
	if functionPointer == nil {
		v := guessKey(key)
		lessThanFuncValue = reflect.ValueOf(_getLessThanComparatorByKeyValue(v))
	}
	if datasetType == KeyValueType {
		return func(a interface{}, b interface{}) bool {
			ret := _functionCall(lessThanFuncValue,
				a.(KeyValue).Key,
				b.(KeyValue).Key,
			)
			return ret[0].Bool()
		}
	} else {
		return func(a interface{}, b interface{}) bool {
			ret := lessThanFuncValue.Call([]reflect.Value{
				reflect.ValueOf(a),
				reflect.ValueOf(b),
			})
			return ret[0].Bool()
		}
	}
}
<commit_msg>support sorting time.Time<commit_after>package flow

import (
	"log"
	"reflect"
	"time"
)

func _getLessThanComparatorByKeyValue(key reflect.Value) (funcPointer interface{}) {
	dt := key.Type()
	if key.Kind() == reflect.Interface {
		dt = reflect.TypeOf(key.Interface())
	}
	if dt.String() == "time.Time" {
		return func(a, b time.Time) bool { return a.Before(b) }
	}
	switch dt.Kind() {
	case reflect.Int:
		funcPointer = func(a, b int) bool { return a < b }
	case reflect.Int8:
		funcPointer = func(a, b int8) bool { return a < b }
	case reflect.Int16:
		funcPointer = func(a, b int16) bool { return a < b }
	case reflect.Int32:
		funcPointer = func(a, b int32) bool { return a < b }
	case reflect.Int64:
		funcPointer = func(a, b int64) bool { return a < b }
	case reflect.Uint:
		funcPointer = func(a, b uint) bool { return a < b }
	case reflect.Uint8:
		funcPointer = func(a, b uint8) bool { return a < b }
	case reflect.Uint16:
		funcPointer = func(a, b uint16) bool { return a < b }
	case reflect.Uint32:
		funcPointer = func(a, b uint32) bool { return a < b }
	case reflect.Uint64:
		funcPointer = func(a, b uint64) bool { return a < b }
	case reflect.Float32:
		funcPointer = func(a, b float32) bool { return a < b }
	case reflect.Float64:
		funcPointer = func(a, b float64) bool { return a < b }
	case reflect.String:
		funcPointer = func(a, b string) bool { return a < b }
	default:
		log.Panicf("No default less than comparator for type:%s, kind:%s", dt.String(), dt.Kind().String())
	}
	return
}

func getLessThanComparator(datasetType reflect.Type, key reflect.Value,
	functionPointer interface{}) func(a interface{}, b interface{}) bool {
	lessThanFuncValue := reflect.ValueOf(functionPointer)
	if functionPointer == nil {
		v := guessKey(key)
		lessThanFuncValue = reflect.ValueOf(_getLessThanComparatorByKeyValue(v))
	}
	if datasetType == KeyValueType {
		return func(a interface{}, b interface{}) bool {
			ret := _functionCall(lessThanFuncValue,
				a.(KeyValue).Key,
				b.(KeyValue).Key,
			)
			return ret[0].Bool()
		}
	} else {
		return func(a interface{}, b interface{}) bool {
			ret := lessThanFuncValue.Call([]reflect.Value{
				reflect.ValueOf(a),
				reflect.ValueOf(b),
			})
			return ret[0].Bool()
		}
	}
}
<|endoftext|>


<commit_before>package boil

import (
	"bytes"
	"database/sql"
	"fmt"
	"strings"

	"github.com/nullbio/sqlboiler/strmangle"
)

type where struct {
	clause      string
	orSeperator bool
	args        []interface{}
}

type plainSQL struct {
	sql  string
	args []interface{}
}

type join struct {
	on   string
	args []interface{}
}

// Query holds the state for the built up query
type Query struct {
	executor        Executor
	plainSQL        plainSQL
	delete          bool
	update          map[string]interface{}
	selectCols      []string
	count           bool
	from            []string
	innerJoins      []join
	outerJoins      []join
	leftOuterJoins  []join
	rightOuterJoins []join
	where           []where
	groupBy         []string
	orderBy         []string
	having          []string
	limit           int
	offset          int
}

func buildQuery(q *Query) (string, []interface{}) {
	var buf *bytes.Buffer
	var args []interface{}

	switch {
	case len(q.plainSQL.sql) != 0:
		return q.plainSQL.sql, q.plainSQL.args
	case q.delete:
		buf, args = buildDeleteQuery(q)
	case len(q.update) > 0:
		buf, args = buildUpdateQuery(q)
	default:
		buf, args = buildSelectQuery(q)
	}

	return buf.String(), args
}

func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("SELECT ")

	if q.count {
		buf.WriteString("COUNT(")
	}
	if len(q.selectCols) > 0 {
		buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.selectCols), `, `))
	} else {
		buf.WriteByte('*')
	}
	// close sql COUNT function
	if q.count {
		buf.WriteString(")")
	}

	buf.WriteString(" FROM ")
	buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.from), ","))

	where, args := whereClause(q)
	buf.WriteString(where)

	if len(q.orderBy) != 0 {
		buf.WriteString(" ORDER BY ")
		buf.WriteString(strings.Join(q.orderBy, ","))
	}

	if q.limit != 0 {
		fmt.Fprintf(buf, " LIMIT %d", q.limit)
	}
	if q.offset != 0 {
		fmt.Fprintf(buf, " OFFSET %d", q.offset)
	}

	buf.WriteByte(';')
	return buf, args
}

func buildDeleteQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("DELETE FROM ")
	fmt.Fprintf(buf, `"%s"`, q.from)

	where, args := whereClause(q)
	buf.WriteString(where)

	buf.WriteByte(';')

	return buf, args
}

func buildUpdateQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteByte(';')
	return buf, nil
}

// ExecQuery executes a query that does not need a row returned
func ExecQuery(q *Query) (sql.Result, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Exec(qs, args...)
}

// ExecQueryOne executes the query for the One finisher and returns a row
func ExecQueryOne(q *Query) *sql.Row {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.QueryRow(qs, args...)
}

// ExecQueryAll executes the query for the All finisher and returns multiple rows
func ExecQueryAll(q *Query) (*sql.Rows, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Query(qs, args...)
}

// SetSQL on the query.
func SetSQL(q *Query, sql string, args ...interface{}) {
	q.plainSQL = plainSQL{sql: sql, args: args}
}

// SetCount on the query.
func SetCount(q *Query) {
	q.count = true
}

// SetDelete on the query.
func SetDelete(q *Query) {
	q.delete = true
}

// SetUpdate on the query.
func SetUpdate(q *Query, cols map[string]interface{}) {
	q.update = cols
}

// SetExecutor on the query.
func SetExecutor(q *Query, exec Executor) {
	q.executor = exec
}

// AppendSelect on the query.
func AppendSelect(q *Query, columns ...string) {
	q.selectCols = append(q.selectCols, columns...)
}

// SetSelect replaces the current select clause.
func SetSelect(q *Query, columns ...string) {
	q.selectCols = append([]string(nil), columns...)
}

// Select returns the select columns in the query.
func Select(q *Query) []string {
	cols := make([]string, len(q.selectCols))
	copy(cols, q.selectCols)
	return cols
}

// AppendFrom on the query.
func AppendFrom(q *Query, from ...string) {
	q.from = append(q.from, from...)
}

// SetFrom replaces the current from statements.
func SetFrom(q *Query, from ...string) {
	q.from = append([]string(nil), from...)
}

// AppendInnerJoin on the query.
func AppendInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append(q.innerJoins, join{on: on, args: args})
}

// SetInnerJoin on the query.
func SetInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append([]join(nil), join{on: on, args: args})
}

// AppendWhere on the query.
func AppendWhere(q *Query, clause string, args ...interface{}) {
	q.where = append(q.where, where{clause: clause, args: args})
}

// SetWhere on the query.
func SetWhere(q *Query, clause string, args ...interface{}) {
	q.where = append([]where(nil), where{clause: clause, args: args})
}

// SetLastWhereAsOr sets the or seperator for the last element in the where slice
func SetLastWhereAsOr(q *Query) {
	q.where[len(q.where)-1].orSeperator = true
}

// ApplyGroupBy on the query.
func ApplyGroupBy(q *Query, clause string) {
	q.groupBy = append(q.groupBy, clause)
}

// SetGroupBy on the query.
func SetGroupBy(q *Query, clause string) {
	q.groupBy = append([]string(nil), clause)
}

// ApplyOrderBy on the query.
func ApplyOrderBy(q *Query, clause string) {
	q.orderBy = append(q.orderBy, clause)
}

// SetOrderBy on the query.
func SetOrderBy(q *Query, clause string) {
	q.orderBy = append([]string(nil), clause)
}

// ApplyHaving on the query.
func ApplyHaving(q *Query, clause string) {
	q.having = append(q.having, clause)
}

// SetHaving on the query.
func SetHaving(q *Query, clause string) {
	q.having = append([]string(nil), clause)
}

// SetLimit on the query.
func SetLimit(q *Query, limit int) {
	q.limit = limit
}

// SetOffset on the query.
func SetOffset(q *Query, offset int) {
	q.offset = offset
}

func whereClause(q *Query) (string, []interface{}) {
	if len(q.where) == 0 {
		return "", nil
	}

	buf := &bytes.Buffer{}
	var args []interface{}

	buf.WriteString(" WHERE ")
	for i := 0; i < len(q.where); i++ {
		buf.WriteString(fmt.Sprintf("%s", q.where[i].clause))
		args = append(args, q.where[i].args...)
		if i >= len(q.where)-1 {
			continue
		}
		if q.where[i].orSeperator {
			buf.WriteString(" OR ")
		} else {
			buf.WriteString(" AND ")
		}
	}

	return buf.String(), args
}
<commit_msg>Remove unused fields<commit_after>package boil

import (
	"bytes"
	"database/sql"
	"fmt"
	"strings"

	"github.com/nullbio/sqlboiler/strmangle"
)

type where struct {
	clause      string
	orSeperator bool
	args        []interface{}
}

type plainSQL struct {
	sql  string
	args []interface{}
}

type join struct {
	on   string
	args []interface{}
}

// Query holds the state for the built up query
type Query struct {
	executor   Executor
	plainSQL   plainSQL
	delete     bool
	update     map[string]interface{}
	selectCols []string
	count      bool
	from       []string
	innerJoins []join
	where      []where
	groupBy    []string
	orderBy    []string
	having     []string
	limit      int
	offset     int
}

func buildQuery(q *Query) (string, []interface{}) {
	var buf *bytes.Buffer
	var args []interface{}

	switch {
	case len(q.plainSQL.sql) != 0:
		return q.plainSQL.sql, q.plainSQL.args
	case q.delete:
		buf, args = buildDeleteQuery(q)
	case len(q.update) > 0:
		buf, args = buildUpdateQuery(q)
	default:
		buf, args = buildSelectQuery(q)
	}

	return buf.String(), args
}

func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("SELECT ")

	if q.count {
		buf.WriteString("COUNT(")
	}
	if len(q.selectCols) > 0 {
		buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.selectCols), `, `))
	} else {
		buf.WriteByte('*')
	}
	// close sql COUNT function
	if q.count {
		buf.WriteString(")")
	}

	buf.WriteString(" FROM ")
	buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.from), ","))

	where, args := whereClause(q)
	buf.WriteString(where)

	if len(q.orderBy) != 0 {
		buf.WriteString(" ORDER BY ")
		buf.WriteString(strings.Join(q.orderBy, ","))
	}

	if q.limit != 0 {
		fmt.Fprintf(buf, " LIMIT %d", q.limit)
	}
	if q.offset != 0 {
		fmt.Fprintf(buf, " OFFSET %d", q.offset)
	}

	buf.WriteByte(';')
	return buf, args
}

func buildDeleteQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("DELETE FROM ")
	fmt.Fprintf(buf, `"%s"`, q.from)

	where, args := whereClause(q)
	buf.WriteString(where)

	buf.WriteByte(';')

	return buf, args
}

func buildUpdateQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteByte(';')
	return buf, nil
}

// ExecQuery executes a query that does not need a row returned
func ExecQuery(q *Query) (sql.Result, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Exec(qs, args...)
}

// ExecQueryOne executes the query for the One finisher and returns a row
func ExecQueryOne(q *Query) *sql.Row {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.QueryRow(qs, args...)
}

// ExecQueryAll executes the query for the All finisher and returns multiple rows
func ExecQueryAll(q *Query) (*sql.Rows, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Query(qs, args...)
}

// SetSQL on the query.
func SetSQL(q *Query, sql string, args ...interface{}) {
	q.plainSQL = plainSQL{sql: sql, args: args}
}

// SetCount on the query.
func SetCount(q *Query) {
	q.count = true
}

// SetDelete on the query.
func SetDelete(q *Query) {
	q.delete = true
}

// SetUpdate on the query.
func SetUpdate(q *Query, cols map[string]interface{}) {
	q.update = cols
}

// SetExecutor on the query.
func SetExecutor(q *Query, exec Executor) {
	q.executor = exec
}

// AppendSelect on the query.
func AppendSelect(q *Query, columns ...string) {
	q.selectCols = append(q.selectCols, columns...)
}

// SetSelect replaces the current select clause.
func SetSelect(q *Query, columns ...string) {
	q.selectCols = append([]string(nil), columns...)
}

// Select returns the select columns in the query.
func Select(q *Query) []string {
	cols := make([]string, len(q.selectCols))
	copy(cols, q.selectCols)
	return cols
}

// AppendFrom on the query.
func AppendFrom(q *Query, from ...string) {
	q.from = append(q.from, from...)
}

// SetFrom replaces the current from statements.
func SetFrom(q *Query, from ...string) {
	q.from = append([]string(nil), from...)
}

// AppendInnerJoin on the query.
func AppendInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append(q.innerJoins, join{on: on, args: args})
}

// SetInnerJoin on the query.
func SetInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append([]join(nil), join{on: on, args: args})
}

// AppendWhere on the query.
func AppendWhere(q *Query, clause string, args ...interface{}) {
	q.where = append(q.where, where{clause: clause, args: args})
}

// SetWhere on the query.
func SetWhere(q *Query, clause string, args ...interface{}) {
	q.where = append([]where(nil), where{clause: clause, args: args})
}

// SetLastWhereAsOr sets the or seperator for the last element in the where slice
func SetLastWhereAsOr(q *Query) {
	q.where[len(q.where)-1].orSeperator = true
}

// ApplyGroupBy on the query.
func ApplyGroupBy(q *Query, clause string) {
	q.groupBy = append(q.groupBy, clause)
}

// SetGroupBy on the query.
func SetGroupBy(q *Query, clause string) {
	q.groupBy = append([]string(nil), clause)
}

// ApplyOrderBy on the query.
func ApplyOrderBy(q *Query, clause string) {
	q.orderBy = append(q.orderBy, clause)
}

// SetOrderBy on the query.
func SetOrderBy(q *Query, clause string) {
	q.orderBy = append([]string(nil), clause)
}

// ApplyHaving on the query.
func ApplyHaving(q *Query, clause string) {
	q.having = append(q.having, clause)
}

// SetHaving on the query.
func SetHaving(q *Query, clause string) {
	q.having = append([]string(nil), clause)
}

// SetLimit on the query.
func SetLimit(q *Query, limit int) {
	q.limit = limit
}

// SetOffset on the query.
func SetOffset(q *Query, offset int) {
	q.offset = offset
}

func whereClause(q *Query) (string, []interface{}) {
	if len(q.where) == 0 {
		return "", nil
	}

	buf := &bytes.Buffer{}
	var args []interface{}

	buf.WriteString(" WHERE ")
	for i := 0; i < len(q.where); i++ {
		buf.WriteString(fmt.Sprintf("%s", q.where[i].clause))
		args = append(args, q.where[i].args...)
		if i >= len(q.where)-1 {
			continue
		}
		if q.where[i].orSeperator {
			buf.WriteString(" OR ")
		} else {
			buf.WriteString(" AND ")
		}
	}

	return buf.String(), args
}
<|endoftext|>