<commit_before>package main
import (
    "project.go/elev"
    "project.go/network"
    "time"
    "fmt"
    "encoding/json"
    "project.go/order"
    . "project.go/obj"
)
/*
const (
    INIT = iota
    IDLE
    RUN
    DOOR_OPEN
)*/

const (
    N_FLOORS = 4
    N_BUTTONS = 3
    DOOR_TIMEOUT = 3
)

func Manager(push_light_channel, pop_light_channel chan<- Order, open_door_channel, direction_channel, check_stop_channel chan<- int) (chan<- Order, chan<- int, chan<- int) {
    local_addr, to_network_channel, from_network_channel, _, _ := network.Manager("33223");

    order_channel := make(chan Order);
    check_stop_channel := make(chan int);
    direction_request_channel := make(chan int);

    go func() {
        for {
            //system.Print();
            select {
            case msg := <-from_network_channel:
                addr := msg.Origin.IP.String();
                err := (error)(nil);
                order := &elev.Order{};
                i := (*int)(nil);
                switch msg.Code {
                case ORDER_PUSH, ORDER_POP:
                    err = json.Unmarshal(msg.Body, order);
                case FLOOR_HIT, DIRECTION_CHANGE:
                    err = json.Unmarshal(msg.Body, i);
                }
                if err != nil {
                    fmt.Println("Could not unmarshal order.");
                    break;
                }
                switch msg.Code {
                case ORDER_PUSH, ORDER_POP:
                    if msg.Code == ORDER_PUSH {
                        value := true;
                        push_light_channel <-order;
                        if carts[local_addr].Direction == 0 {
                            direction_channel <-getDirection();
                        }
                    } else {
                        value := false;
                        pop_light_channel <-order;
                    }
                    if order.Button == order.COMMAND {
                        cart[addr].Cab[order.Floor] = value;
                    } else {
                        hall[order.Floor][order.Button] = value;
                    }
                case FLOOR_HIT:
                    carts[addr].Floor = i;
                case DIRECTION_CHANGE:
                    carts[addr].Direction = i;
                }
            case order := <-order_channel:
                b, err := json.Marshal(order);
                if err != nil {
                    fmt.Println("Could not marshal order.");
                } else {
                    to_network_channel <-*NewMessage(ORDER_PUSH, b, nil, nil);
                }
            case floor := <-check_stop_channel:
                b, err := json.Marshal(floor);
                if err != nil {
                    fmt.Println("Could not marshal direction.");
                } else {
                    to_network_channel <-*NewMessage(FLOOR_HIT, b, nil, nil);
                }
                carts[local_addr].Floor = floor;
                if checkIfStop() {
                    order := Order{Button: order.COMMAND, Floor: floor};
                    b, _ := json.Marshal(order);
                    to_network_channel <-*NewMessage(ORDER_POP, b, nil, nil);
                    direction := getDirection();
                    if direction == elev.UP {
                        order.Button = order.UP;
                    } else if direction == elev.DOWN {
                        order.Button = order.DOWN;
                    }
                    b, _ := json.Marshal(order);
                    to_network_channel <-*NewMessage(ORDER_POP, b, nil, nil);
                    open_door_channel <-floor;
                }
            case <-direction_request_channel:
                direction := getDirection();
                b, err := json.Marshal(direction);
                if err != nil {
                    fmt.Println ("Could not marshal direction.");
                } else {
                    to_network_channel <-*NewMessage(DIRECTION_CHANGE, b, nil, nil);
                }
                carts[local_addr].Direction = direction;
                direction_channel <-direction;
            }
        }
    }();
    return order_channel, check_stop_channel, direction_request_channel;
}

func main() {
    elev.Init()
    door_open_floor := -1;
    door_open := false;

    button_channel := elev.Button_checker();
    floor_signal_channel := elev.Floor_checker();
    stop_signal_channel := elev.Stop_checker();

    push_light_channel := make(chan Order);
    pop_light_channel := make(chan Order);
    open_door_channel := make(chan int);
    direction_channel := make(chan int);

    order_channel, direction_request_channel := Manager(push_light_channel, pop_light_channel, open_door_channel, direction_channel);

    for {
        select {
        case order := <-push_light_channel:
            elev.SetButtonLamp(order.Floor, order.Button, true);
        case order := <-pop_light_channel:
            elev.SetButtonLamp(order.Floor, order.Button, false);
        case floor := <-open_door_channel:
            door_open = true;
            elev.SetDoorOpenLamp(true);
            elev.SetMotorDirection(0);
        case direction := <-direction_channel:
            elev.SetMotorDirection(direction);
        case floor := <-floor_signal_channel:
            check_stop_channel <-floor;
        case order := <-button_channel:
            if door_open && door_open_floor == order.Floor {
                door_timer.Start(3*time.Second);
            } else {
                order_channel <-order;
            }
        case <-door_timer.Timer.C:
            door_open = false;
            elev.SetDoorOpenLamp(false);
            direction_request_channel <-true;
        }
    }
}
<commit_msg>Very minor.<commit_after>package main
import (
    "project.go/elev"
    "project.go/network"
    "time"
    "fmt"
    "encoding/json"
    "project.go/order"
    . "project.go/obj"
)

const (
    N_FLOORS = 4
    N_BUTTONS = 3
)

func Manager(push_light_channel, pop_light_channel chan<- Order, open_door_channel, direction_channel, check_stop_channel chan<- int) (chan<- Order, chan<- int, chan<- int) {
    local_addr, to_network_channel, from_network_channel, _, _ := network.Manager("33223");

    order_channel := make(chan Order);
    check_stop_channel := make(chan int);
    direction_request_channel := make(chan int);

    go func() {
        for {
            //system.Print();
            select {
            case msg := <-from_network_channel:
                addr := msg.Origin.IP.String();
                err := (error)(nil);
                order := &elev.Order{};
                i := (*int)(nil);
                switch msg.Code {
                case ORDER_PUSH, ORDER_POP:
                    err = json.Unmarshal(msg.Body, order);
                case FLOOR_HIT, DIRECTION_CHANGE:
                    err = json.Unmarshal(msg.Body, i);
                }
                if err != nil {
                    fmt.Println("Could not unmarshal order.");
                    break;
                }
                switch msg.Code {
                case ORDER_PUSH, ORDER_POP:
                    if msg.Code == ORDER_PUSH {
                        value := true;
                        push_light_channel <-order;
                        if carts[local_addr].Direction == 0 {
                            direction_channel <-getDirection();
                        }
                    } else {
                        value := false;
                        pop_light_channel <-order;
                    }
                    if order.Button == order.COMMAND {
                        cart[addr].Cab[order.Floor] = value;
                    } else {
                        hall[order.Floor][order.Button] = value;
                    }
                case FLOOR_HIT:
                    carts[addr].Floor = i;
                case DIRECTION_CHANGE:
                    carts[addr].Direction = i;
                }
            case order := <-order_channel:
                b, err := json.Marshal(order);
                if err != nil {
                    fmt.Println("Could not marshal order.");
                } else {
                    to_network_channel <-*NewMessage(ORDER_PUSH, b, nil, nil);
                }
            case floor := <-check_stop_channel:
                b, err := json.Marshal(floor);
                if err != nil {
                    fmt.Println("Could not marshal direction.");
                } else {
                    to_network_channel <-*NewMessage(FLOOR_HIT, b, nil, nil);
                }
                carts[local_addr].Floor = floor;
                if checkIfStop() {
                    order := Order{Button: order.COMMAND, Floor: floor};
                    b, _ := json.Marshal(order);
                    to_network_channel <-*NewMessage(ORDER_POP, b, nil, nil);
                    direction := getDirection();
                    if direction == elev.UP {
                        order.Button = order.UP;
                    } else if direction == elev.DOWN {
                        order.Button = order.DOWN;
                    }
                    b, _ := json.Marshal(order);
                    to_network_channel <-*NewMessage(ORDER_POP, b, nil, nil);
                    open_door_channel <-floor;
                }
            case <-direction_request_channel:
                direction := getDirection();
                b, err := json.Marshal(direction);
                if err != nil {
                    fmt.Println ("Could not marshal direction.");
                } else {
                    to_network_channel <-*NewMessage(DIRECTION_CHANGE, b, nil, nil);
                }
                carts[local_addr].Direction = direction;
                direction_channel <-direction;
            }
        }
    }();
    return order_channel, check_stop_channel, direction_request_channel;
}

func main() {
    elev.Init()
    door_open_floor := -1;
    door_open := false;

    button_channel := elev.Button_checker();
    floor_signal_channel := elev.Floor_checker();
    stop_signal_channel := elev.Stop_checker();

    push_light_channel := make(chan Order);
    pop_light_channel := make(chan Order);
    open_door_channel := make(chan int);
    direction_channel := make(chan int);

    order_channel, direction_request_channel := Manager(push_light_channel, pop_light_channel, open_door_channel, direction_channel);

    for {
        select {
        case order := <-push_light_channel:
            elev.SetButtonLamp(order.Floor, order.Button, true);
        case order := <-pop_light_channel:
            elev.SetButtonLamp(order.Floor, order.Button, false);
        case floor := <-open_door_channel:
            door_open = true;
            elev.SetDoorOpenLamp(true);
            elev.SetMotorDirection(0);
        case direction := <-direction_channel:
            elev.SetMotorDirection(direction);
        case floor := <-floor_signal_channel:
            check_stop_channel <-floor;
        case order := <-button_channel:
            if door_open && door_open_floor == order.Floor {
                door_timer.Start(3*time.Second);
            } else {
                order_channel <-order;
            }
        case <-door_timer.Timer.C:
            door_open = false;
            elev.SetDoorOpenLamp(false);
            direction_request_channel <-true;
        }
    }
}
<|endoftext|>


<commit_before>package main

import (
  "io/ioutil"
  "os"
  "os/exec"
  "path/filepath"
  "regexp"
  "strings"

  "github.com/codegangsta/cli"
  "github.com/Sirupsen/logrus"
  "stash0.eng.lancope.local/dev-infrastructure/project-lifecycle/template"
  "stash0.eng.lancope.local/dev-infrastructure/project-lifecycle/helpers"
)

func main() {
  if err := LoadConfigFile("lc.yml"); err != nil {
    panic(err)
  }

  app := cli.NewApp()
  app.Name = Name
  app.Version = Version
  app.Author = "lancope"
  app.Email = ""
  app.Usage = ""

  app.Flags = GlobalFlags()
  app.Commands = Commands()
  app.CommandNotFound = CommandNotFound
  app.Before = beforeHook
  app.After = afterHook
  app.RunAndExitOnError()

  if !CommandSuccess {
    os.Exit(1)
  }
}

func beforeHook(c *cli.Context) error {
  setLogLevel(c)
  preReqCheck(c)
  setComposeBinary(c)
  setComposeProjectName(c)
  setComposeTemplate(c)
  return nil
}

func afterHook(c *cli.Context) error {
  // clean up compose template if it exists
  if file := os.Getenv("LC_BASE_COMPOSE_FILE"); len(file) > 0 {
    logrus.Debugf("attempting to remove base compose file: %v", file)
    if err := os.Remove(file); err != nil {
      return err
    }
  }
  return nil
}

func setLogLevel(c *cli.Context) {
  if c.GlobalBool("debug") {
    logrus.SetLevel(logrus.DebugLevel)
  } else {
    logrus.SetLevel(logrus.InfoLevel)
  }
}

func preReqCheck(c *cli.Context) {
  // TODO: replace this with checking presence and version of local-docker-stack
  if _, err := exec.LookPath("docker"); err != nil {
    logrus.Fatal("could not find docker, please install local-docker-stack")
  }
  dockerCompose := c.GlobalString("docker-compose")
  if _, err := exec.LookPath(dockerCompose); err != nil {
    logrus.Fatalf("could not find docker compose binary: %q, please install local-docker-stack", dockerCompose)
  }

  if versionString, versionComponents, err := helpers.GetDockerComposeVersion(c); err != nil {
    logrus.Warnf("failed checking docker-compose version. Note that lc only supports docker-compose 1.5.0 or higher")
  } else {
    major, minor := versionComponents[0], versionComponents[1]
    // assuming we won't see any docker-compose versions less than 1.x
    if major == 1 && minor < 5 {
      logrus.Fatalf("found docker-compose version %s, lc only supports docker-compose 1.5.0 or higher", versionString)
    }
  }

  if err := helpers.EnsureDockerConnectivity(); err != nil {
    ip, _ := helpers.DockerIp()
    logrus.Fatalf("could not connect to docker daemon at %q, err: %q.\n%s", ip, err, helpers.DockerDebugMsg)

  }
}

func setComposeBinary(c *cli.Context) {
  os.Setenv("DOCKER_COMPOSE_BINARY", c.GlobalString("docker-compose"))
}

func setComposeProjectName(c *cli.Context) {
  var invalidChars = regexp.MustCompile("[^a-z0-9]")
  projectName := c.GlobalString("project-name")
  if len(projectName) == 0 {
    logrus.Debug("using current working directory for compose project name")
    path, _ := os.Getwd()
    projectName = filepath.Base(path)
  } else {
    logrus.Debugf("using configured value: %q for project name", projectName)
  }
  projectName = invalidChars.ReplaceAllString(strings.ToLower(projectName), "")
  os.Setenv("COMPOSE_PROJECT_NAME", projectName)
}

func setComposeTemplate(c *cli.Context) {
  templateName := c.GlobalString("template")
  if len(templateName) > 0 {
    if yaml, err := template.Get(templateName); err == nil {
      file := createTempComposeFile(yaml)
      logrus.Debugf("setting LC_BASE_COMPOSE_FILE to %v", file)
      os.Setenv("LC_BASE_COMPOSE_FILE", file)
    } else {
      logrus.Panicf("template %q does not exist", templateName)
    }
  }

  dataContainers := template.GetSharedExternalDataContainers(templateName)
  for _, dataContainer := range dataContainers {
    if err := dataContainer.Ensure(); err != nil {
      logrus.Panic("unable to create data container")
    }
  }
}

func createTempComposeFile(yaml string) string {
  cwd, _ := os.Getwd()
  fh, err := ioutil.TempFile(cwd, "lc_docker_compose_template")
  if err != nil {
    logrus.Panic("could not create temporary yaml file")
  }
  defer fh.Close()
  _, err = fh.WriteString(yaml)
  if err != nil {
    logrus.Panic("could not write to temporary yaml file")
  }
  return fh.Name()
}
<commit_msg>cleanup template file even when interrupted<commit_after>package main

import (
  "io/ioutil"
  "os"
  "os/exec"
  "os/signal"
  "path/filepath"
  "regexp"
  "strings"
  "syscall"

  "github.com/codegangsta/cli"
  "github.com/Sirupsen/logrus"
  "stash0.eng.lancope.local/dev-infrastructure/project-lifecycle/template"
  "stash0.eng.lancope.local/dev-infrastructure/project-lifecycle/helpers"
)

func main() {
  if err := LoadConfigFile("lc.yml"); err != nil {
    panic(err)
  }

  app := cli.NewApp()
  app.Name = Name
  app.Version = Version
  app.Author = "lancope"
  app.Email = ""
  app.Usage = ""

  app.Flags = GlobalFlags()
  app.Commands = Commands()
  app.CommandNotFound = CommandNotFound
  app.Before = beforeHook
  app.After = afterHook
  app.RunAndExitOnError()

  if !CommandSuccess {
    os.Exit(1)
  }
}

func beforeHook(c *cli.Context) error {
  setLogLevel(c)
  preReqCheck(c)
  setComposeBinary(c)
  setComposeProjectName(c)
  setComposeTemplate(c)
  addSignalListener()
  return nil
}

func afterHook(c *cli.Context) error {
  return removeComposeTemplate()
}

func addSignalListener() {
  c := make(chan os.Signal, 1)
  signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  go func() {
    <-c
    removeComposeTemplate()
    os.Exit(2)
  }()
}

func removeComposeTemplate() error {
  // clean up compose template if it exists
  if file := os.Getenv("LC_BASE_COMPOSE_FILE"); len(file) > 0 {
    logrus.Debugf("attempting to remove base compose file: %v", file)
    if err := os.Remove(file); err != nil {
      return err
    }
  }
  return nil
}

func setLogLevel(c *cli.Context) {
  if c.GlobalBool("debug") {
    logrus.SetLevel(logrus.DebugLevel)
  } else {
    logrus.SetLevel(logrus.InfoLevel)
  }
}

func preReqCheck(c *cli.Context) {
  // TODO: replace this with checking presence and version of local-docker-stack
  if _, err := exec.LookPath("docker"); err != nil {
    logrus.Fatal("could not find docker, please install local-docker-stack")
  }
  dockerCompose := c.GlobalString("docker-compose")
  if _, err := exec.LookPath(dockerCompose); err != nil {
    logrus.Fatalf("could not find docker compose binary: %q, please install local-docker-stack", dockerCompose)
  }

  if versionString, versionComponents, err := helpers.GetDockerComposeVersion(c); err != nil {
    logrus.Warnf("failed checking docker-compose version. Note that lc only supports docker-compose 1.5.0 or higher")
  } else {
    major, minor := versionComponents[0], versionComponents[1]
    // assuming we won't see any docker-compose versions less than 1.x
    if major == 1 && minor < 5 {
      logrus.Fatalf("found docker-compose version %s, lc only supports docker-compose 1.5.0 or higher", versionString)
    }
  }

  if err := helpers.EnsureDockerConnectivity(); err != nil {
    ip, _ := helpers.DockerIp()
    logrus.Fatalf("could not connect to docker daemon at %q, err: %q.\n%s", ip, err, helpers.DockerDebugMsg)

  }
}

func setComposeBinary(c *cli.Context) {
  os.Setenv("DOCKER_COMPOSE_BINARY", c.GlobalString("docker-compose"))
}

func setComposeProjectName(c *cli.Context) {
  var invalidChars = regexp.MustCompile("[^a-z0-9]")
  projectName := c.GlobalString("project-name")
  if len(projectName) == 0 {
    logrus.Debug("using current working directory for compose project name")
    path, _ := os.Getwd()
    projectName = filepath.Base(path)
  } else {
    logrus.Debugf("using configured value: %q for project name", projectName)
  }
  projectName = invalidChars.ReplaceAllString(strings.ToLower(projectName), "")
  os.Setenv("COMPOSE_PROJECT_NAME", projectName)
}

func setComposeTemplate(c *cli.Context) {
  templateName := c.GlobalString("template")
  if len(templateName) > 0 {
    if yaml, err := template.Get(templateName); err == nil {
      file := createTempComposeFile(yaml)
      logrus.Debugf("setting LC_BASE_COMPOSE_FILE to %v", file)
      os.Setenv("LC_BASE_COMPOSE_FILE", file)
    } else {
      logrus.Panicf("template %q does not exist", templateName)
    }
  }

  dataContainers := template.GetSharedExternalDataContainers(templateName)
  for _, dataContainer := range dataContainers {
    if err := dataContainer.Ensure(); err != nil {
      logrus.Panic("unable to create data container")
    }
  }
}

func createTempComposeFile(yaml string) string {
  cwd, _ := os.Getwd()
  fh, err := ioutil.TempFile(cwd, "lc_docker_compose_template")
  if err != nil {
    logrus.Panic("could not create temporary yaml file")
  }
  defer fh.Close()
  _, err = fh.WriteString(yaml)
  if err != nil {
    logrus.Panic("could not write to temporary yaml file")
  }
  return fh.Name()
}
<|endoftext|>


<commit_before>package main

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

	"github.com/gorilla/mux"
)

// func Index(w http.ResponseWriter, r *http.Request) {
// 	fmt.Fprintln(w, "Welcome!")
// }

func TodoIndex(w http.ResponseWriter, r *http.Request) {
	// todos := Todos{
	// 	Todo{Name: "Write presentation"},
	// 	Todo{Name: "Host meetup"},
	// }

	// var movies []Movie
	// csvFile, _ := os.Open("../movie_metadata.csv")
	// reader := csv.NewReader(bufio.NewReader(csvFile))
	// for {
	// 	// fmt.Println("hellosrse")
	// 	line, error := reader.Read()
	// 	if error == io.EOF {
	// 		break
	// 	} else if error != nil {
	// 		fmt.Println("hellofff")
	// 		log.Fatal(error)
	// 	}
	// 	movies = append(movies, Movie{
	// 		MovieTitle:   line[11],
	// 		DirectorName: line[1],
	// 		IMDBScore:    line[25],
	// 	})
	// }
	// movieJson, _ := json.Marshal(movies)
	// fmt.Println(string(movieJson))
	movies := getMovies()
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(movies); err != nil {
		panic(err)
	}
}

func TodoShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	todoId := vars["todoId"]
	fmt.Fprintln(w, "Todo show:", todoId)
}
<commit_msg>Update handlers.go<commit_after>package main

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

	"github.com/gorilla/mux"
)

// func Index(w http.ResponseWriter, r *http.Request) {
// 	fmt.Fprintln(w, "Welcome!")
// }

func TodoIndex(w http.ResponseWriter, r *http.Request) {
	// todos := Todos{
	// 	Todo{Name: "Write presentation"},
	// 	Todo{Name: "Host meetup"},
	// }
	movies := getMovies()
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(movies); err != nil {
		panic(err)
	}
}

func TodoShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	todoId := vars["todoId"]
	fmt.Fprintln(w, "Todo show:", todoId)
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"
)

const inputFile = "day1_input.txt"
const goalFloor = -1

func main() {
	file, err := os.Open(inputFile)
	if err != nil {
		log.Fatal(err)
	}
	total, entryPoint := doWork(file, goalFloor)
	fmt.Println("Final Floor:", total)
	fmt.Printf("Entered Basement at: %d\n", entryPoint)
}

// read each line of the file, building the total and looking for the expected
// entry point
func doWork(file *os.File, goalFloor int) (int, int) {
	scanner := bufio.NewScanner(file)
	total := 0
	entryPoint := 0
	entryFound := false
	for scanner.Scan() {
		line := scanner.Text()
		if !entryFound {
			index := 0
			index, entryFound = FindEntryPoint(line, goalFloor)
			entryPoint += index
		}
		total += Count(line)
	}
	return total, entryPoint
}

// Count returns the final floor from a string
func Count(x string) int {
	return strings.Count(x, "(") - strings.Count(x, ")")
}

// FindEntryPoint returns the first step at which a given floor is reached
func FindEntryPoint(input string, floor int) (int, bool) {
	total := 0
	for index, runeValue := range input {
		strVal := string(runeValue)
		if strVal == "(" {
			total++
		} else if strVal == ")" {
			total--
		}
		if total == floor {
			return index + 1, true
		}
	}
	return len(input), false
}
<commit_msg>using global variables to track entry point and current floor found another way to get correct values across multiple lines of text<commit_after>package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

const inputFile = "day1_input.txt"
const goalFloor = -1

var currentFloor = 0
var entryPoint = 0

func main() {
	file, err := os.Open(inputFile)
	if err != nil {
		log.Fatal(err)
	}
	doWork(file, goalFloor)
	fmt.Println("Final Floor:", currentFloor)
	fmt.Printf("Entered Basement at: %d\n", entryPoint)
}

// read each line of the file, building the total and
//looking for the expected entry point
func doWork(file *os.File, goalFloor int) {
	scanner := bufio.NewScanner(file)
	scanner.Split(bufio.ScanBytes)
	counter := 0
	entryFound := false
	for scanner.Scan() {
		counter += Count(scanner.Text())
		if !entryFound && currentFloor == goalFloor {
			entryFound = true
			entryPoint = counter
		}
	}
}

// Count returns the final floor from a string
func Count(x string) int {
	if x == "(" {
		currentFloor++
		return 1
	} else if x == ")" {
		currentFloor--
		return 1
	}
	return 0
}
<|endoftext|>


<commit_before>package main

import (
	"reflect"
	"testing"
)

func TestAnalyzers(t *testing.T) {
	ts := []struct {
		name     string
		args     []string
		expected [][]string
	}{
		{
			name:     "tests -map-name",
			args:     []string{"-replay", "testdata/larvavsMini.rep", "-map-name", "-o", "none"},
			expected: [][]string{{"Transistor1.2"}},
		},
	}
	for _, tc := range ts {
		t.Run(tc.name, func(t *testing.T) {
			executor, _, errs := buildAnalyzerExecutor(tc.args)
			if len(errs) != 0 {
				t.Errorf("Expected no errors building AnalyzerExecutor but: %v", errs)
				t.FailNow()
			}
			results, errs := executor.ExecuteWithResults()
			if len(errs) != 0 {
				t.Errorf("Expected no errors executing AnalyzerExecutor but: %v", errs)
				t.FailNow()
			}
			if !reflect.DeepEqual(tc.expected, results) {
				t.Errorf("Expected: %v, but got: %v", tc.expected, results)
				t.FailNow()
			}
		})
	}
}
<commit_msg>Tests a bunch of analyzers.<commit_after>package main

import (
	"reflect"
	"testing"
)

func TestAnalyzers(t *testing.T) {
	ts := []struct {
		name     string
		args     []string
		expected [][]string
	}{
		{
			name: "tests -map-name",
			args: []string{
				"-is-1v1", // TODO: this should be true; review!
				"-is-2v2",
				"-is-there-a-race", "protoss",
				"-map-name",
				"-matchup",
				"-my-game",
				"-my-matchup", // TODO: this should be ZvP; review!
				"-my-name",
				"-my-race",
				"-my-race-is", "zerg",
				"-me", "adultrabbit",
				"-replay", "testdata/larvavsMini.rep", "-o", "none",
			},
			expected: [][]string{{"false", "false", "true", "Transistor1.2", "PvZ", "true", "PvZ", "adultrabbit", "Zerg", "true"}},
		},
	}
	for _, tc := range ts {
		t.Run(tc.name, func(t *testing.T) {
			executor, _, errs := buildAnalyzerExecutor(tc.args)
			if len(errs) != 0 {
				t.Errorf("Expected no errors building AnalyzerExecutor but: %v", errs)
				t.FailNow()
			}
			results, errs := executor.ExecuteWithResults()
			if len(errs) != 0 {
				t.Errorf("Expected no errors executing AnalyzerExecutor but: %v", errs)
				t.FailNow()
			}
			if !reflect.DeepEqual(tc.expected, results) {
				t.Errorf("Expected: %v, but got: %v", tc.expected, results)
				t.FailNow()
			}
		})
	}
}
<|endoftext|>


<commit_before>package main

import (
	"strings"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/statsd_exporter/pkg/mapper"
	"github.com/stretchr/testify/assert"
)

type mockMapper struct {
	labels  prometheus.Labels
	present bool
	name    string
	action  mapper.ActionType
}

func (m *mockMapper) GetMapping(metricName string, metricType mapper.MetricType) (*mapper.MetricMapping, prometheus.Labels, bool) {

	mapping := mapper.MetricMapping{Name: m.name, Action: m.action}

	return &mapping, m.labels, m.present

}

func (m *mockMapper) InitFromFile(string) error {
	return nil
}

func TestProcessLine(t *testing.T) {

	type testCase struct {
		line     string
		name     string
		labels   map[string]string
		value    float64
		present  bool
		willFail bool
		action   mapper.ActionType
		strict   bool
	}

	testCases := []testCase{
		{
			line: "my.simple.metric 9001 1534620625",
			name: "my_simple_metric",
			labels: map[string]string{
				"foo":  "bar",
				"zip":  "zot",
				"name": "alabel",
			},
			present: true,
			value:   float64(9001),
		},
		{
			line: "my.simple.metric.baz 9002 1534620625",
			name: "my_simple_metric",
			labels: map[string]string{
				"baz": "bat",
			},
			present: true,
			value:   float64(9002),
		},
		{
			line:    "my.nomap.metric 9001 1534620625",
			name:    "my_nomap_metric",
			value:   float64(9001),
			present: false,
		},
		{
			line:     "my.nomap.metric.novalue 9001 ",
			name:     "my_nomap_metric_novalue",
			labels:   nil,
			value:    float64(9001),
			willFail: true,
		},
		{
			line:     "my.mapped.metric.drop 55 1534620625",
			name:     "my_mapped_metric_drop",
			present:  true,
			willFail: true,
			action:   mapper.ActionTypeDrop,
		},
		{
			line:     "my.mapped.strict.metric 55 1534620625",
			name:     "my_mapped_strict_metric",
			value:    float64(55),
			present:  true,
			willFail: false,
			strict:   true,
		},
		{
			line:     "my.mapped.strict.metric.drop 55 1534620625",
			name:     "my_mapped_strict_metric_drop",
			present:  false,
			willFail: true,
			strict:   true,
		},
	}

	c := newGraphiteCollector()

	for _, testCase := range testCases {

		if testCase.present {
			c.mapper = &mockMapper{
				name:    testCase.name,
				labels:  testCase.labels,
				action:  testCase.action,
				present: testCase.present,
			}
		} else {
			c.mapper = &mockMapper{
				present: testCase.present,
			}
		}

		c.strictMatch = testCase.strict
		c.processLine(testCase.line)

	}

	c.ch <- nil
	for _, k := range testCases {
		originalName := strings.Split(k.line, " ")[0]
		sample := c.samples[originalName]
		if k.willFail {
			assert.Nil(t, sample, "Found %s", k.name)
		} else {
			if assert.NotNil(t, sample, "Missing %s", k.name) {
				assert.Equal(t, k.name, sample.Name)
				assert.Equal(t, k.labels, sample.Labels)
				assert.Equal(t, k.value, sample.Value)
			}
		}
	}
}
<commit_msg>Add missing license header to main_test.go<commit_after>// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"strings"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/statsd_exporter/pkg/mapper"
	"github.com/stretchr/testify/assert"
)

type mockMapper struct {
	labels  prometheus.Labels
	present bool
	name    string
	action  mapper.ActionType
}

func (m *mockMapper) GetMapping(metricName string, metricType mapper.MetricType) (*mapper.MetricMapping, prometheus.Labels, bool) {

	mapping := mapper.MetricMapping{Name: m.name, Action: m.action}

	return &mapping, m.labels, m.present

}

func (m *mockMapper) InitFromFile(string) error {
	return nil
}

func TestProcessLine(t *testing.T) {

	type testCase struct {
		line     string
		name     string
		labels   map[string]string
		value    float64
		present  bool
		willFail bool
		action   mapper.ActionType
		strict   bool
	}

	testCases := []testCase{
		{
			line: "my.simple.metric 9001 1534620625",
			name: "my_simple_metric",
			labels: map[string]string{
				"foo":  "bar",
				"zip":  "zot",
				"name": "alabel",
			},
			present: true,
			value:   float64(9001),
		},
		{
			line: "my.simple.metric.baz 9002 1534620625",
			name: "my_simple_metric",
			labels: map[string]string{
				"baz": "bat",
			},
			present: true,
			value:   float64(9002),
		},
		{
			line:    "my.nomap.metric 9001 1534620625",
			name:    "my_nomap_metric",
			value:   float64(9001),
			present: false,
		},
		{
			line:     "my.nomap.metric.novalue 9001 ",
			name:     "my_nomap_metric_novalue",
			labels:   nil,
			value:    float64(9001),
			willFail: true,
		},
		{
			line:     "my.mapped.metric.drop 55 1534620625",
			name:     "my_mapped_metric_drop",
			present:  true,
			willFail: true,
			action:   mapper.ActionTypeDrop,
		},
		{
			line:     "my.mapped.strict.metric 55 1534620625",
			name:     "my_mapped_strict_metric",
			value:    float64(55),
			present:  true,
			willFail: false,
			strict:   true,
		},
		{
			line:     "my.mapped.strict.metric.drop 55 1534620625",
			name:     "my_mapped_strict_metric_drop",
			present:  false,
			willFail: true,
			strict:   true,
		},
	}

	c := newGraphiteCollector()

	for _, testCase := range testCases {

		if testCase.present {
			c.mapper = &mockMapper{
				name:    testCase.name,
				labels:  testCase.labels,
				action:  testCase.action,
				present: testCase.present,
			}
		} else {
			c.mapper = &mockMapper{
				present: testCase.present,
			}
		}

		c.strictMatch = testCase.strict
		c.processLine(testCase.line)

	}

	c.ch <- nil
	for _, k := range testCases {
		originalName := strings.Split(k.line, " ")[0]
		sample := c.samples[originalName]
		if k.willFail {
			assert.Nil(t, sample, "Found %s", k.name)
		} else {
			if assert.NotNil(t, sample, "Missing %s", k.name) {
				assert.Equal(t, k.name, sample.Name)
				assert.Equal(t, k.labels, sample.Labels)
				assert.Equal(t, k.value, sample.Value)
			}
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"net"
	"testing"
	"time"

	dhcp "github.com/krolaw/dhcp4"
	"github.com/stretchr/testify/assert"
)

func TestNewDHCPServer(t *testing.T) {
	expected := &dhcpServerHandler{
		ip:            net.ParseIP(DHCP_SERVER_ADDR),
		start:         net.ParseIP(DHCP_SERVER_LEASE_START_ADDR),
		leaseDuration: DHCP_LEASE_DURATION * time.Minute,
		leases:        make(map[int]lease, DHCP_LEASE_COUNT),
		leaseRange:    DHCP_LEASE_RANGE,
		options: dhcp.Options{
			dhcp.OptionTFTPServerName:   []byte(TFTP_SERVER_ADDR),
			dhcp.OptionBootFileName:     []byte(PXELINUX_LOADER),
			dhcp.OptionDomainNameServer: []byte(DNS_SERVER_ADDR),
		},
	}

	actual := newDHCPServer()
	assert.Equal(t, expected, actual)
}

func TestFreeLease_OK(t *testing.T) {
	dhcpServer := newDHCPServer()
	NotExpected := -1
	actual := dhcpServer.freeLease()
	assert.NotEqual(t, NotExpected, actual)
}

func TestServeDHCPDiscover_OK(t *testing.T) {
	dhcpServer := newDHCPServer()

	expected := dhcp.ReplyPacket(dhcp.NewPacket(dhcp.BootReply), dhcp.Offer, dhcpServer.ip,
		dhcp.IPAdd(dhcpServer.start, dhcpServer.freeLease()),
		dhcpServer.leaseDuration, dhcpServer.options.SelectOrderOrAll(nil))
	actual := dhcpServer.ServeDHCP(dhcp.NewPacket(dhcp.BootReply), dhcp.Discover, nil)

	// TODO: Need a strong assertion
	// See Issue: https://github.com/simar7/xserver/issues/8
	assert.ObjectsAreEqual(expected, actual)
}

func TestServeDHCPInvalidRequest_OK(t *testing.T) {
	dhcpServer := newDHCPServer()

	expected := dhcp.ReplyPacket(dhcp.NewPacket(dhcp.BootReply), dhcp.NAK, dhcpServer.ip, nil, 0, nil)
	actual := dhcpServer.ServeDHCP(dhcp.NewPacket(dhcp.BootReply), dhcp.Request, dhcpServer.options)

	assert.Equal(t, expected, actual)
}

func TestServeDHCPValidRequest_OK(t *testing.T) {
	dhcpServer := newDHCPServer()
	p := dhcp.NewPacket(dhcp.BootReply)
	// Request the IP from the DHCP Server
	p.SetCIAddr(net.ParseIP("172.10.0.2"))

	reqIP := net.IP(dhcpServer.options[dhcp.OptionRequestedIPAddress])
	if reqIP == nil {
		reqIP = net.IP(p.CIAddr())
		log.Print("[DEBUG] ", "Request IP: ", reqIP)
	}

	expected := dhcp.ReplyPacket(p, dhcp.ACK, dhcpServer.ip, reqIP,
		dhcpServer.leaseDuration, dhcpServer.options.SelectOrder(dhcpServer.options[dhcp.OptionParameterRequestList]))
	actual := dhcpServer.ServeDHCP(p, dhcp.Request, dhcp.Options{
		dhcp.OptionTFTPServerName:   []byte(TFTP_SERVER_ADDR),
		dhcp.OptionBootFileName:     []byte(PXELINUX_LOADER),
		dhcp.OptionDomainNameServer: []byte(DNS_SERVER_ADDR),
	})

	assert.Equal(t, expected, actual)
}
<commit_msg>dhcp: Adding test for DHCP release<commit_after>package main

import (
	"log"
	"net"
	"testing"
	"time"

	dhcp "github.com/krolaw/dhcp4"
	"github.com/stretchr/testify/assert"
)

func TestNewDHCPServer(t *testing.T) {
	expected := &dhcpServerHandler{
		ip:            net.ParseIP(DHCP_SERVER_ADDR),
		start:         net.ParseIP(DHCP_SERVER_LEASE_START_ADDR),
		leaseDuration: DHCP_LEASE_DURATION * time.Minute,
		leases:        make(map[int]lease, DHCP_LEASE_COUNT),
		leaseRange:    DHCP_LEASE_RANGE,
		options: dhcp.Options{
			dhcp.OptionTFTPServerName:   []byte(TFTP_SERVER_ADDR),
			dhcp.OptionBootFileName:     []byte(PXELINUX_LOADER),
			dhcp.OptionDomainNameServer: []byte(DNS_SERVER_ADDR),
		},
	}

	actual := newDHCPServer()
	assert.Equal(t, expected, actual)
}

func TestFreeLease_OK(t *testing.T) {
	dhcpServer := newDHCPServer()
	NotExpected := -1
	actual := dhcpServer.freeLease()
	assert.NotEqual(t, NotExpected, actual)
}

func TestServeDHCPDiscover_OK(t *testing.T) {
	dhcpServer := newDHCPServer()

	expected := dhcp.ReplyPacket(dhcp.NewPacket(dhcp.BootReply), dhcp.Offer, dhcpServer.ip,
		dhcp.IPAdd(dhcpServer.start, dhcpServer.freeLease()),
		dhcpServer.leaseDuration, dhcpServer.options.SelectOrderOrAll(nil))
	actual := dhcpServer.ServeDHCP(dhcp.NewPacket(dhcp.BootReply), dhcp.Discover, nil)

	// TODO: Need a strong assertion
	// See Issue: https://github.com/simar7/xserver/issues/8
	assert.ObjectsAreEqual(expected, actual)
}

func TestServeDHCPInvalidRequest_OK(t *testing.T) {
	dhcpServer := newDHCPServer()

	expected := dhcp.ReplyPacket(dhcp.NewPacket(dhcp.BootReply), dhcp.NAK, dhcpServer.ip, nil, 0, nil)
	actual := dhcpServer.ServeDHCP(dhcp.NewPacket(dhcp.BootReply), dhcp.Request, dhcpServer.options)

	assert.Equal(t, expected, actual)
}

func TestServeDHCPValidRequest_OK(t *testing.T) {
	dhcpServer := newDHCPServer()
	p := dhcp.NewPacket(dhcp.BootReply)
	// Request the IP from the DHCP Server
	p.SetCIAddr(net.ParseIP("172.10.0.2"))

	reqIP := net.IP(dhcpServer.options[dhcp.OptionRequestedIPAddress])
	if reqIP == nil {
		reqIP = net.IP(p.CIAddr())
		log.Print("[DEBUG] ", "Request IP: ", reqIP)
	}

	expected := dhcp.ReplyPacket(p, dhcp.ACK, dhcpServer.ip, reqIP,
		dhcpServer.leaseDuration, dhcpServer.options.SelectOrder(dhcpServer.options[dhcp.OptionParameterRequestList]))
	actual := dhcpServer.ServeDHCP(p, dhcp.Request, dhcp.Options{
		dhcp.OptionTFTPServerName:   []byte(TFTP_SERVER_ADDR),
		dhcp.OptionBootFileName:     []byte(PXELINUX_LOADER),
		dhcp.OptionDomainNameServer: []byte(DNS_SERVER_ADDR),
	})

	assert.Equal(t, expected, actual)
}

func TestServeDHCPRelease_OK(t *testing.T) {
	dhcpServer := newDHCPServer()
	p := dhcp.NewPacket(dhcp.BootReply)
	// Request the IP from the DHCP Server
	p.SetCIAddr(net.ParseIP("172.10.0.2"))

	expected := dhcp.Packet(nil)
	actual := dhcpServer.ServeDHCP(p, dhcp.Release, nil)

	assert.Equal(t, expected, actual)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"net/http"
	"net/url"
)

var (
	APIAddress = "http://localhost:8080"
)

func ExampleGetSuccessResponseIfRequestMethodIsPost() {
	entity := url.Values{}
	rsp, err := http.PostForm(APIAddress+"/task/run", entity)
	if err != nil {
		fmt.Println(err)
		return
	}

	if rsp.StatusCode != 200 {
		fmt.Printf("UnSuccesful Response with status: %s", rsp.Status)
	} else {
		fmt.Printf("Successful Response with status: %s", rsp.Status)
	}

	//Output: Successful Response with status: 200 OK
}

func ExampleGetUnSuccessfulResponseIfRequestMethodIsGet() {
	rsp, err := http.Get(APIAddress + "/task/run")
	if err != nil {
		fmt.Println(err)
		return
	}

	if rsp.StatusCode != 200 {
		fmt.Printf("UnSuccesful Response with status: %s", rsp.Status)
	} else {
		fmt.Printf("Successful Response with status: %s", rsp.Status)
	}

	//Output: UnSuccessful Response with status: 500 Internal Server Error
}
<commit_msg>fix typo<commit_after>package main

import (
	"fmt"
	"net/http"
	"net/url"
)

var (
	APIAddress = "http://localhost:8080"
)

func ExampleGetSuccessResponseIfRequestMethodIsPost() {
	entity := url.Values{}
	rsp, err := http.PostForm(APIAddress+"/task/run", entity)
	if err != nil {
		fmt.Println(err)
		return
	}

	if rsp.StatusCode != 200 {
		fmt.Printf("UnSuccessful Response with status: %s", rsp.Status)
	} else {
		fmt.Printf("Successful Response with status: %s", rsp.Status)
	}

	//Output: Successful Response with status: 200 OK
}

func ExampleGetUnSuccessfulResponseIfRequestMethodIsGet() {
	rsp, err := http.Get(APIAddress + "/task/run")
	if err != nil {
		fmt.Println(err)
		return
	}

	if rsp.StatusCode != 200 {
		fmt.Printf("UnSuccessful Response with status: %s", rsp.Status)
	} else {
		fmt.Printf("Successful Response with status: %s", rsp.Status)
	}

	//Output: UnSuccessful Response with status: 500 Internal Server Error
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"testing"
)

func BenchmarkHello(b *testing.B) {
	for i := 0; i < b.N; i++ {
		ds := Datasource{Name: fmt.Sprintf("datasource %v", i)}
		addItemToState(ds)
	}
}

// All state is not reset
func TestDeleteFileNonExisting(t *testing.T) {
	file := "/slkjasd/wefoiwef/8c2f54b252f1a23b00768bf94bfa48db/"
	err := deleteFile(file)
	if err == true {
		t.Fatal(fmt.Sprintf("Deleting non existing file did not return error: %v", file))
	}
}
func TestDeleteFileNoName(t *testing.T) {
	file := ""
	err := deleteFile(file)
	if err == true {
		t.Fatal(fmt.Sprintf("Deleting file with no name does not return error: %v", file))
	}
}

func TestDeleteFile(t *testing.T) {
	file := "/tmp/graphite-news-test-file-safe-to-delete-8c2f54b252f1a23b00768bf94bfa48db"
	// remove the file if it exists, ignore errors, and defer one too
	// just to be sure everything is gone and clean after the tests
	os.Remove(file)
	//defer os.Remove(file)

	// create the file
	filehandle, _ := os.Create(file)
	filehandle.Close()

	err := deleteFile(file)
	if err == true {
		t.Fatal(fmt.Sprintf("Deleting file returned error: %v", file))
	}

	// check filesystem to see file is gone
	_, err1 := os.Stat(file)
	if err1 == nil {
		t.Fatal(fmt.Sprintf("Tried deleting file, did not return error but still exists: %s", file))
	}
}

func TestGettingAsset(t *testing.T) {
	file := fmt.Sprintf("%vindex.html", staticAssetsURL)[1:]
	data, _ := Asset(file)
	if len(data) == 0 {
		t.Fatal(fmt.Sprintf("Could not load static asset: %v", file))
	}
}

func TestSingleDsIntoState(t *testing.T) {
	tmp := len(State.Vals)
	ds1 := Datasource{Name: "some name"}
	addItemToState(ds1)
	if (len(State.Vals) - tmp) != 1 {
		t.Fatal("Not able to add datasource to internal state")
	}

	// find it back
	ds2 := getDSbyName(ds1.Name)
	if ds1.Name != ds2.Name {
		t.Fatal("getDSbyName did not return DS that we know exists")
	}

	// now delete it
	if deleteDSbyName(ds1.Name) {
		fmt.Printf("%+v", State.Vals)
		// all went well
		if len(State.Vals) != 0 {
			t.Fatal("After removing only DS, state is not empty")
		}
		ds3 := getDSbyName(ds1.Name)
		if ds1.Name == ds3.Name {
			t.Fatal("getDSbyName did return DS that should not have been there")
		}
	} else {
		// fatal
		t.Fatal("Was not allowed to delete ds known to exist")
	}
}

func TestDuplicateEntriesIntoState(t *testing.T) {
	tmp := len(State.Vals)
	ds1 := Datasource{Name: "TestDuplicateEntriesIntoState same name"}
	ds2 := Datasource{Name: "TestDuplicateEntriesIntoState same name"}
	addItemToState(ds1)
	addItemToState(ds2)
	if (len(State.Vals) - tmp) > 1 {
		t.Fatal("Able to add more than one data source with the same name")
	}
}

func TestDontStoreMoreThan1k(t *testing.T) {
	// test that we dont keep more than maxState items in the state
	// and that when we go above it, we keep the last values (and not
	// the oldest ones)

	// reset internal state so that we know exactly what the last value
	// should be in the internal state
	State.Vals = nil
	const testString string = "TestDontStoreMoreThanMaxState, item: "

	ds := Datasource{Name: "tmp"}
	for i := 1; i < maxState+11; i++ {
		ds.Name = fmt.Sprintf("%v %v", testString, i)
		addItemToState(ds)
	}
	if len(State.Vals) > maxState {
		t.Fatal("Able to add more than maxState items into State.Vals")
	}
	if len(State.Vals) < maxState-10 {
		t.Fatal("Too few items in State (e.g. got reset somewhere in the middle?)")
	}

	lastItem := State.Vals[len(State.Vals)-1:][0]
	if lastItem.Name != ds.Name {
		t.Fatal(fmt.Sprintf("The expected last item (after adding more then maxState items) was [%v] but actually found [%v]!", ds.Name, lastItem.Name))
	}
}

func TestParsing(t *testing.T) {

	type testpair struct {
		incr int
		line string
	}

	// integer indicates with how much the count of internal state should go up
	// (could be 0, eg. not valid test input, or ds already captured)
	// Also, each line should have a non-nil Create_date
	var testCases = []testpair{
		{1, "launchctl-carbon.stdout:24/08/2014 17:59:53 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Recovery_HD/df_complex-free.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{0, "astt"},
		{0, "launchctl-carbon.stdout:24/08/2014 17:59:53 :: [creates] creating database file / (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "13/09/2014 23:10:56 :: [creates] creating database file /opt/graphite/storage/whisper/local/random/diceroll.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 17:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Recovery_HD/df_complex-reserved.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 17:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Recovery_HD/df_complex-used.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 20:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Media/df_complex-free.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 20:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Media/df_complex-reserved.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 20:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Media/df_complex-used.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 23:10:40 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/curl_xml-default/gauge-tvseries_watched-Babylon_5.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 23:10:40 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/curl_xml-default/gauge-tvseries_total-Babylon_5.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{0, "launchctl-carbon.stdout:24/08/2014 23:10:40 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/curl_xml-default/.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
	}
	State.Vals = nil // start fresh
	prev_count := len(State.Vals)

	for _, test := range testCases {
		parseLine(test.line)

		if len(State.Vals) != prev_count+test.incr {
			t.Fatal(fmt.Sprintf("Parsed line, should have seen %v new entries, saw %v. Line: %v", test.incr, len(State.Vals)-prev_count, test))
		}
		prev_count = len(State.Vals)

		// Check date parseing
		last_ds := State.Vals[len(State.Vals)-1:][0]
		// Do any checking on the actual values for the data source (not complete yet)
		if last_ds.Create_date.IsZero() {
			t.Fatal(fmt.Sprintf("Data source has invalid Create_date: %+v", last_ds))
		}
		if len(last_ds.Name) < 1 {
			t.Fatal(fmt.Sprintf("Data source doesnt have proper Name: %+v", last_ds))
		}
	}
}
<commit_msg>fixing up unit tests<commit_after>package main

import (
	"fmt"
	"os"
	"testing"
)

func BenchmarkHello(b *testing.B) {
	for i := 0; i < b.N; i++ {
		ds := Datasource{Name: fmt.Sprintf("datasource %v", i)}
		addItemToState(ds)
	}
}

// All state is not reset
func TestDeleteFileNonExisting(t *testing.T) {
	file := "/slkjasd/wefoiwef/8c2f54b252f1a23b00768bf94bfa48db/"
	err := deleteFile(file)
	if err == true {
		t.Fatal(fmt.Sprintf("Deleting non existing file did not return error: %v", file))
	}
}
func TestDeleteFileNoName(t *testing.T) {
	file := ""
	err := deleteFile(file)
	if err == true {
		t.Fatal(fmt.Sprintf("Deleting file with no name does not return error: %v", file))
	}
}

func TestDeleteFile(t *testing.T) {
	file := "/tmp/graphite-news-test-file-safe-to-delete-8c2f54b252f1a23b00768bf94bfa48db"
	// remove the file if it exists, ignore errors, and defer one too
	// just to be sure everything is gone and clean after the tests
	os.Remove(file)
	defer os.Remove(file)

	// create the file
	filehandle, _ := os.Create(file)
	filehandle.Close()

	result := deleteFile(file)
	if result == false {
		t.Fatal(fmt.Sprintf("Deleting file returned error: %v", file))
	}

	// check filesystem to see file is gone
	_, err1 := os.Stat(file)
	if err1 == nil {
		t.Fatal(fmt.Sprintf("Tried deleting file, did not return error but still exists: %s", file))
	}
}

func TestGettingAsset(t *testing.T) {
	file := fmt.Sprintf("%vindex.html", staticAssetsURL)[1:]
	data, _ := Asset(file)
	if len(data) == 0 {
		t.Fatal(fmt.Sprintf("Could not load static asset: %v", file))
	}
}

func TestSingleDsIntoState(t *testing.T) {
	tmp := len(State.Vals)
	ds1 := Datasource{Name: "some name"}
	addItemToState(ds1)
	if (len(State.Vals) - tmp) != 1 {
		t.Fatal("Not able to add datasource to internal state")
	}

	// find it back
	ds2 := getDSbyName(ds1.Name)
	if ds1.Name != ds2.Name {
		t.Fatal("getDSbyName did not return DS that we know exists")
	}

	// now delete it
	if deleteDSbyName(ds1.Name) {
		fmt.Printf("%+v", State.Vals)
		// all went well
		if len(State.Vals) != 0 {
			t.Fatal("After removing only DS, state is not empty")
		}
		ds3 := getDSbyName(ds1.Name)
		if ds1.Name == ds3.Name {
			t.Fatal("getDSbyName did return DS that should not have been there")
		}
	} else {
		// fatal
		t.Fatal("Was not allowed to delete ds known to exist")
	}
}

func TestDuplicateEntriesIntoState(t *testing.T) {
	tmp := len(State.Vals)
	ds1 := Datasource{Name: "TestDuplicateEntriesIntoState same name"}
	ds2 := Datasource{Name: "TestDuplicateEntriesIntoState same name"}
	addItemToState(ds1)
	addItemToState(ds2)
	if (len(State.Vals) - tmp) > 1 {
		t.Fatal("Able to add more than one data source with the same name")
	}
}

func TestDontStoreMoreThan1k(t *testing.T) {
	// test that we dont keep more than maxState items in the state
	// and that when we go above it, we keep the last values (and not
	// the oldest ones)

	// reset internal state so that we know exactly what the last value
	// should be in the internal state
	State.Vals = nil
	const testString string = "TestDontStoreMoreThanMaxState, item: "

	ds := Datasource{Name: "tmp"}
	for i := 1; i < maxState+11; i++ {
		ds.Name = fmt.Sprintf("%v %v", testString, i)
		addItemToState(ds)
	}
	if len(State.Vals) > maxState {
		t.Fatal("Able to add more than maxState items into State.Vals")
	}
	if len(State.Vals) < maxState-10 {
		t.Fatal("Too few items in State (e.g. got reset somewhere in the middle?)")
	}

	lastItem := State.Vals[len(State.Vals)-1:][0]
	if lastItem.Name != ds.Name {
		t.Fatal(fmt.Sprintf("The expected last item (after adding more then maxState items) was [%v] but actually found [%v]!", ds.Name, lastItem.Name))
	}
}

func TestParsing(t *testing.T) {

	type testpair struct {
		incr int
		line string
	}

	// integer indicates with how much the count of internal state should go up
	// (could be 0, eg. not valid test input, or ds already captured)
	// Also, each line should have a non-nil Create_date
	var testCases = []testpair{
		{1, "launchctl-carbon.stdout:24/08/2014 17:59:53 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Recovery_HD/df_complex-free.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{0, "astt"},
		{0, "launchctl-carbon.stdout:24/08/2014 17:59:53 :: [creates] creating database file / (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "13/09/2014 23:10:56 :: [creates] creating database file /opt/graphite/storage/whisper/local/random/diceroll.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 17:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Recovery_HD/df_complex-reserved.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 17:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Recovery_HD/df_complex-used.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 20:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Media/df_complex-free.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 20:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Media/df_complex-reserved.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 20:59:54 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/df-Volumes-Media/df_complex-used.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 23:10:40 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/curl_xml-default/gauge-tvseries_watched-Babylon_5.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{1, "launchctl-carbon.stdout:24/08/2014 23:10:40 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/curl_xml-default/gauge-tvseries_total-Babylon_5.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
		{0, "launchctl-carbon.stdout:24/08/2014 23:10:40 :: [creates] creating database file /opt/graphite/storage/whisper/mac-mini_local/collectd/curl_xml-default/.wsp (archive=[(60, 525600), (600, 518400)] xff=None agg=None)"},
	}
	State.Vals = nil // start fresh
	prev_count := len(State.Vals)

	for _, test := range testCases {
		parseLine(test.line)

		if len(State.Vals) != prev_count+test.incr {
			t.Fatal(fmt.Sprintf("Parsed line, should have seen %v new entries, saw %v. Line: %v", test.incr, len(State.Vals)-prev_count, test))
		}
		prev_count = len(State.Vals)

		// Check date parseing
		last_ds := State.Vals[len(State.Vals)-1:][0]
		// Do any checking on the actual values for the data source (not complete yet)
		if last_ds.Create_date.IsZero() {
			t.Fatal(fmt.Sprintf("Data source has invalid Create_date: %+v", last_ds))
		}
		if len(last_ds.Name) < 1 {
			t.Fatal(fmt.Sprintf("Data source doesnt have proper Name: %+v", last_ds))
		}
	}
}
<|endoftext|>


<commit_before>package main

import "testing"

func TestPing(t *testing.T) {

	if err := isPingable("localhost"); err != nil {
		t.Error("\"localhost\" should be pingable: " + err.Error())
	}

	if err := isPingable("tsohlacol"); err == nil {
		t.Error("It would be very surprising if \"tsohlacol\" was pingable")
	}
}
<commit_msg>Fix ping unit test<commit_after>package main

import "testing"

func TestPing(t *testing.T) {

	if err := ping("localhost"); err != nil {
		t.Error("\"localhost\" should be pingable: " + err.Error())
	}

	if err := ping("tsohlacol"); err == nil {
		t.Error("It would be very surprising if \"tsohlacol\" was pingable")
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package gen

import (
	"bytes"
	"fmt"
	"go/token"
	"path/filepath"
	"strings"

	"github.com/thriftrw/thriftrw-go/compile"
)

// TODO: This should be moved into a separate program or template

// YARPC generates YARPC-specific code for a service.
//
// Each service gets a ${serviceName}server and ${serviceName}client package.
func YARPC(i thriftPackageImporter, s *compile.ServiceSpec) (map[string]*bytes.Buffer, error) {
	files := make(map[string]*bytes.Buffer)

	thriftPackage, err := i.Package(s.ThriftFile())
	if err != nil {
		return nil, err
	}

	serverPkgName := strings.ToLower(s.Name) + "server"
	serverImportPath := filepath.Join(thriftPackage, "yarpc", serverPkgName)
	serverFile, err := yarpcGenerator{
		NewGenerator(i, serverImportPath, serverPkgName), i,
	}.server(s)
	if err != nil {
		return nil, err
	}
	files[filepath.Join(serverPkgName, "server.go")] = serverFile

	clientPkgName := strings.ToLower(s.Name) + "client"
	clientImportPath := filepath.Join(thriftPackage, "yarpc", clientPkgName)
	clientFile, err := yarpcGenerator{
		NewGenerator(i, clientImportPath, clientPkgName), i,
	}.client(s)
	if err != nil {
		return nil, err
	}
	files[filepath.Join(clientPkgName, "client.go")] = clientFile

	return files, nil
}

type yarpcGenerator struct {
	g Generator
	i thriftPackageImporter
}

func (yg yarpcGenerator) server(s *compile.ServiceSpec) (*bytes.Buffer, error) {
	if err := yg.iface(s, true); err != nil {
		return nil, err
	}

	err := yg.g.DeclareFromTemplate(
		`
		<$yarpc := import "github.com/yarpc/yarpc-go">
		<$thrift := import "github.com/yarpc/yarpc-go/encoding/thrift">
		<$protocol := import "github.com/thriftrw/thriftrw-go/protocol">
		<$wire := import "github.com/thriftrw/thriftrw-go/wire">

		func New(impl Interface) <$thrift>.Service {
			return service{handler{impl}}
		}

		type service struct{h handler}

		func (service) Name() string {
			 return "<.Name>"
		 }

		func (service) Protocol() <$protocol>.Protocol {
			return <$protocol>.Binary
		}

		func (s service) Handlers() map[string]<$thrift>.Handler {
			return map[string]<$thrift>.Handler{
				<range .Functions>
					"<.Name>": <$thrift>.HandlerFunc(s.h.<goCase .Name>),
				<end>
			}
		}

		type handler struct{impl Interface}

		<$service := .>
		<range .Functions>
			<$servicePackage := servicePackage $service>
			<$Args := printf "%s.%sArgs" $servicePackage (goCase .Name)>
			<$Helper := printf "%s.%sHelper" $servicePackage (goCase .Name)>

			<$vars := newNamespace>
			<$reqMeta := $vars.NewName "reqMeta">
			<$body := $vars.NewName "body">

			func (h handler) <goCase .Name>(
				<$reqMeta> <$yarpc>.ReqMeta,
				<$body> <$wire>.Value,
			) (<$thrift>.Response, error) {

				<$args := $vars.NewName "args">
				var <$args> <$Args>
				if err := <$args>.FromWire(<$body>); err != nil {
					return <$thrift>.Response{}, err
				}

				<$resMeta := $vars.NewName "resMeta">
				<$succ := $vars.NewName "success">
				<if .ResultSpec.ReturnType>
					<$succ>,
				<end>
				<$resMeta>, err := h.impl.<goCase .Name>(
					<$reqMeta>,
					<range .ArgsSpec><$args>.<goCase .Name>,<end>
				)

				<$result := $vars.NewName "result">
				<$hadError := $vars.NewName "hadError">

				<$hadError> := err != nil
				<$result>, err := <$Helper>.WrapResponse(
					<if .ResultSpec.ReturnType>
						<$succ>,
					<end>
					err)

				<$response := $vars.NewName "response">
				var <$response> <$thrift>.Response
				if err == nil {
					<$response>.IsApplicationError = <$hadError>
					<$response>.Meta = <$resMeta>
					<$response>.Body, err = <$result>.ToWire()
				}
				return <$response>, err
			}
		<end>
		`,
		s)

	if err != nil {
		return nil, err
	}

	buff := new(bytes.Buffer)
	if err := yg.g.Write(buff, token.NewFileSet()); err != nil {
		return nil, fmt.Errorf(
			"failed to write YARPC server for service %q: %v", s.Name, err)
	}

	return buff, nil
}

func (yg yarpcGenerator) client(s *compile.ServiceSpec) (*bytes.Buffer, error) {
	if err := yg.iface(s, false); err != nil {
		return nil, err
	}

	err := yg.g.DeclareFromTemplate(
		`
		<$yarpc := import "github.com/yarpc/yarpc-go">
		<$transport := import "github.com/yarpc/yarpc-go/transport">
		<$thrift := import "github.com/yarpc/yarpc-go/encoding/thrift">
		<$protocol := import "github.com/thriftrw/thriftrw-go/protocol">

		func New(c <$transport>.Channel) Interface {
			return client{
				c: <$thrift>.New(<$thrift>.Config{
					Service: "<.Name>",
					Channel: c,
					Protocol: <$protocol>.Binary,
				}),
			}
		}

		type client struct{c <$thrift>.Client}

		<$service := .>
		<range .Functions>
			<$wire := import "github.com/thriftrw/thriftrw-go/wire">
			<$servicePackage := servicePackage $service>

			<$Result := printf "%s.%sResult" $servicePackage (goCase .Name)>
			<$Helper := printf "%s.%sHelper" $servicePackage (goCase .Name)>

			<$vars := newNamespace>
			func (c client) <goCase .Name>(
				<$vars.NewName "reqMeta"> <$yarpc>.CallReqMeta,
				<range .ArgsSpec>
					<if .Required>
						<$vars.NewName .Name> <typeReference .Type>,
					<else>
						<$vars.NewName .Name> <typeReferencePtr .Type>,
					<end>
				<end>
			) (
				<if .ResultSpec.ReturnType>
					<$vars.NewName "success"> <typeReference .ResultSpec.ReturnType>,
				<end>
				<$vars.NewName "resMeta"> <$yarpc>.CallResMeta,
				err error,
			 ) {
				<$reqMeta := $vars.Rotate "reqMeta">
				<$args := $vars.NewName "args">
				<$args> := <$servicePackage>.<goCase .Name>Helper.Args(
					<range .ArgsSpec>
						<$vars.Rotate .Name>,
					<end>
				)

				<$resMeta := $vars.Rotate "resMeta">
				<$body := $vars.NewName "body">

				<$w := $vars.NewName "w">
				var <$w> <$wire>.Value
				<$w>, err = <$args>.ToWire()
				if err != nil {
					return
				}

				var <$body> <$wire>.Value
				<$body>, <$resMeta>, err = c.c.Call("<.Name>", <$reqMeta>, <$w>)
				if err != nil {
					return
				}

				<$result := $vars.NewName "result">
				var <$result> <$Result>
				if err = <$result>.FromWire(<$body>); err != nil {
					return
				}

				<if .ResultSpec.ReturnType>
					<$succ := $vars.Rotate "success">
					<$succ>, err = <$Helper>.UnwrapResponse(&<$result>)
				<else>
					err = <$Helper>.UnwrapResponse(&<$result>)
				<end>
				return
			}
		<end>
		`, s)

	if err != nil {
		return nil, err
	}

	buff := new(bytes.Buffer)
	if err := yg.g.Write(buff, token.NewFileSet()); err != nil {
		return nil, fmt.Errorf(
			"failed to write YARPC server for service %q: %v", s.Name, err)
	}

	return buff, nil
}

// iface generates the service interface for the service and the client.
func (yg yarpcGenerator) iface(s *compile.ServiceSpec, isServer bool) error {
	return yg.g.DeclareFromTemplate(
		`
		<$yarpc := import "github.com/yarpc/yarpc-go">
		<$thrift := import "github.com/yarpc/yarpc-go/encoding/thrift">

		type Interface interface {
			<if .Parent>
				<if isServer>
					<import (serverPackage .Parent)>.Interface
				<else>
					<import (clientPackage .Parent)>.Interface
				<end>
			<end>

			<range .Functions>
				<$params := newNamespace>
				<goCase .Name>(
					<if isServer>
						<$params.NewName "reqMeta"> <$yarpc>.ReqMeta,
					<else>
						<$params.NewName "reqMeta"> <$yarpc>.CallReqMeta,
					<end>
					<range .ArgsSpec>
						<if .Required>
							<$params.NewName .Name> <typeReference .Type>,
						<else>
							<$params.NewName .Name> <typeReferencePtr .Type>,
						<end>
					<end>
				) (
					<if .ResultSpec.ReturnType>
						<typeReference .ResultSpec.ReturnType>,
					<end>
					<if isServer>
						<$yarpc>.ResMeta,
					<else>
						<$yarpc>.CallResMeta,
					<end>
					 error,
				 )
			<end>
		}
		`,
		s,
		TemplateFunc("isServer", func() bool { return isServer }),
		TemplateFunc("clientPackage", func(service *compile.ServiceSpec) (string, error) {
			return yg.clientPackage(service)
		}),
		TemplateFunc("serverPackage", func(service *compile.ServiceSpec) (string, error) {
			return yg.serverPackage(service)
		}),
	)
}

func (yg yarpcGenerator) basePackage(s *compile.ServiceSpec) (string, error) {
	pkg, err := yg.i.Package(s.ThriftFile())
	if err != nil {
		return "", err
	}
	return filepath.Join(pkg, "yarpc"), nil
}

func (yg yarpcGenerator) serverPackage(s *compile.ServiceSpec) (string, error) {
	pkg, err := yg.basePackage(s)
	if err != nil {
		return "", err
	}
	return filepath.Join(pkg, strings.ToLower(s.Name)+"server"), nil
}

func (yg yarpcGenerator) clientPackage(s *compile.ServiceSpec) (string, error) {
	pkg, err := yg.basePackage(s)
	if err != nil {
		return "", err
	}
	return filepath.Join(pkg, strings.ToLower(s.Name)+"client"), nil
}
<commit_msg>yarpc: Use Enveloper (#160)<commit_after>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package gen

import (
	"bytes"
	"fmt"
	"go/token"
	"path/filepath"
	"strings"

	"github.com/thriftrw/thriftrw-go/compile"
)

// TODO: This should be moved into a separate program or template

// YARPC generates YARPC-specific code for a service.
//
// Each service gets a ${serviceName}server and ${serviceName}client package.
func YARPC(i thriftPackageImporter, s *compile.ServiceSpec) (map[string]*bytes.Buffer, error) {
	files := make(map[string]*bytes.Buffer)

	thriftPackage, err := i.Package(s.ThriftFile())
	if err != nil {
		return nil, err
	}

	serverPkgName := strings.ToLower(s.Name) + "server"
	serverImportPath := filepath.Join(thriftPackage, "yarpc", serverPkgName)
	serverFile, err := yarpcGenerator{
		NewGenerator(i, serverImportPath, serverPkgName), i,
	}.server(s)
	if err != nil {
		return nil, err
	}
	files[filepath.Join(serverPkgName, "server.go")] = serverFile

	clientPkgName := strings.ToLower(s.Name) + "client"
	clientImportPath := filepath.Join(thriftPackage, "yarpc", clientPkgName)
	clientFile, err := yarpcGenerator{
		NewGenerator(i, clientImportPath, clientPkgName), i,
	}.client(s)
	if err != nil {
		return nil, err
	}
	files[filepath.Join(clientPkgName, "client.go")] = clientFile

	return files, nil
}

type yarpcGenerator struct {
	g Generator
	i thriftPackageImporter
}

func (yg yarpcGenerator) server(s *compile.ServiceSpec) (*bytes.Buffer, error) {
	if err := yg.iface(s, true); err != nil {
		return nil, err
	}

	err := yg.g.DeclareFromTemplate(
		`
		<$yarpc := import "github.com/yarpc/yarpc-go">
		<$thrift := import "github.com/yarpc/yarpc-go/encoding/thrift">
		<$protocol := import "github.com/thriftrw/thriftrw-go/protocol">
		<$wire := import "github.com/thriftrw/thriftrw-go/wire">

		func New(impl Interface) <$thrift>.Service {
			return service{handler{impl}}
		}

		type service struct{h handler}

		func (service) Name() string {
			 return "<.Name>"
		 }

		func (service) Protocol() <$protocol>.Protocol {
			return <$protocol>.Binary
		}

		func (s service) Handlers() map[string]<$thrift>.Handler {
			return map[string]<$thrift>.Handler{
				<range .Functions>
					"<.Name>": <$thrift>.HandlerFunc(s.h.<goCase .Name>),
				<end>
			}
		}

		type handler struct{impl Interface}

		<$service := .>
		<range .Functions>
			<$servicePackage := servicePackage $service>
			<$Args := printf "%s.%sArgs" $servicePackage (goCase .Name)>
			<$Helper := printf "%s.%sHelper" $servicePackage (goCase .Name)>

			<$vars := newNamespace>
			<$reqMeta := $vars.NewName "reqMeta">
			<$body := $vars.NewName "body">

			func (h handler) <goCase .Name>(
				<$reqMeta> <$yarpc>.ReqMeta,
				<$body> <$wire>.Value,
			) (<$thrift>.Response, error) {

				<$args := $vars.NewName "args">
				var <$args> <$Args>
				if err := <$args>.FromWire(<$body>); err != nil {
					return <$thrift>.Response{}, err
				}

				<$resMeta := $vars.NewName "resMeta">
				<$succ := $vars.NewName "success">
				<if .ResultSpec.ReturnType>
					<$succ>,
				<end>
				<$resMeta>, err := h.impl.<goCase .Name>(
					<$reqMeta>,
					<range .ArgsSpec><$args>.<goCase .Name>,<end>
				)

				<$result := $vars.NewName "result">
				<$hadError := $vars.NewName "hadError">

				<$hadError> := err != nil
				<$result>, err := <$Helper>.WrapResponse(
					<if .ResultSpec.ReturnType>
						<$succ>,
					<end>
					err)

				<$response := $vars.NewName "response">
				var <$response> <$thrift>.Response
				if err == nil {
					<$response>.IsApplicationError = <$hadError>
					<$response>.Meta = <$resMeta>
					<$response>.Body = <$result>
				}
				return <$response>, err
			}
		<end>
		`,
		s)

	if err != nil {
		return nil, err
	}

	buff := new(bytes.Buffer)
	if err := yg.g.Write(buff, token.NewFileSet()); err != nil {
		return nil, fmt.Errorf(
			"failed to write YARPC server for service %q: %v", s.Name, err)
	}

	return buff, nil
}

func (yg yarpcGenerator) client(s *compile.ServiceSpec) (*bytes.Buffer, error) {
	if err := yg.iface(s, false); err != nil {
		return nil, err
	}

	err := yg.g.DeclareFromTemplate(
		`
		<$yarpc := import "github.com/yarpc/yarpc-go">
		<$transport := import "github.com/yarpc/yarpc-go/transport">
		<$thrift := import "github.com/yarpc/yarpc-go/encoding/thrift">
		<$protocol := import "github.com/thriftrw/thriftrw-go/protocol">

		func New(c <$transport>.Channel) Interface {
			return client{
				c: <$thrift>.New(<$thrift>.Config{
					Service: "<.Name>",
					Channel: c,
					Protocol: <$protocol>.Binary,
				}),
			}
		}

		type client struct{c <$thrift>.Client}

		<$service := .>
		<range .Functions>
			<$wire := import "github.com/thriftrw/thriftrw-go/wire">
			<$servicePackage := servicePackage $service>

			<$Result := printf "%s.%sResult" $servicePackage (goCase .Name)>
			<$Helper := printf "%s.%sHelper" $servicePackage (goCase .Name)>

			<$vars := newNamespace>
			func (c client) <goCase .Name>(
				<$vars.NewName "reqMeta"> <$yarpc>.CallReqMeta,
				<range .ArgsSpec>
					<if .Required>
						<$vars.NewName .Name> <typeReference .Type>,
					<else>
						<$vars.NewName .Name> <typeReferencePtr .Type>,
					<end>
				<end>
			) (
				<if .ResultSpec.ReturnType>
					<$vars.NewName "success"> <typeReference .ResultSpec.ReturnType>,
				<end>
				<$vars.NewName "resMeta"> <$yarpc>.CallResMeta,
				err error,
			 ) {
				<$reqMeta := $vars.Rotate "reqMeta">
				<$args := $vars.NewName "args">
				<$args> := <$servicePackage>.<goCase .Name>Helper.Args(
					<range .ArgsSpec>
						<$vars.Rotate .Name>,
					<end>
				)

				<$resMeta := $vars.Rotate "resMeta">
				<$body := $vars.NewName "body">

				var <$body> <$wire>.Value
				<$body>, <$resMeta>, err = c.c.Call(<$reqMeta>, <$args>)
				if err != nil {
					return
				}

				<$result := $vars.NewName "result">
				var <$result> <$Result>
				if err = <$result>.FromWire(<$body>); err != nil {
					return
				}

				<if .ResultSpec.ReturnType>
					<$succ := $vars.Rotate "success">
					<$succ>, err = <$Helper>.UnwrapResponse(&<$result>)
				<else>
					err = <$Helper>.UnwrapResponse(&<$result>)
				<end>
				return
			}
		<end>
		`, s)

	if err != nil {
		return nil, err
	}

	buff := new(bytes.Buffer)
	if err := yg.g.Write(buff, token.NewFileSet()); err != nil {
		return nil, fmt.Errorf(
			"failed to write YARPC server for service %q: %v", s.Name, err)
	}

	return buff, nil
}

// iface generates the service interface for the service and the client.
func (yg yarpcGenerator) iface(s *compile.ServiceSpec, isServer bool) error {
	return yg.g.DeclareFromTemplate(
		`
		<$yarpc := import "github.com/yarpc/yarpc-go">
		<$thrift := import "github.com/yarpc/yarpc-go/encoding/thrift">

		type Interface interface {
			<if .Parent>
				<if isServer>
					<import (serverPackage .Parent)>.Interface
				<else>
					<import (clientPackage .Parent)>.Interface
				<end>
			<end>

			<range .Functions>
				<$params := newNamespace>
				<goCase .Name>(
					<if isServer>
						<$params.NewName "reqMeta"> <$yarpc>.ReqMeta,
					<else>
						<$params.NewName "reqMeta"> <$yarpc>.CallReqMeta,
					<end>
					<range .ArgsSpec>
						<if .Required>
							<$params.NewName .Name> <typeReference .Type>,
						<else>
							<$params.NewName .Name> <typeReferencePtr .Type>,
						<end>
					<end>
				) (
					<if .ResultSpec.ReturnType>
						<typeReference .ResultSpec.ReturnType>,
					<end>
					<if isServer>
						<$yarpc>.ResMeta,
					<else>
						<$yarpc>.CallResMeta,
					<end>
					 error,
				 )
			<end>
		}
		`,
		s,
		TemplateFunc("isServer", func() bool { return isServer }),
		TemplateFunc("clientPackage", func(service *compile.ServiceSpec) (string, error) {
			return yg.clientPackage(service)
		}),
		TemplateFunc("serverPackage", func(service *compile.ServiceSpec) (string, error) {
			return yg.serverPackage(service)
		}),
	)
}

func (yg yarpcGenerator) basePackage(s *compile.ServiceSpec) (string, error) {
	pkg, err := yg.i.Package(s.ThriftFile())
	if err != nil {
		return "", err
	}
	return filepath.Join(pkg, "yarpc"), nil
}

func (yg yarpcGenerator) serverPackage(s *compile.ServiceSpec) (string, error) {
	pkg, err := yg.basePackage(s)
	if err != nil {
		return "", err
	}
	return filepath.Join(pkg, strings.ToLower(s.Name)+"server"), nil
}

func (yg yarpcGenerator) clientPackage(s *compile.ServiceSpec) (string, error) {
	pkg, err := yg.basePackage(s)
	if err != nil {
		return "", err
	}
	return filepath.Join(pkg, strings.ToLower(s.Name)+"client"), nil
}
<|endoftext|>


<commit_before>package main

import (
	"time"
)

type jargon struct {
	ID     int
	name   string
	quote  string
	source string
	date   time.Time
}

var jargonCollection []jargon

func main() {
}
<commit_msg>use db<commit_after>package main

import (
	"database/sql"
	"log"
	"time"
)

type jargon struct {
	ID     int
	name   string
	quote  string
	source string
	date   time.Time
}

var jargonCollection []jargon

func main() {
	db, err := sql.Open("sqlite3", "./jargon.db")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	sql := `
	CREATE TABLE jargon (id integer NOT NULL PRIMARY KEY,
						 name VARCHAR(11),
						 quote TEXT,
						 source VARCHAR(11),
						 date TIMESTAMP)
	`
	_, err = db.Exec(sql)
	if err != nil {
		log.Printf("%q: %s\n", err, sql)
		return
	}
}
<|endoftext|>


<commit_before>package sdl

// #include "sdl_wrapper.h"
import "C"
import (
	"reflect"
	"unsafe"
)

const (
	AUDIO_MASK_BITSIZE  = C.SDL_AUDIO_MASK_BITSIZE
	AUDIO_MASK_DATATYPE = C.SDL_AUDIO_MASK_DATATYPE
	AUDIO_MASK_ENDIAN   = C.SDL_AUDIO_MASK_ENDIAN
	AUDIO_MASK_SIGNED   = C.SDL_AUDIO_MASK_SIGNED
)

const (
	AUDIO_U8     = C.AUDIO_U8
	AUDIO_S8     = C.AUDIO_S8
	AUDIO_U16LSB = C.AUDIO_U16LSB
	AUDIO_S16LSB = C.AUDIO_S16LSB
	AUDIO_U16MSB = C.AUDIO_U16MSB
	AUDIO_S16MSB = C.AUDIO_S16MSB
	AUDIO_U16    = C.AUDIO_U16
	AUDIO_S16    = C.AUDIO_S16
	AUDIO_S32LSB = C.AUDIO_S32LSB
	AUDIO_S32MSB = C.AUDIO_S32MSB
	AUDIO_S32    = C.AUDIO_S32
	AUDIO_F32LSB = C.AUDIO_F32LSB
	AUDIO_F32MSB = C.AUDIO_F32MSB
	AUDIO_F32    = C.AUDIO_F32
	AUDIO_U16SYS = C.AUDIO_U16SYS
	AUDIO_S16SYS = C.AUDIO_S16SYS
	AUDIO_S32SYS = C.AUDIO_S32SYS
	AUDIO_F32SYS = C.AUDIO_F32SYS
)

const (
	AUDIO_ALLOW_FREQUENCY_CHANGE = C.SDL_AUDIO_ALLOW_FREQUENCY_CHANGE
	AUDIO_ALLOW_FORMAT_CHANGE    = C.SDL_AUDIO_ALLOW_FORMAT_CHANGE
	AUDIO_ALLOW_CHANNELS_CHANGE  = C.SDL_AUDIO_ALLOW_CHANNELS_CHANGE
	AUDIO_ALLOW_ANY_CHANGE       = C.SDL_AUDIO_ALLOW_ANY_CHANGE
)

const (
	AUDIO_STOPPED AudioStatus = C.SDL_AUDIO_STOPPED
	AUDIO_PLAYING             = C.SDL_AUDIO_PLAYING
	AUDIO_PAUSED              = C.SDL_AUDIO_PAUSED
)

const MIX_MAXVOLUME = C.SDL_MIX_MAXVOLUME

// AudioFormat (https://wiki.libsdl.org/SDL_AudioFormat)
type AudioFormat uint16
type AudioCallback C.SDL_AudioCallback
type AudioFilter C.SDL_AudioFilter
type AudioDeviceID uint32

// AudioStatus (https://wiki.libsdl.org/SDL_AudioStatus)
type AudioStatus uint32
type cAudioStatus C.SDL_AudioStatus

// AudioSpec (https://wiki.libsdl.org/SDL_AudioSpec)
type AudioSpec struct {
	Freq     int32
	Format   AudioFormat
	Channels uint8
	Silence  uint8
	Samples  uint16
	Padding  uint16
	Size     uint32
	Callback AudioCallback
	UserData unsafe.Pointer
}
type cAudioSpec C.SDL_AudioSpec

// AudioCVT (https://wiki.libsdl.org/SDL_AudioCVT)
type AudioCVT struct {
	Needed      int32
	SrcFormat   AudioFormat
	DstFormat   AudioFormat
	RateIncr    float64
	Buf         unsafe.Pointer // use AudioCVT.BufAsSlice() for access via Go slice
	Len         int32
	LenCVT      int32
	LenMult     int32
	LenRatio    float64
	filters     [10]AudioFilter // internal
	filterIndex int32           // internal
}
type cAudioCVT C.SDL_AudioCVT

func (fmt AudioFormat) c() C.SDL_AudioFormat {
	return C.SDL_AudioFormat(fmt)
}

func (id AudioDeviceID) c() C.SDL_AudioDeviceID {
	return C.SDL_AudioDeviceID(id)
}

func (as *AudioSpec) cptr() *C.SDL_AudioSpec {
	return (*C.SDL_AudioSpec)(unsafe.Pointer(as))
}

func (cvt *AudioCVT) cptr() *C.SDL_AudioCVT {
	return (*C.SDL_AudioCVT)(unsafe.Pointer(cvt))
}

func (format AudioFormat) BitSize() uint8 {
	return uint8(format & AUDIO_MASK_BITSIZE)
}

func (format AudioFormat) IsFloat() bool {
	return (format & AUDIO_MASK_DATATYPE) > 0
}

func (format AudioFormat) IsBigEndian() bool {
	return (format & AUDIO_MASK_ENDIAN) > 0
}

func (format AudioFormat) IsSigned() bool {
	return (format & AUDIO_MASK_SIGNED) > 0
}

func (format AudioFormat) IsInt() bool {
	return !format.IsFloat()
}

func (format AudioFormat) IsLittleEndian() bool {
	return !format.IsBigEndian()
}

func (format AudioFormat) IsUnsigned() bool {
	return !format.IsSigned()
}

func (cvt *AudioCVT) AllocBuf(size uintptr) {
	cvt.Buf = C.malloc(C.size_t(size))
}

func (cvt *AudioCVT) FreeBuf() {
	C.free(cvt.Buf)
}

// Access AudioCVT.buf as slice.
// NOTE: Must have used ConvertAudio() before usage because it uses LenCVT as slice length.
func (cvt AudioCVT) BufAsSlice() []byte {
	var b []byte
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sliceHeader.Len = int(cvt.LenCVT)
	sliceHeader.Cap = int(cvt.Len * cvt.LenMult)
	sliceHeader.Data = uintptr(unsafe.Pointer(cvt.Buf))
	return b
}

// GetNumAudioDrivers (https://wiki.libsdl.org/SDL_GetNumAudioDrivers)
func GetNumAudioDrivers() int {
	return int(C.SDL_GetNumAudioDrivers())
}

// GetAudioDriver (https://wiki.libsdl.org/SDL_GetAudioDriver)
func GetAudioDriver(index int) string {
	return string(C.GoString(C.SDL_GetAudioDriver(C.int(index))))
}

// AudioInit (https://wiki.libsdl.org/SDL_AudioInit)
func AudioInit(driverName string) error {
	_driverName := C.CString(driverName)
	defer C.free(unsafe.Pointer(_driverName))
	if C.SDL_AudioInit(_driverName) != 0 {
		return GetError()
	}
	return nil
}

// AudioQuit (https://wiki.libsdl.org/SDL_AudioQuit)
func AudioQuit() {
	C.SDL_AudioQuit()
}

// GetCurrentAudioDriver (https://wiki.libsdl.org/SDL_GetCurrentAudioDriver)
func GetCurrentAudioDriver() string {
	return string(C.GoString(C.SDL_GetCurrentAudioDriver()))
}

// OpenAudio (https://wiki.libsdl.org/SDL_OpenAudio)
func OpenAudio(desired, obtained *AudioSpec) error {
	if C.SDL_OpenAudio(desired.cptr(), obtained.cptr()) != 0 {
		return GetError()
	}
	return nil
}

// GetNumAudioDevices (https://wiki.libsdl.org/SDL_GetNumAudioDevices)
func GetNumAudioDevices(isCapture bool) int {
	return int(C.SDL_GetNumAudioDevices(C.int(Btoi(isCapture))))
}

// GetAudioDeviceName (https://wiki.libsdl.org/SDL_GetAudioDeviceName)
func GetAudioDeviceName(index int, isCapture bool) string {
	return string(C.GoString(C.SDL_GetAudioDeviceName(C.int(index), C.int(Btoi(isCapture)))))
}

// OpenAudioDevice (https://wiki.libsdl.org/SDL_OpenAudioDevice)
func OpenAudioDevice(device string, isCapture bool, desired, obtained *AudioSpec, allowedChanges int) (AudioDeviceID, error) {
	_device := C.CString(device)
	if device == "" {
		_device = nil
	}
	defer C.free(unsafe.Pointer(_device))
	if id := AudioDeviceID(C.SDL_OpenAudioDevice(_device, C.int(Btoi(isCapture)), desired.cptr(), obtained.cptr(), C.int(allowedChanges))); id > 0 {
		return id, nil
	}
	return 0, GetError()
}

// GetAudioStatus (https://wiki.libsdl.org/SDL_GetAudioStatus)
func GetAudioStatus() AudioStatus {
	return (AudioStatus)(C.SDL_GetAudioStatus())
}

// GetAudioDeviceStatus (https://wiki.libsdl.org/SDL_GetAudioDeviceStatus)
func GetAudioDeviceStatus(dev AudioDeviceID) AudioStatus {
	return (AudioStatus)(C.SDL_GetAudioDeviceStatus(dev.c()))
}

// PauseAudio (https://wiki.libsdl.org/SDL_PauseAudio)
func PauseAudio(pauseOn bool) {
	C.SDL_PauseAudio(C.int(Btoi(pauseOn)))
}

// PauseAudioDevice (https://wiki.libsdl.org/SDL_PauseAudioDevice)
func PauseAudioDevice(dev AudioDeviceID, pauseOn bool) {
	C.SDL_PauseAudioDevice(dev.c(), C.int(Btoi(pauseOn)))
}

// LoadWAV_RW (https://wiki.libsdl.org/SDL_LoadWAV_RW)
func LoadWAV_RW(src *RWops, freeSrc bool, spec *AudioSpec) ([]byte, *AudioSpec) {
	var _audioBuf *C.Uint8
	var _audioLen C.Uint32
	audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(src.cptr(), C.int(Btoi(freeSrc)), spec.cptr(), &_audioBuf, &_audioLen)))

	var b []byte
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sliceHeader.Len = (int)(_audioLen)
	sliceHeader.Cap = (int)(_audioLen)
	sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf))
	return b, audioSpec
}

// LoadWAV (https://wiki.libsdl.org/SDL_LoadWAV)
func LoadWAV(file string, spec *AudioSpec) ([]byte, *AudioSpec) {
	_file := C.CString(file)
	_rb := C.CString("rb")
	defer C.free(unsafe.Pointer(_file))
	defer C.free(unsafe.Pointer(_rb))

	var _audioBuf *C.Uint8
	var _audioLen C.Uint32
	audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(C.SDL_RWFromFile(_file, _rb), 1, spec.cptr(), &_audioBuf, &_audioLen)))

	var b []byte
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sliceHeader.Len = (int)(_audioLen)
	sliceHeader.Cap = (int)(_audioLen)
	sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf))
	return b, audioSpec
}

// FreeWAV (https://wiki.libsdl.org/SDL_FreeWAV)
func FreeWAV(audioBuf []uint8) {
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&audioBuf))
	_audioBuf := (*C.Uint8)(unsafe.Pointer(sliceHeader.Data))
	C.SDL_FreeWAV(_audioBuf)
}

// BuildAudioCVT (https://wiki.libsdl.org/SDL_BuildAudioCVT)
func BuildAudioCVT(cvt *AudioCVT, srcFormat AudioFormat, srcChannels uint8, srcRate int, dstFormat AudioFormat, dstChannels uint8, dstRate int) (converted bool, err error) {
	switch int(C.SDL_BuildAudioCVT(cvt.cptr(), srcFormat.c(), C.Uint8(srcChannels), C.int(srcRate), dstFormat.c(), C.Uint8(dstChannels), C.int(dstRate))) {
	case 1:
		return true, nil
	case 0:
		return false, nil
	}
	return false, GetError()
}

// ConvertAudio (https://wiki.libsdl.org/SDL_ConvertAudio)
func ConvertAudio(cvt *AudioCVT) error {
	_cvt := (*C.SDL_AudioCVT)(unsafe.Pointer(cvt))
	if C.SDL_ConvertAudio(_cvt) != 0 {
		return GetError()
	}
	return nil
}

// MixAudio (https://wiki.libsdl.org/SDL_MixAudio)
func MixAudio(dst, src *uint8, len_ uint32, volume int) {
	_dst := (*C.Uint8)(unsafe.Pointer(dst))
	_src := (*C.Uint8)(unsafe.Pointer(src))
	C.SDL_MixAudio(_dst, _src, C.Uint32(len_), C.int(volume))
}

// MixAudioFormat (https://wiki.libsdl.org/SDL_MixAudioFormat)
func MixAudioFormat(dst, src *uint8, format AudioFormat, len_ uint32, volume int) {
	_dst := (*C.Uint8)(unsafe.Pointer(dst))
	_src := (*C.Uint8)(unsafe.Pointer(src))
	C.SDL_MixAudioFormat(_dst, _src, format.c(), C.Uint32(len_), C.int(volume))
}

// LockAudio (https://wiki.libsdl.org/SDL_LockAudio)
func LockAudio() {
	C.SDL_LockAudio()
}

// LockAudioDevice (https://wiki.libsdl.org/SDL_LockAudioDevice)
func LockAudioDevice(dev AudioDeviceID) {
	C.SDL_LockAudioDevice(dev.c())
}

// UnlockAudio (https://wiki.libsdl.org/SDL_UnlockAudio)
func UnlockAudio() {
	C.SDL_UnlockAudio()
}

// UnlockAudioDevice (https://wiki.libsdl.org/SDL_UnlockAudioDevice)
func UnlockAudioDevice(dev AudioDeviceID) {
	C.SDL_UnlockAudioDevice(dev.c())
}

// CloseAudio (https://wiki.libsdl.org/SDL_CloseAudio)
func CloseAudio() {
	C.SDL_CloseAudio()
}

// CloseAudioDevice (https://wiki.libsdl.org/SDL_CloseAudioDevice)
func CloseAudioDevice(dev AudioDeviceID) {
	C.SDL_CloseAudioDevice(dev.c())
}

/*
func AudioDeviceConnected(dev AudioDeviceID) int {
	_dev := (C.SDL_AudioDeviceID) (dev)
	return int (C.SDL_AudioDeviceConnected(_dev))
}
*/
<commit_msg>Implement SDL_QueueAudio binding (#215)<commit_after>package sdl

// #include "sdl_wrapper.h"
import "C"
import (
	"reflect"
	"unsafe"
)

const (
	AUDIO_MASK_BITSIZE  = C.SDL_AUDIO_MASK_BITSIZE
	AUDIO_MASK_DATATYPE = C.SDL_AUDIO_MASK_DATATYPE
	AUDIO_MASK_ENDIAN   = C.SDL_AUDIO_MASK_ENDIAN
	AUDIO_MASK_SIGNED   = C.SDL_AUDIO_MASK_SIGNED
)

const (
	AUDIO_U8     = C.AUDIO_U8
	AUDIO_S8     = C.AUDIO_S8
	AUDIO_U16LSB = C.AUDIO_U16LSB
	AUDIO_S16LSB = C.AUDIO_S16LSB
	AUDIO_U16MSB = C.AUDIO_U16MSB
	AUDIO_S16MSB = C.AUDIO_S16MSB
	AUDIO_U16    = C.AUDIO_U16
	AUDIO_S16    = C.AUDIO_S16
	AUDIO_S32LSB = C.AUDIO_S32LSB
	AUDIO_S32MSB = C.AUDIO_S32MSB
	AUDIO_S32    = C.AUDIO_S32
	AUDIO_F32LSB = C.AUDIO_F32LSB
	AUDIO_F32MSB = C.AUDIO_F32MSB
	AUDIO_F32    = C.AUDIO_F32
	AUDIO_U16SYS = C.AUDIO_U16SYS
	AUDIO_S16SYS = C.AUDIO_S16SYS
	AUDIO_S32SYS = C.AUDIO_S32SYS
	AUDIO_F32SYS = C.AUDIO_F32SYS
)

const (
	AUDIO_ALLOW_FREQUENCY_CHANGE = C.SDL_AUDIO_ALLOW_FREQUENCY_CHANGE
	AUDIO_ALLOW_FORMAT_CHANGE    = C.SDL_AUDIO_ALLOW_FORMAT_CHANGE
	AUDIO_ALLOW_CHANNELS_CHANGE  = C.SDL_AUDIO_ALLOW_CHANNELS_CHANGE
	AUDIO_ALLOW_ANY_CHANGE       = C.SDL_AUDIO_ALLOW_ANY_CHANGE
)

const (
	AUDIO_STOPPED AudioStatus = C.SDL_AUDIO_STOPPED
	AUDIO_PLAYING             = C.SDL_AUDIO_PLAYING
	AUDIO_PAUSED              = C.SDL_AUDIO_PAUSED
)

const MIX_MAXVOLUME = C.SDL_MIX_MAXVOLUME

// AudioFormat (https://wiki.libsdl.org/SDL_AudioFormat)
type AudioFormat uint16
type AudioCallback C.SDL_AudioCallback
type AudioFilter C.SDL_AudioFilter
type AudioDeviceID uint32

// AudioStatus (https://wiki.libsdl.org/SDL_AudioStatus)
type AudioStatus uint32
type cAudioStatus C.SDL_AudioStatus

// AudioSpec (https://wiki.libsdl.org/SDL_AudioSpec)
type AudioSpec struct {
	Freq     int32
	Format   AudioFormat
	Channels uint8
	Silence  uint8
	Samples  uint16
	Padding  uint16
	Size     uint32
	Callback AudioCallback
	UserData unsafe.Pointer
}
type cAudioSpec C.SDL_AudioSpec

// AudioCVT (https://wiki.libsdl.org/SDL_AudioCVT)
type AudioCVT struct {
	Needed      int32
	SrcFormat   AudioFormat
	DstFormat   AudioFormat
	RateIncr    float64
	Buf         unsafe.Pointer // use AudioCVT.BufAsSlice() for access via Go slice
	Len         int32
	LenCVT      int32
	LenMult     int32
	LenRatio    float64
	filters     [10]AudioFilter // internal
	filterIndex int32           // internal
}
type cAudioCVT C.SDL_AudioCVT

func (fmt AudioFormat) c() C.SDL_AudioFormat {
	return C.SDL_AudioFormat(fmt)
}

func (id AudioDeviceID) c() C.SDL_AudioDeviceID {
	return C.SDL_AudioDeviceID(id)
}

func (as *AudioSpec) cptr() *C.SDL_AudioSpec {
	return (*C.SDL_AudioSpec)(unsafe.Pointer(as))
}

func (cvt *AudioCVT) cptr() *C.SDL_AudioCVT {
	return (*C.SDL_AudioCVT)(unsafe.Pointer(cvt))
}

func (format AudioFormat) BitSize() uint8 {
	return uint8(format & AUDIO_MASK_BITSIZE)
}

func (format AudioFormat) IsFloat() bool {
	return (format & AUDIO_MASK_DATATYPE) > 0
}

func (format AudioFormat) IsBigEndian() bool {
	return (format & AUDIO_MASK_ENDIAN) > 0
}

func (format AudioFormat) IsSigned() bool {
	return (format & AUDIO_MASK_SIGNED) > 0
}

func (format AudioFormat) IsInt() bool {
	return !format.IsFloat()
}

func (format AudioFormat) IsLittleEndian() bool {
	return !format.IsBigEndian()
}

func (format AudioFormat) IsUnsigned() bool {
	return !format.IsSigned()
}

func (cvt *AudioCVT) AllocBuf(size uintptr) {
	cvt.Buf = C.malloc(C.size_t(size))
}

func (cvt *AudioCVT) FreeBuf() {
	C.free(cvt.Buf)
}

// Access AudioCVT.buf as slice.
// NOTE: Must have used ConvertAudio() before usage because it uses LenCVT as slice length.
func (cvt AudioCVT) BufAsSlice() []byte {
	var b []byte
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sliceHeader.Len = int(cvt.LenCVT)
	sliceHeader.Cap = int(cvt.Len * cvt.LenMult)
	sliceHeader.Data = uintptr(unsafe.Pointer(cvt.Buf))
	return b
}

// GetNumAudioDrivers (https://wiki.libsdl.org/SDL_GetNumAudioDrivers)
func GetNumAudioDrivers() int {
	return int(C.SDL_GetNumAudioDrivers())
}

// GetAudioDriver (https://wiki.libsdl.org/SDL_GetAudioDriver)
func GetAudioDriver(index int) string {
	return string(C.GoString(C.SDL_GetAudioDriver(C.int(index))))
}

// AudioInit (https://wiki.libsdl.org/SDL_AudioInit)
func AudioInit(driverName string) error {
	_driverName := C.CString(driverName)
	defer C.free(unsafe.Pointer(_driverName))
	if C.SDL_AudioInit(_driverName) != 0 {
		return GetError()
	}
	return nil
}

// AudioQuit (https://wiki.libsdl.org/SDL_AudioQuit)
func AudioQuit() {
	C.SDL_AudioQuit()
}

// GetCurrentAudioDriver (https://wiki.libsdl.org/SDL_GetCurrentAudioDriver)
func GetCurrentAudioDriver() string {
	return string(C.GoString(C.SDL_GetCurrentAudioDriver()))
}

// OpenAudio (https://wiki.libsdl.org/SDL_OpenAudio)
func OpenAudio(desired, obtained *AudioSpec) error {
	if C.SDL_OpenAudio(desired.cptr(), obtained.cptr()) != 0 {
		return GetError()
	}
	return nil
}

// GetNumAudioDevices (https://wiki.libsdl.org/SDL_GetNumAudioDevices)
func GetNumAudioDevices(isCapture bool) int {
	return int(C.SDL_GetNumAudioDevices(C.int(Btoi(isCapture))))
}

// GetAudioDeviceName (https://wiki.libsdl.org/SDL_GetAudioDeviceName)
func GetAudioDeviceName(index int, isCapture bool) string {
	return string(C.GoString(C.SDL_GetAudioDeviceName(C.int(index), C.int(Btoi(isCapture)))))
}

// OpenAudioDevice (https://wiki.libsdl.org/SDL_OpenAudioDevice)
func OpenAudioDevice(device string, isCapture bool, desired, obtained *AudioSpec, allowedChanges int) (AudioDeviceID, error) {
	_device := C.CString(device)
	if device == "" {
		_device = nil
	}
	defer C.free(unsafe.Pointer(_device))
	if id := AudioDeviceID(C.SDL_OpenAudioDevice(_device, C.int(Btoi(isCapture)), desired.cptr(), obtained.cptr(), C.int(allowedChanges))); id > 0 {
		return id, nil
	}
	return 0, GetError()
}

// GetAudioStatus (https://wiki.libsdl.org/SDL_GetAudioStatus)
func GetAudioStatus() AudioStatus {
	return (AudioStatus)(C.SDL_GetAudioStatus())
}

// GetAudioDeviceStatus (https://wiki.libsdl.org/SDL_GetAudioDeviceStatus)
func GetAudioDeviceStatus(dev AudioDeviceID) AudioStatus {
	return (AudioStatus)(C.SDL_GetAudioDeviceStatus(dev.c()))
}

// PauseAudio (https://wiki.libsdl.org/SDL_PauseAudio)
func PauseAudio(pauseOn bool) {
	C.SDL_PauseAudio(C.int(Btoi(pauseOn)))
}

// PauseAudioDevice (https://wiki.libsdl.org/SDL_PauseAudioDevice)
func PauseAudioDevice(dev AudioDeviceID, pauseOn bool) {
	C.SDL_PauseAudioDevice(dev.c(), C.int(Btoi(pauseOn)))
}

// LoadWAV_RW (https://wiki.libsdl.org/SDL_LoadWAV_RW)
func LoadWAV_RW(src *RWops, freeSrc bool, spec *AudioSpec) ([]byte, *AudioSpec) {
	var _audioBuf *C.Uint8
	var _audioLen C.Uint32
	audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(src.cptr(), C.int(Btoi(freeSrc)), spec.cptr(), &_audioBuf, &_audioLen)))

	var b []byte
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sliceHeader.Len = (int)(_audioLen)
	sliceHeader.Cap = (int)(_audioLen)
	sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf))
	return b, audioSpec
}

// LoadWAV (https://wiki.libsdl.org/SDL_LoadWAV)
func LoadWAV(file string, spec *AudioSpec) ([]byte, *AudioSpec) {
	_file := C.CString(file)
	_rb := C.CString("rb")
	defer C.free(unsafe.Pointer(_file))
	defer C.free(unsafe.Pointer(_rb))

	var _audioBuf *C.Uint8
	var _audioLen C.Uint32
	audioSpec := (*AudioSpec)(unsafe.Pointer(C.SDL_LoadWAV_RW(C.SDL_RWFromFile(_file, _rb), 1, spec.cptr(), &_audioBuf, &_audioLen)))

	var b []byte
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	sliceHeader.Len = (int)(_audioLen)
	sliceHeader.Cap = (int)(_audioLen)
	sliceHeader.Data = uintptr(unsafe.Pointer(_audioBuf))
	return b, audioSpec
}

// FreeWAV (https://wiki.libsdl.org/SDL_FreeWAV)
func FreeWAV(audioBuf []uint8) {
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&audioBuf))
	_audioBuf := (*C.Uint8)(unsafe.Pointer(sliceHeader.Data))
	C.SDL_FreeWAV(_audioBuf)
}

// BuildAudioCVT (https://wiki.libsdl.org/SDL_BuildAudioCVT)
func BuildAudioCVT(cvt *AudioCVT, srcFormat AudioFormat, srcChannels uint8, srcRate int, dstFormat AudioFormat, dstChannels uint8, dstRate int) (converted bool, err error) {
	switch int(C.SDL_BuildAudioCVT(cvt.cptr(), srcFormat.c(), C.Uint8(srcChannels), C.int(srcRate), dstFormat.c(), C.Uint8(dstChannels), C.int(dstRate))) {
	case 1:
		return true, nil
	case 0:
		return false, nil
	}
	return false, GetError()
}

// ConvertAudio (https://wiki.libsdl.org/SDL_ConvertAudio)
func ConvertAudio(cvt *AudioCVT) error {
	_cvt := (*C.SDL_AudioCVT)(unsafe.Pointer(cvt))
	if C.SDL_ConvertAudio(_cvt) != 0 {
		return GetError()
	}
	return nil
}

// QueueAudio (https://wiki.libsdl.org/SDL_QueueAudio)
func QueueAudio(dev AudioDeviceID, data []byte) error {
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data))
	_data := unsafe.Pointer(sliceHeader.Data)
	_len := (C.Uint32)(sliceHeader.Len)
	if C.SDL_QueueAudio(dev.c(), _data, _len) != 0 {
		return GetError()
	}
	return nil
}

// MixAudio (https://wiki.libsdl.org/SDL_MixAudio)
func MixAudio(dst, src *uint8, len_ uint32, volume int) {
	_dst := (*C.Uint8)(unsafe.Pointer(dst))
	_src := (*C.Uint8)(unsafe.Pointer(src))
	C.SDL_MixAudio(_dst, _src, C.Uint32(len_), C.int(volume))
}

// MixAudioFormat (https://wiki.libsdl.org/SDL_MixAudioFormat)
func MixAudioFormat(dst, src *uint8, format AudioFormat, len_ uint32, volume int) {
	_dst := (*C.Uint8)(unsafe.Pointer(dst))
	_src := (*C.Uint8)(unsafe.Pointer(src))
	C.SDL_MixAudioFormat(_dst, _src, format.c(), C.Uint32(len_), C.int(volume))
}

// LockAudio (https://wiki.libsdl.org/SDL_LockAudio)
func LockAudio() {
	C.SDL_LockAudio()
}

// LockAudioDevice (https://wiki.libsdl.org/SDL_LockAudioDevice)
func LockAudioDevice(dev AudioDeviceID) {
	C.SDL_LockAudioDevice(dev.c())
}

// UnlockAudio (https://wiki.libsdl.org/SDL_UnlockAudio)
func UnlockAudio() {
	C.SDL_UnlockAudio()
}

// UnlockAudioDevice (https://wiki.libsdl.org/SDL_UnlockAudioDevice)
func UnlockAudioDevice(dev AudioDeviceID) {
	C.SDL_UnlockAudioDevice(dev.c())
}

// CloseAudio (https://wiki.libsdl.org/SDL_CloseAudio)
func CloseAudio() {
	C.SDL_CloseAudio()
}

// CloseAudioDevice (https://wiki.libsdl.org/SDL_CloseAudioDevice)
func CloseAudioDevice(dev AudioDeviceID) {
	C.SDL_CloseAudioDevice(dev.c())
}

/*
func AudioDeviceConnected(dev AudioDeviceID) int {
	_dev := (C.SDL_AudioDeviceID) (dev)
	return int (C.SDL_AudioDeviceConnected(_dev))
}
*/
<|endoftext|>


<commit_before>package main

import "os"

const (
	gcmCcsEndpoint        = "gcm.googleapis.com:5235"
	gcmCcsStagingEndpoint = "gcm-staging.googleapis.com:5236"
)

var config Config
var initialized bool

// Config describes the global configuration for the NBusy server.
type Config struct {
	App App
	GCM GCM
}

// App contains the global application variables.
type App struct {
	Env string
}

// GCM describes the Google Cloud Messaging parameters as described here: https://developer.android.com/google/gcm/gs.html
type GCM struct {
	CCSEndpoint string
	SenderID    string
	APIKey      string
}

// Config returns a singleton instance of the application configuration.
func GetConfig() Config {
	if initialized {
		return config
	}

	env := os.Getenv("GO_ENV")
	if (env == "") {
		env = "development"
	}
	app := App{Env: env}

	gcm := GCM{SenderID: os.Getenv("GCM_SENDER_ID"), APIKey: os.Getenv("GOOGLE_API_KEY")}
	if env == "development" {
		gcm.CCSEndpoint = gcmCcsStagingEndpoint
	} else {
		gcm.CCSEndpoint = gcmCcsEndpoint
	}

	config = Config{App: app, GCM: gcm}
	initialized = true
	return config
}
<commit_msg>fix gcm staging endpoint check<commit_after>package main

import "os"

const (
	gcmCcsEndpoint        = "gcm.googleapis.com:5235"
	gcmCcsStagingEndpoint = "gcm-staging.googleapis.com:5236"
)

var config Config
var initialized bool

// Config describes the global configuration for the NBusy server.
type Config struct {
	App App
	GCM GCM
}

// App contains the global application variables.
type App struct {
	Env string
}

// GCM describes the Google Cloud Messaging parameters as described here: https://developer.android.com/google/gcm/gs.html
type GCM struct {
	CCSEndpoint string
	SenderID    string
	APIKey      string
}

// Config returns a singleton instance of the application configuration.
func GetConfig() Config {
	if initialized {
		return config
	}

	env := os.Getenv("GO_ENV")
	if (env == "") {
		env = "development"
	}
	app := App{Env: env}

	gcm := GCM{SenderID: os.Getenv("GCM_SENDER_ID"), APIKey: os.Getenv("GOOGLE_API_KEY")}
	if env == "development" || env == "test" || env == "staging"  {
		gcm.CCSEndpoint = gcmCcsStagingEndpoint
	} else {
		gcm.CCSEndpoint = gcmCcsEndpoint
	}

	config = Config{App: app, GCM: gcm}
	initialized = true
	return config
}
<|endoftext|>