<commit_before>package msfapi

import (
	"bytes"
	"errors"
	"fmt"
	"gopkg.in/vmihailenco/msgpack.v2"
	"io/ioutil"
	"net/http"
)

type API struct {
	Token string
	URL   string
}

type versionInfoResponse struct {
	Version string
	Ruby    string
	API     string
}

func New(url string) *API {
	// TODO ensure url responds before continuing
	api := new(API)
	api.URL = url
	return api
}

func (api *API) AuthLogin(user, pass string) error {
	var loginResponse map[string]interface{}
	var login = []string{"auth.login", user, pass}
	err := api.request(&login, &loginResponse)
	if err != nil {
		return err
	}
	if loginResponse["error"] != nil {
		if loginResponse["error"].(bool) {
			return errors.New(fmt.Sprintf("%#v, %#v",
				loginResponse["error_class"].(string),
				loginResponse["error_message"].(string),
			))
		}
	}
	api.Token = fmt.Sprintf("%v", loginResponse["token"])
	return nil
}

func (api *API) AuthLogout() error {
	var response map[string]interface{}
	var request = []string{"auth.logout", api.Token, api.Token}
	err := api.request(&request, &response)
	if err != nil {
		return err
	}
	if response["error"] != nil {
		if response["error"].(bool) {
			return errors.New(fmt.Sprintf("%#v, %#v",
				response["error_class"].(string),
				response["error_message"].(string),
			))
		}
	}
	api.Token = fmt.Sprintf("%v", response["token"])
	return nil
}

func (api *API) CoreVersion() (versionInfoResponse, error) {
	if err := api.ensureToken(); err != nil {
		return versionInfoResponse{}, err
	}
	var response map[string]string
	var request = []string{"core.version", api.Token}
	err := api.request(&request, &response)
	if err != nil {
		return versionInfoResponse{}, err
	}
	versionInfo := versionInfoResponse{
		Version: response["version"],
		Ruby:    response["ruby"],
		API:     response["api"],
	}
	return versionInfo, nil
}

func (api *API) ModuleExecute(mType, name string, mapp map[string]interface{}) (int64, error) {
	if err := api.ensureToken(); err != nil {
		return 0, err
	}
	var response map[string]interface{}
	var request = []interface{}{"module.execute", api.Token, mType, name, mapp}
	err := api.request(&request, &response)
	if err != nil {
		return 0, err
	}
	if response["error"] != nil {
		if response["error"].(bool) {
			return 0, errors.New(fmt.Sprintf("%#v, %#v",
				response["error_class"].(string),
				response["error_message"].(string),
			))
		}
	}
	jobID := response["job_id"].(int64)
	return jobID, nil
}

func (api *API) JobList() (map[string]string, error) {
	if err := api.ensureToken(); err != nil {
		return map[string]string{}, err
	}
	var response map[string]string
	var request = []string{"job.list", api.Token}
	err := api.request(&request, &response)
	if err != nil {
		return map[string]string{}, err
	}
	return response, nil
}

func (api *API) ensureToken() error {
	if api.Token == "" {
		return errors.New("Token is empty for some reason")
	}
	return nil
}

func (api *API) request(request, response interface{}) error {
	packedBytes, err := msgpack.Marshal(request)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem with marshaling:\n\t%v\n", err))
		return err
	}

	responseReader := bytes.NewReader(packedBytes)
	resp, err := http.Post(api.URL, "binary/message-pack", responseReader)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem with posting:\n\t%v\n", err))
		return err
	}
	defer resp.Body.Close()

	receiveBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem with ReadAll:\n\t%v\n", err))
		return err
	}

	err = msgpack.Unmarshal(receiveBytes, response)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem unmarshaling:\n\t%v", err))
		return err
	}
	return nil
}
<commit_msg>Int64ify inconsistent jobID result.<commit_after>package msfapi

import (
	"bytes"
	"errors"
	"fmt"
	"gopkg.in/vmihailenco/msgpack.v2"
	"io/ioutil"
	"net/http"
)

type API struct {
	Token string
	URL   string
}

type versionInfoResponse struct {
	Version string
	Ruby    string
	API     string
}

func New(url string) *API {
	// TODO ensure url responds before continuing
	api := new(API)
	api.URL = url
	return api
}

func (api *API) AuthLogin(user, pass string) error {
	var loginResponse map[string]interface{}
	var login = []string{"auth.login", user, pass}
	err := api.request(&login, &loginResponse)
	if err != nil {
		return err
	}
	if loginResponse["error"] != nil {
		if loginResponse["error"].(bool) {
			return errors.New(fmt.Sprintf("%#v, %#v",
				loginResponse["error_class"].(string),
				loginResponse["error_message"].(string),
			))
		}
	}
	api.Token = fmt.Sprintf("%v", loginResponse["token"])
	return nil
}

func (api *API) AuthLogout() error {
	var response map[string]interface{}
	var request = []string{"auth.logout", api.Token, api.Token}
	err := api.request(&request, &response)
	if err != nil {
		return err
	}
	if response["error"] != nil {
		if response["error"].(bool) {
			return errors.New(fmt.Sprintf("%#v, %#v",
				response["error_class"].(string),
				response["error_message"].(string),
			))
		}
	}
	api.Token = fmt.Sprintf("%v", response["token"])
	return nil
}

func (api *API) CoreVersion() (versionInfoResponse, error) {
	if err := api.ensureToken(); err != nil {
		return versionInfoResponse{}, err
	}
	var response map[string]string
	var request = []string{"core.version", api.Token}
	err := api.request(&request, &response)
	if err != nil {
		return versionInfoResponse{}, err
	}
	versionInfo := versionInfoResponse{
		Version: response["version"],
		Ruby:    response["ruby"],
		API:     response["api"],
	}
	return versionInfo, nil
}

func (api *API) ModuleExecute(mType, name string, mapp map[string]interface{}) (int64, error) {
	if err := api.ensureToken(); err != nil {
		return 0, err
	}
	var response map[string]interface{}
	var request = []interface{}{"module.execute", api.Token, mType, name, mapp}
	err := api.request(&request, &response)
	if err != nil {
		return 0, err
	}
	if response["error"] != nil {
		if response["error"].(bool) {
			return 0, errors.New(fmt.Sprintf("%#v, %#v",
				response["error_class"].(string),
				response["error_message"].(string),
			))
		}
	}
	jobID := int64ify(response["job_id"])
	return jobID, nil
}

func (api *API) JobList() (map[string]string, error) {
	if err := api.ensureToken(); err != nil {
		return map[string]string{}, err
	}
	var response map[string]string
	var request = []string{"job.list", api.Token}
	err := api.request(&request, &response)
	if err != nil {
		return map[string]string{}, err
	}
	return response, nil
}

func (api *API) ensureToken() error {
	if api.Token == "" {
		return errors.New("Token is empty for some reason")
	}
	return nil
}

func (api *API) request(request, response interface{}) error {
	packedBytes, err := msgpack.Marshal(request)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem with marshaling:\n\t%v\n", err))
		return err
	}

	responseReader := bytes.NewReader(packedBytes)
	resp, err := http.Post(api.URL, "binary/message-pack", responseReader)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem with posting:\n\t%v\n", err))
		return err
	}
	defer resp.Body.Close()

	receiveBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem with ReadAll:\n\t%v\n", err))
		return err
	}

	err = msgpack.Unmarshal(receiveBytes, response)
	if err != nil {
		// return errors.New(fmt.Sprintf("problem unmarshaling:\n\t%v", err))
		return err
	}
	return nil
}

func int64ify(n interface{}) int64 {
	switch n := n.(type) {
	case int:
		return int64(n)
	case int8:
		return int64(n)
	case int16:
		return int64(n)
	case int32:
		return int64(n)
	case int64:
		return int64(n)
	case uint:
		return int64(n)
	case uintptr:
		return int64(n)
	case uint8:
		return int64(n)
	case uint16:
		return int64(n)
	case uint32:
		return int64(n)
	case uint64:
		return int64(n)
	}
	return int64(0)
}
<|endoftext|>


<commit_before>package main

import (
	"natyla"
)

/*
 * Create the server
 */
func main() {

	natyla.Start();

}

<commit_msg>github relative path<commit_after>package main

import (
	"github.com/Fersca/natyla/src/natyla"
)

/*
 * Create the server
 */
func main() {

	natyla.Start();

}

<|endoftext|>


<commit_before>package zego

import (
	"encoding/json"
)

type CommentArray struct {
	Comments []Comments `json:"comments"`
}

type Comments struct {
	Id          int           `json:"id"`
	Type        string        `json:"type"`
	Body        string        `json:"body"`
	Public      bool          `json:"public"`
	CreatedAt   string        `json:"created_at"`
	AuthorId    int           `json:"author_id"`
	Attachments []Attachments `json:"attachments"`
	Metadata    interface{}   `json:"metadata"`
	Via         interface{}   `json:"via"`
}

type Attachments struct {
	Id          int           `json:"id"`
	Name        string        `json:"name"`
	ContentURL  string        `json:"content_url"`
	ContentType string        `json:"content_type"`
	Size        int           `json:"size"`
	Thumbnails  []interface{} `json:"thumbnails"`
}
<commit_msg>Added list comments<commit_after>package zego

import (
	"encoding/json"
)

type CommentArray struct {
	Comments []Comments `json:"comments"`
}

type Comments struct {
	Id          int           `json:"id"`
	Type        string        `json:"type"`
	Body        string        `json:"body"`
	Public      bool          `json:"public"`
	CreatedAt   string        `json:"created_at"`
	AuthorId    int           `json:"author_id"`
	Attachments []Attachments `json:"attachments"`
	Metadata    interface{}   `json:"metadata"`
	Via         interface{}   `json:"via"`
}

type Attachments struct {
	Id          int           `json:"id"`
	Name        string        `json:"name"`
	ContentURL  string        `json:"content_url"`
	ContentType string        `json:"content_type"`
	Size        int           `json:"size"`
	Thumbnails  []interface{} `json:"thumbnails"`
}

func (a Auth) ListComments(ticket_id string) (*CommentArray, error) {

	CommentStruct := &CommentArray{}

	path := "/api/v2/tickets/" + ticket_id + "/comments.json"
	resource, err := api(a, "GET", path, "")
	if err != nil {
		return nil, err
	}

	json.Unmarshal([]byte(resource.Raw), CommentStruct)

	return CommentStruct, nil

}
<|endoftext|>


<commit_before>package zk

import (
	"fmt"
)

type Controller struct {
	Broker   *Broker
	BrokerId int
	Epoch    string
}

func (c *Controller) String() string {
	return fmt.Sprintf("%8d epoch:%s", c.BrokerId, c.Epoch, c.Broker.String())
}
<commit_msg>was a stupid fmt bug<commit_after>package zk

import (
	"fmt"
)

type Controller struct {
	Broker   *Broker
	BrokerId int
	Epoch    string
}

func (c *Controller) String() string {
	return fmt.Sprintf("%8d epoch:%s %s", c.BrokerId, c.Epoch, c.Broker.String())
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"encoding/xml"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/google/uuid"
)

type FileXmlT struct {
	XMLName xml.Name `xml:"File"`
	Id      string   `xml:"Id,attr"`      // 'NyagosExe'
	Name    string   `xml:"Name,attr"`    // 'nyagos.exe'
	DiskId  int      `xml:"DiskId,attr"`  // '1'
	Source  string   `xml:"Source,attr"`  // '../../cmd/amd64/nyagos.exe'
	KeyPath string   `xml:"KeyPath,attr"` // 'yes'
}

type ComponentXmlT struct {
	XMLName xml.Name `xml:"Component"`
	Id      string   `xml:"Id,attr"`
	Guid    string   `xml:"Guid,attr"`
	File    FileXmlT `xml:"File"`
}

type DirectoryXmlT struct {
	XMLName   xml.Name         `xml:"Directory"`
	Id        string           `xml:"Id,attr"`
	Name      string           `xml:"Name,attr"`
	File      []*ComponentXmlT `xml:"File,omitempty"`
	Directory []*DirectoryXmlT `xml:"Directory,omitempty"`
}

func (this *DirectoryXmlT) GetDirectory() []*DirectoryXmlT {
	return this.Directory
}
func (this *DirectoryXmlT) SetDirectory(value []*DirectoryXmlT) {
	this.Directory = value
}

func (this *DirectoryXmlT) GetFile() []*ComponentXmlT {
	return this.File
}

func (this *DirectoryXmlT) SetFile(value []*ComponentXmlT) {
	this.File = value
}

type IncludeXmlT struct {
	XMLName   xml.Name         `xml:"Include"`
	File      []*ComponentXmlT `xml:"File,omitempty"`
	Directory []*DirectoryXmlT `xml:"Directory"`
}

func (this *IncludeXmlT) GetDirectory() []*DirectoryXmlT {
	return this.Directory
}
func (this *IncludeXmlT) SetDirectory(value []*DirectoryXmlT) {
	this.Directory = value
}

func (this *IncludeXmlT) GetFile() []*ComponentXmlT {
	return this.File
}

func (this *IncludeXmlT) SetFile(value []*ComponentXmlT) {
	this.File = value
}

type DirectoryI interface {
	GetDirectory() []*DirectoryXmlT
	SetDirectory([]*DirectoryXmlT)
	GetFile() []*ComponentXmlT
	SetFile([]*ComponentXmlT)
}

var _ DirectoryI = &DirectoryXmlT{}
var _ DirectoryI = &IncludeXmlT{}

func makeId(sourcePath string) string {
	baseName := filepath.Base(sourcePath)
	suffix := filepath.Ext(sourcePath)

	left := baseName[:len(baseName)-len(suffix)]
	if len(left) <= 0 {
		left = "Dot"
	} else {
		left = strings.Title(left)
	}
	return left + strings.Title(strings.TrimLeft(suffix, "."))
}

func setFiles(this DirectoryI, subdir []string, files []*ComponentXmlT) {
	if len(subdir) <= 0 || subdir[0] == "." {
		this.SetFile(append(this.GetFile(), files...))
		return
	}
	for _, d := range this.GetDirectory() {
		if d.Name == subdir[0] {
			setFiles(d, subdir[1:], files)
			return
		}
	}
	d := &DirectoryXmlT{Id: makeId(subdir[0]) + "Dir", Name: subdir[0]}
	setFiles(d, subdir[1:], files)
	this.SetDirectory(append(this.GetDirectory(), d))
}

func SetFiles(this DirectoryI, subdir string, files []*ComponentXmlT) {
	subdirArray := strings.Split(filepath.ToSlash(subdir), "/")
	setFiles(this, subdirArray, files)
}

var rxTrimDots = regexp.MustCompile(`^(\.\./)+`)

func readerToFileObjs(uuidSeed uuid.UUID, in io.Reader) (*IncludeXmlT, error) {
	sc := bufio.NewScanner(in)
	fileXmls := []*ComponentXmlT{}
	directory := map[string][]*ComponentXmlT{}
	for sc.Scan() {
		field := strings.Fields(sc.Text())
		if len(field) <= 0 {
			continue
		}
		sourcePath := strings.TrimSpace(field[0])
		if sourcePath == "" {
			continue
		}
		sourcePath = filepath.ToSlash(sourcePath)
		if _, err := os.Stat(sourcePath); err != nil {
			return nil, fmt.Errorf("%s: %w", sourcePath, err)
		}
		dstPath := sourcePath
		if len(field) >= 2 {
			dstPath = filepath.ToSlash(strings.TrimSpace(field[1]))
		}

		id := makeId(sourcePath)
		guid := uuid.NewMD5(uuidSeed, []byte(id))
		f := &ComponentXmlT{
			Id:   id,
			Guid: guid.String(),
			File: FileXmlT{
				Id:      "F" + id,
				Name:    filepath.Base(dstPath),
				DiskId:  len(fileXmls) + 1,
				Source:  filepath.FromSlash(sourcePath),
				KeyPath: "yes",
			},
		}

		dstDir := filepath.Dir(rxTrimDots.ReplaceAllString(dstPath, ""))

		directory[dstDir] = append(directory[dstDir], f)
	}
	root := &IncludeXmlT{}
	for dirName, files := range directory {
		SetFiles(root, dirName, files)
	}
	return root, nil
}

func fileXmlToBin(xml1 *IncludeXmlT) ([]byte, error) {
	return xml.MarshalIndent(xml1, "", "    ")
}

func MakeWxi(fileList io.Reader, uuidSeed string, wxsOutput io.Writer) error {
	seed, err := uuid.Parse(uuidSeed)
	if err != nil {
		return err
	}
	xml1, err := readerToFileObjs(seed, fileList)
	if err != nil {
		return err
	}
	bin, err := fileXmlToBin(xml1)
	if err != nil {
		return err
	}
	bw := bufio.NewWriter(wxsOutput)
	bw.Write([]byte(xml.Header))
	bw.Write(bin)
	bw.Write([]byte{'\n'})
	bw.Flush()
	return nil
}

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr,
			"Usage: %s SeedUUID < FileList.txt > Files.wxi\n",
			os.Args[0])
		os.Exit(2)
	}
	if err := MakeWxi(os.Stdin, os.Args[1], os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
}
<commit_msg>installer: unify two tools (WIP)<commit_after>package main

import (
	"bufio"
	"encoding/xml"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/google/uuid"
)

type FileXml struct {
	XMLName xml.Name `xml:"File"`
	Id      string   `xml:"Id,attr"`      // 'NyagosExe'
	Name    string   `xml:"Name,attr"`    // 'nyagos.exe'
	DiskId  int      `xml:"DiskId,attr"`  // '1'
	Source  string   `xml:"Source,attr"`  // '../../cmd/amd64/nyagos.exe'
	KeyPath string   `xml:"KeyPath,attr"` // 'yes'
}

type ComponentXml struct {
	XMLName xml.Name `xml:"Component"`
	Id      string   `xml:"Id,attr"`
	Guid    string   `xml:"Guid,attr"`
	File    FileXml  `xml:"File"`
}

type DirectoryXml struct {
	XMLName   xml.Name        `xml:"Directory"`
	Id        string          `xml:"Id,attr"`
	Name      string          `xml:"Name,attr"`
	File      []*ComponentXml `xml:"File,omitempty"`
	Directory []*DirectoryXml `xml:"Directory,omitempty"`
}

func (this *DirectoryXml) GetDirectory() []*DirectoryXml {
	return this.Directory
}
func (this *DirectoryXml) SetDirectory(value []*DirectoryXml) {
	this.Directory = value
}

func (this *DirectoryXml) GetFile() []*ComponentXml {
	return this.File
}

func (this *DirectoryXml) SetFile(value []*ComponentXml) {
	this.File = value
}

type IncludeXml struct {
	XMLName   xml.Name        `xml:"Include"`
	File      []*ComponentXml `xml:"File,omitempty"`
	Directory []*DirectoryXml `xml:"Directory"`
}

func (this *IncludeXml) GetDirectory() []*DirectoryXml {
	return this.Directory
}
func (this *IncludeXml) SetDirectory(value []*DirectoryXml) {
	this.Directory = value
}

func (this *IncludeXml) GetFile() []*ComponentXml {
	return this.File
}

func (this *IncludeXml) SetFile(value []*ComponentXml) {
	this.File = value
}

func (this *IncludeXml) WriteTo(out io.Writer) (int64, error) {
	bin, err := xml.MarshalIndent(this, "", "    ")
	if err != nil {
		return 0, err
	}
	n, err := out.Write(bin)
	return int64(n), err
}

type DirectoryI interface {
	GetDirectory() []*DirectoryXml
	SetDirectory([]*DirectoryXml)
	GetFile() []*ComponentXml
	SetFile([]*ComponentXml)
}

func makeId(sourcePath string) string {
	baseName := filepath.Base(sourcePath)
	suffix := filepath.Ext(sourcePath)

	left := baseName[:len(baseName)-len(suffix)]
	if len(left) <= 0 {
		left = "Dot"
	} else {
		left = strings.Title(left)
	}
	return left + strings.Title(strings.TrimLeft(suffix, "."))
}

func setFiles(this DirectoryI, subdir []string, files []*ComponentXml) {
	if len(subdir) <= 0 || subdir[0] == "." {
		this.SetFile(append(this.GetFile(), files...))
		return
	}
	for _, d := range this.GetDirectory() {
		if d.Name == subdir[0] {
			setFiles(d, subdir[1:], files)
			return
		}
	}
	d := &DirectoryXml{Id: makeId(subdir[0]) + "Dir", Name: subdir[0]}
	setFiles(d, subdir[1:], files)
	this.SetDirectory(append(this.GetDirectory(), d))
}

func SetFiles(this DirectoryI, subdir string, files []*ComponentXml) {
	subdirArray := strings.Split(filepath.ToSlash(subdir), "/")
	setFiles(this, subdirArray, files)
}

var rxTrimDots = regexp.MustCompile(`^(\.\./)+`)

type ComponentRefXml struct {
	XMLName xml.Name `xml:"ComponentRef"`
	Id      string   `xml:"Id,attr"`
}

type Include2Xml struct {
	XMLName      xml.Name           `xml:"Include"`
	ComponentRef []*ComponentRefXml `xml:"ComponentRef"`
}

func (this *Include2Xml) WriteTo(out io.Writer) (int64, error) {
	bin, err := xml.MarshalIndent(this, "", "    ")
	if err != nil {
		return 0, err
	}
	n, err := out.Write(bin)
	return int64(n), err
}

func readerToFileObjs(uuidSeed uuid.UUID, in io.Reader) ([]io.WriterTo, error) {
	sc := bufio.NewScanner(in)
	fileXmls := []*ComponentXml{}
	directory := map[string][]*ComponentXml{}
	references := []*ComponentRefXml{}
	for sc.Scan() {
		field := strings.Fields(sc.Text())
		if len(field) <= 0 {
			continue
		}
		sourcePath := strings.TrimSpace(field[0])
		if sourcePath == "" {
			continue
		}
		sourcePath = filepath.ToSlash(sourcePath)
		if _, err := os.Stat(sourcePath); err != nil {
			return nil, fmt.Errorf("%s: %w", sourcePath, err)
		}
		dstPath := sourcePath
		if len(field) >= 2 {
			dstPath = filepath.ToSlash(strings.TrimSpace(field[1]))
		}

		id := makeId(sourcePath)
		guid := uuid.NewMD5(uuidSeed, []byte(id))
		f := &ComponentXml{
			Id:   id,
			Guid: guid.String(),
			File: FileXml{
				Id:      "F" + id,
				Name:    filepath.Base(dstPath),
				DiskId:  len(fileXmls) + 1,
				Source:  filepath.FromSlash(sourcePath),
				KeyPath: "yes",
			},
		}

		dstDir := filepath.Dir(rxTrimDots.ReplaceAllString(dstPath, ""))

		directory[dstDir] = append(directory[dstDir], f)

		references = append(references, &ComponentRefXml{Id: id})
	}
	root := &IncludeXml{}
	for dirName, files := range directory {
		SetFiles(root, dirName, files)
	}
	return []io.WriterTo{root, &Include2Xml{ComponentRef: references}}, nil
}

func outputWithXmlHeader(xml1 io.WriterTo,w io.Writer) error {
	bw := bufio.NewWriter(w)
	if _, err := bw.WriteString(xml.Header); err != nil {
		return err
	}
	if _, err := xml1.WriteTo(bw); err != nil {
		return err
	}
	if err := bw.WriteByte('\n'); err != nil {
		return err
	}
	return bw.Flush()
}

func MakeWxi(fileList io.Reader, uuidSeed string, out []io.Writer) error {
	seed, err := uuid.Parse(uuidSeed)
	if err != nil {
		return err
	}
	xmls, err := readerToFileObjs(seed, fileList)
	if err != nil {
		return err
	}
	for i, xml1 := range xmls {
		if i >= len(out) {
			break
		}
		if out[i] == nil {
			continue
		}
		if err := outputWithXmlHeader(xml1,out[i]) ; err != nil {
			return err
		}
	}
	return nil
}

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr,
			"Usage: %s SeedUUID < FileList.txt > Files.wxi\n",
			os.Args[0])
		os.Exit(2)
	}
	if err := MakeWxi(os.Stdin, os.Args[1], []io.Writer{os.Stdout}); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package vagrantutil

import (
	"bytes"
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
)

//go:generate stringer -type=BoxSubcommand,Status  -output=stringer.go

type (
	BoxSubcommand int
	Status        int
)

const (
	Add BoxSubcommand = iota
	List
	Outdated
	Remove
	Repackage
	Update
)

const (
	Unknown Status = iota
	NotCreated
	Running
	Saved
)

type Vagrant struct {
	// VagrantfilePath is the directory with specifies the directory where
	// Vagrantfile is being stored.
	VagrantfilePath string
}

// NewVagrant returns a new Vagrant instance for the given name. The name
// should be unique. If the name already exists in the system it'll be used, if
// not a new setup will be createad.
func NewVagrant(name string) (*Vagrant, error) {
	u, err := user.Current()
	if err != nil {
		return nil, err
	}

	if name == "" {
		return nil, err
	}

	vagrantHome := filepath.Join(u.HomeDir, ".koding-boxes", name)
	if err := os.MkdirAll(vagrantHome, 0755); err != nil {
		return nil, err
	}

	return &Vagrant{
		VagrantfilePath: vagrantHome,
	}, nil
}

func (v *Vagrant) Version() (string, error) {
	out, err := v.runCommand("version")
	if err != nil {
		return "", err
	}

	records, err := parseRecords(out)
	if err != nil {
		return "", err
	}

	versionInstalled, err := parseData(records, "version-installed")
	if err != nil {
		return "", err
	}

	return versionInstalled, nil
}

func (v *Vagrant) Box(subcommand BoxSubcommand) (string, error) {
	out, err := v.runCommand("box", subcommand.String())
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(out), nil
}

func (v *Vagrant) Status() (Status, error) {
	if err := v.vagrantfileExists(); err != nil {
		return Unknown, err
	}

	out, err := v.runCommand("status")
	if err != nil {
		return Unknown, err
	}

	records, err := parseRecords(out)
	if err != nil {
		return Unknown, err
	}

	status, err := parseData(records, "state")
	if err != nil {
		return Unknown, err
	}

	return toStatus(status), nil
}

// Up executes "vagrant up" for the given vagrantfile. The returned reader
// contains the output stream. The client is responsible of calling the Close
// method of the returned reader.
func (v *Vagrant) Up(vagrantfile string) (io.ReadCloser, error) {
	if vagrantfile == "" {
		return nil, errors.New("Vagrantfile content is empty")
	}

	// if it's exists, don't overwrite anything and use the existing one
	if err := v.vagrantfileExists(); err != nil {
		err := ioutil.WriteFile(v.vagrantfile(), []byte(vagrantfile), 0644)
		if err != nil {
			return nil, err
		}
	} else {
		// TODO(arslan): replace logging with koding/logging
		log.Printf("Using existing Vagrantfile at %s", v.VagrantfilePath)
	}

	cmd := v.createCommand("up")
	pipe, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if err := cmd.Start(); err != nil {
		return nil, err
	}

	go func() {
		if err := cmd.Wait(); err != nil {
			log.Printf("[error]: vagrant up error: %s", err)
		}
	}()

	return pipe, nil
}

// Destroy executes "vagrant destroy". The returned reader contains the output
// stream. The client is responsible of calling the Close method of the
// returned reader.
func (v *Vagrant) Destroy() (io.ReadCloser, error) {
	if err := v.vagrantfileExists(); err != nil {
		return nil, err
	}

	cmd := v.createCommand("destroy", "--force")
	pipe, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if err := cmd.Start(); err != nil {
		return nil, err
	}

	go func() {
		if err := cmd.Wait(); err != nil {
			log.Printf("[error]: vagrant up error: %s", err)
		}
	}()

	return pipe, nil
}

// vagrantfile returns the Vagrantfile path
func (v *Vagrant) vagrantfile() string {
	return filepath.Join(v.VagrantfilePath, "Vagrantfile")
}

// vagrantfileExists checks if a Vagrantfile exists in the given path. It
// returns a nil error if exists.
func (v *Vagrant) vagrantfileExists() error {
	if _, err := os.Stat(v.vagrantfile()); os.IsNotExist(err) {
		return err
	}
	return nil
}

func (v *Vagrant) createCommand(args ...string) *exec.Cmd {
	cmd := exec.Command("vagrant", args...)
	cmd.Dir = v.VagrantfilePath
	return cmd
}

func (v *Vagrant) runCommand(args ...string) (string, error) {
	args = append(args, "--machine-readable")
	cmd := exec.Command("vagrant", args...)
	cmd.Dir = v.VagrantfilePath
	out, err := cmd.CombinedOutput()
	if err != nil {
		return "", err
	}

	return string(out), nil
}

func parseData(records [][]string, typeName string) (string, error) {
	data := ""
	for _, record := range records {
		// first three are defined, after that data is variadic, it contains
		// zero or more information. We should have a data, otherwise it's
		// useless.
		if len(record) < 4 {
			continue
		}

		if typeName == record[2] {
			data = record[3]
		}
	}

	if data == "" {
		return "", fmt.Errorf("couldn't parse data for vagrant type: '%s'", typeName)
	}

	return data, nil
}

func parseRecords(out string) ([][]string, error) {
	buf := bytes.NewBufferString(out)
	c := csv.NewReader(buf)
	return c.ReadAll()
}

// toStatus convers the given state string to Status type
func toStatus(state string) Status {
	switch state {
	case "running":
		return Running
	case "not_created":
		return NotCreated
	case "saved":
		return Saved
	default:
		return Unknown
	}

}
<commit_msg>vagrant: state should return an error to catch unknown states<commit_after>package vagrantutil

import (
	"bytes"
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
)

//go:generate stringer -type=BoxSubcommand,Status  -output=stringer.go

type (
	BoxSubcommand int
	Status        int
)

const (
	Add BoxSubcommand = iota
	List
	Outdated
	Remove
	Repackage
	Update
)

const (
	// Some possible states:
	// https://github.com/mitchellh/vagrant/blob/master/templates/locales/en.yml#L1504
	Unknown Status = iota
	NotCreated
	Running
	Saved
	PowerOff
)

type Vagrant struct {
	// VagrantfilePath is the directory with specifies the directory where
	// Vagrantfile is being stored.
	VagrantfilePath string
}

// NewVagrant returns a new Vagrant instance for the given name. The name
// should be unique. If the name already exists in the system it'll be used, if
// not a new setup will be createad.
func NewVagrant(name string) (*Vagrant, error) {
	u, err := user.Current()
	if err != nil {
		return nil, err
	}

	if name == "" {
		return nil, err
	}

	vagrantHome := filepath.Join(u.HomeDir, ".koding-boxes", name)
	if err := os.MkdirAll(vagrantHome, 0755); err != nil {
		return nil, err
	}

	return &Vagrant{
		VagrantfilePath: vagrantHome,
	}, nil
}

func (v *Vagrant) Version() (string, error) {
	out, err := v.runCommand("version")
	if err != nil {
		return "", err
	}

	records, err := parseRecords(out)
	if err != nil {
		return "", err
	}

	versionInstalled, err := parseData(records, "version-installed")
	if err != nil {
		return "", err
	}

	return versionInstalled, nil
}

func (v *Vagrant) Box(subcommand BoxSubcommand) (string, error) {
	out, err := v.runCommand("box", subcommand.String())
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(out), nil
}

func (v *Vagrant) Status() (Status, error) {
	if err := v.vagrantfileExists(); err != nil {
		return Unknown, err
	}

	out, err := v.runCommand("status")
	if err != nil {
		return Unknown, err
	}

	records, err := parseRecords(out)
	if err != nil {
		return Unknown, err
	}

	status, err := parseData(records, "state")
	if err != nil {
		return Unknown, err
	}

	return toStatus(status)
}

// Up executes "vagrant up" for the given vagrantfile. The returned reader
// contains the output stream. The client is responsible of calling the Close
// method of the returned reader.
func (v *Vagrant) Up(vagrantfile string) (io.ReadCloser, error) {
	if vagrantfile == "" {
		return nil, errors.New("Vagrantfile content is empty")
	}

	// if it's exists, don't overwrite anything and use the existing one
	if err := v.vagrantfileExists(); err != nil {
		err := ioutil.WriteFile(v.vagrantfile(), []byte(vagrantfile), 0644)
		if err != nil {
			return nil, err
		}
	} else {
		// TODO(arslan): replace logging with koding/logging
		log.Printf("Using existing Vagrantfile at %s", v.VagrantfilePath)
	}

	cmd := v.createCommand("up")
	pipe, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if err := cmd.Start(); err != nil {
		return nil, err
	}

	go func() {
		if err := cmd.Wait(); err != nil {
			log.Printf("[error]: vagrant up error: %s", err)
		}
	}()

	return pipe, nil
}

// Destroy executes "vagrant destroy". The returned reader contains the output
// stream. The client is responsible of calling the Close method of the
// returned reader.
func (v *Vagrant) Destroy() (io.ReadCloser, error) {
	if err := v.vagrantfileExists(); err != nil {
		return nil, err
	}

	cmd := v.createCommand("destroy", "--force")
	pipe, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if err := cmd.Start(); err != nil {
		return nil, err
	}

	go func() {
		if err := cmd.Wait(); err != nil {
			log.Printf("[error]: vagrant up error: %s", err)
		}
	}()

	return pipe, nil
}

// vagrantfile returns the Vagrantfile path
func (v *Vagrant) vagrantfile() string {
	return filepath.Join(v.VagrantfilePath, "Vagrantfile")
}

// vagrantfileExists checks if a Vagrantfile exists in the given path. It
// returns a nil error if exists.
func (v *Vagrant) vagrantfileExists() error {
	if _, err := os.Stat(v.vagrantfile()); os.IsNotExist(err) {
		return err
	}
	return nil
}

func (v *Vagrant) createCommand(args ...string) *exec.Cmd {
	cmd := exec.Command("vagrant", args...)
	cmd.Dir = v.VagrantfilePath
	return cmd
}

func (v *Vagrant) runCommand(args ...string) (string, error) {
	args = append(args, "--machine-readable")
	cmd := exec.Command("vagrant", args...)
	cmd.Dir = v.VagrantfilePath
	out, err := cmd.CombinedOutput()
	if err != nil {
		return "", err
	}

	return string(out), nil
}

func parseData(records [][]string, typeName string) (string, error) {
	data := ""
	for _, record := range records {
		// first three are defined, after that data is variadic, it contains
		// zero or more information. We should have a data, otherwise it's
		// useless.
		if len(record) < 4 {
			continue
		}

		if typeName == record[2] {
			data = record[3]
		}
	}

	if data == "" {
		return "", fmt.Errorf("couldn't parse data for vagrant type: '%s'", typeName)
	}

	return data, nil
}

func parseRecords(out string) ([][]string, error) {
	buf := bytes.NewBufferString(out)
	c := csv.NewReader(buf)
	return c.ReadAll()
}

// toStatus convers the given state string to Status type
func toStatus(state string) (Status, error) {
	switch state {
	case "running":
		return Running, nil
	case "not_created":
		return NotCreated, nil
	case "saved":
		return Saved, nil
	case "poweroff":
		return PowerOff, nil
	default:
		return Unknown, fmt.Errorf("Unknown state: %s", state)
	}

}
<|endoftext|>


<commit_before>package controllers

import (
	"github.com/robfig/revel"
	"os"
	fpath "path/filepath"
)

type Static struct {
	*revel.Controller
}

func (c Static) ServeDir(prefix, filepath string) revel.Result {
	var basePath string

	if !fpath.IsAbs(prefix) {
		basePath = revel.BasePath
	}

	fname := fpath.Join(basePath, fpath.FromSlash(prefix), fpath.FromSlash(filepath))
	file, err := os.Open(fname)
	if os.IsNotExist(err) {
		revel.WARN.Printf("File not found (%s): %s ", fname, err)
		return c.NotFound("")
	} else if err != nil {
		revel.WARN.Printf("Problem opening file (%s): %s ", fname, err)
		return c.NotFound("This was found but not sure why we couldn't open it.")
	}
	return c.RenderFile(file, "")
}

func (c Static) ServeFile(filepath string) revel.Result {
	return c.ServeDir("", filepath)
}
<commit_msg>Fix absolute path routing for ServeFile()<commit_after>package controllers

import (
	"github.com/robfig/revel"
	"os"
	fpath "path/filepath"
)

type Static struct {
	*revel.Controller
}

func (c Static) ServeDir(prefix, filepath string) revel.Result {
	var basePath string

	if !fpath.IsAbs(prefix) {
		basePath = revel.BasePath
	}

	fname := fpath.Join(basePath, fpath.FromSlash(prefix), fpath.FromSlash(filepath))
	file, err := os.Open(fname)
	if os.IsNotExist(err) {
		revel.WARN.Printf("File not found (%s): %s ", fname, err)
		return c.NotFound("")
	} else if err != nil {
		revel.WARN.Printf("Problem opening file (%s): %s ", fname, err)
		return c.NotFound("This was found but not sure why we couldn't open it.")
	}
	return c.RenderFile(file, "")
}

func (c Static) ServeFile(filepath string) revel.Result {
	if !fpath.IsAbs(filepath) {
		return c.ServeDir("", filepath)
	}
	return c.ServeDir("/", filepath)
}
<|endoftext|>


<commit_before>// Copyright (c) 2013, Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

// Package notify provides DBus notifications.
//
// WARNING: You are free to use this package, however please note that the API is
// likely to be unstable till all the functionality is implemented, and there is
// a lot missing!
//
// There is not much you need to do use this package, just start sending
// notifications:
//
//	func main() {
//		id, err := notify.SendMsg("My summary", "My body, which some notification services don't show")
//		if err != nil {
//			fmt.Println(err)
//		}
//		// You can also ignore the error message, in which case failed notifications are ignored,
//		// because let's be honest, who cares if the notifications get delivered or not? ;-)
//		notify.ReplaceUrgentMsg("Forget that last message", "", notify.LowUrgency)
//	}
//
// The defaults are a timeout of 3 seconds for notifications and a normal
// urgency, with everything being empty.  You are free to change these via
// Init, SetName, SetTimeout, SetIconPath, and SetUrgency.
//
// Alternatively, you can create your own Notification template, via New.
//
// The notify package has been developed according to
// https://developer.gnome.org/notification-spec, although there is a lot of
// functionality missing.
//
// There is some markup that you can use in the summary and body parts of a
// notification:
//
//	bold
//	italic
//	underline
//	hyperlink
//
//
// I have tried to implement this in the Go philosophy, please let me know if
// I can improve it somehow.
package notify

import (
	"time"
)

// note acts as the default notification, which allows you to set default
// parameters and then send messages without creating any Notifications.
var note = Notification{
	Timeout: 3 * time.Second,
	Urgency: NormalUrgency,
}

// Init sets the defaults for the implicit notification.
func Init(name, icon string, timeout time.Duration, urgency NotificationUrgency) {
	note.Name = name
	note.IconPath = icon
	note.Timeout = timeout
	note.Urgency = urgency
}

// Name returns the name for the implicit notification.
func Name() string { return note.Name }

// SetName sets the name for the implicit notification.
func SetName(name string) { note.Name = name }

// IconPath returns the icon path for the implicit notification.
func IconPath() string { return note.IconPath }

// SetIconPath sets the icon path for the implicit notification.
func SetIconPath(path string) { note.IconPath = path }

// Timeout returns the timeout for the implicit notification.
func Timeout() time.Duration { return note.Timeout }

// SetTimeout sets the timeout for the implicit notification.
func SetTimeout(dur time.Duration) { note.Timeout = dur }

// Urgency returns the urgency level for the implicit notification.
// It can be either LowUrgency, NormalUrgency, or CriticalUrgency.
func Urgency() NotificationUrgency { return note.Urgency }

// SetUrgency sets the urgency level for the implicit notification.
// It can be either LowUrgency, NormalUrgency, or CriticalUrgency.
func SetUrgency(urgency NotificationUrgency) { note.Urgency = urgency }

// SendMsg sends the summary and the body as a notification, returning a unique
// notification ID and an error, possibly nil. It takes all other values from
// the implicit notification object.
func SendMsg(summary, body string) (id uint32, err error) {
	return note.SendMsg(summary, body)
}

// SendUrgentMsg sends the summary and the body as a notification with the
// urgency of urgency, and returns a unique notification ID and an error,
// possibly nil. Otherwise it is like SendMsg.
func SendUrgentMsg(summary, body string, urgency NotificationUrgency) (id uint32, err error) {
	return note.SendUrgentMsg(summary, body, urgency)
}

// ReplaceMsg replaces the already existing notification with the ID id with
// summary and body, returning an error if it fails. It takes all other values
// from the implicit notification object.
//
// In particular, if the notification it is replacing had other properties,
// such as another urgency, these are also replaced by the defaults in the
// implicit notification!
func ReplaceMsg(id uint32, summary, body string) error {
	return note.ReplaceMsg(id, summary, body)
}

// ReplaceUrgentMsg replaces the already existing notification with the ID id
// with summary and body and urgency, returning an error if it fails. It takes
// all other values from the implicit notification object.
func ReplaceUrgentMsg(id uint32, summary, body string, urgency NotificationUrgency) error {
	return note.ReplaceUrgentMsg(id, summary, body, urgency)
}
<commit_msg>Updating package summary<commit_after>// Copyright (c) 2013, Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

// Package notify provides tray notifications via D-Bus freedesktop.org notifications.
//
// WARNING: You are free to use this package, however please note that the API is
// likely to be unstable till all the functionality is implemented, and there is
// a lot missing!
//
// There is not much you need to do use this package, just start sending
// notifications:
//
//	func main() {
//		id, err := notify.SendMsg("My summary", "My body, which some notification services don't show")
//		if err != nil {
//			fmt.Println(err)
//		}
//		// You can also ignore the error message, in which case failed notifications are ignored,
//		// because let's be honest, who cares if the notifications get delivered or not? ;-)
//		notify.ReplaceUrgentMsg("Forget that last message", "", notify.LowUrgency)
//	}
//
// The defaults are a timeout of 3 seconds for notifications and a normal
// urgency, with everything being empty.  You are free to change these via
// Init, SetName, SetTimeout, SetIconPath, and SetUrgency.
//
// Alternatively, you can create your own Notification template, via New.
//
// The notify package has been developed according to
// https://developer.gnome.org/notification-spec, although there is a lot of
// functionality missing.
//
// There is some markup that you can use in the summary and body parts of a
// notification:
//
//	bold
//	italic
//	underline
//	hyperlink
//
//
// I have tried to implement this in the Go philosophy, please let me know if
// I can improve it somehow.
package notify

import (
	"time"
)

// note acts as the default notification, which allows you to set default
// parameters and then send messages without creating any Notifications.
var note = Notification{
	Timeout: 3 * time.Second,
	Urgency: NormalUrgency,
}

// Init sets the defaults for the implicit notification.
func Init(name, icon string, timeout time.Duration, urgency NotificationUrgency) {
	note.Name = name
	note.IconPath = icon
	note.Timeout = timeout
	note.Urgency = urgency
}

// Name returns the name for the implicit notification.
func Name() string { return note.Name }

// SetName sets the name for the implicit notification.
func SetName(name string) { note.Name = name }

// IconPath returns the icon path for the implicit notification.
func IconPath() string { return note.IconPath }

// SetIconPath sets the icon path for the implicit notification.
func SetIconPath(path string) { note.IconPath = path }

// Timeout returns the timeout for the implicit notification.
func Timeout() time.Duration { return note.Timeout }

// SetTimeout sets the timeout for the implicit notification.
func SetTimeout(dur time.Duration) { note.Timeout = dur }

// Urgency returns the urgency level for the implicit notification.
// It can be either LowUrgency, NormalUrgency, or CriticalUrgency.
func Urgency() NotificationUrgency { return note.Urgency }

// SetUrgency sets the urgency level for the implicit notification.
// It can be either LowUrgency, NormalUrgency, or CriticalUrgency.
func SetUrgency(urgency NotificationUrgency) { note.Urgency = urgency }

// SendMsg sends the summary and the body as a notification, returning a unique
// notification ID and an error, possibly nil. It takes all other values from
// the implicit notification object.
func SendMsg(summary, body string) (id uint32, err error) {
	return note.SendMsg(summary, body)
}

// SendUrgentMsg sends the summary and the body as a notification with the
// urgency of urgency, and returns a unique notification ID and an error,
// possibly nil. Otherwise it is like SendMsg.
func SendUrgentMsg(summary, body string, urgency NotificationUrgency) (id uint32, err error) {
	return note.SendUrgentMsg(summary, body, urgency)
}

// ReplaceMsg replaces the already existing notification with the ID id with
// summary and body, returning an error if it fails. It takes all other values
// from the implicit notification object.
//
// In particular, if the notification it is replacing had other properties,
// such as another urgency, these are also replaced by the defaults in the
// implicit notification!
func ReplaceMsg(id uint32, summary, body string) error {
	return note.ReplaceMsg(id, summary, body)
}

// ReplaceUrgentMsg replaces the already existing notification with the ID id
// with summary and body and urgency, returning an error if it fails. It takes
// all other values from the implicit notification object.
func ReplaceUrgentMsg(id uint32, summary, body string, urgency NotificationUrgency) error {
	return note.ReplaceUrgentMsg(id, summary, body, urgency)
}
<|endoftext|>


<commit_before>// Copyright 2014 The Cayley Authors. All rights reserved.
//
// 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 (
	"bufio"
	"fmt"
	"io"
	"strings"
)

func isWhitespace(s uint8) bool {
	return (s == '\t' || s == '\r' || s == ' ')
}
func Parse(str string) *Triple {
	// Skip leading whitespace.
	str = skipWhitespace(str)
	// Check for a comment
	if str != "" && str[0] == '#' {
		return nil
	}
	sub, remainder := getTripleComponent(str)
	if sub == nil {
		return nil
	}
	str = skipWhitespace(remainder)
	pred, remainder := getTripleComponent(str)
	if pred == nil {
		return nil
	}
	str = skipWhitespace(remainder)
	obj, remainder := getTripleComponent(str)
	if obj == nil {
		return nil
	}
	str = skipWhitespace(remainder)
	prov_ptr, remainder := getTripleComponent(str)
	var prov string
	if prov_ptr == nil {
		prov = ""
	} else {
		prov = *prov_ptr
	}
	str = skipWhitespace(remainder)
	if str != "" && str[0] == '.' {
		return &Triple{[]byte(*sub), []byte(*pred), []byte(*obj), []byte(prov)}
	}
	return nil
}

func skipWhitespace(str string) string {
	i := 0
	for i < len(str) && isWhitespace(str[i]) {
		i += 1
	}
	return str[i:]
}

func getTripleComponent(str string) (*string, string) {
	if len(str) == 0 {
		return nil, str
	}
	if str[0] == '<' {
		return getUriPart(str[1:])
	} else if str[0] == '"' {
		return getQuotedPart(str[1:])
	} else if str[0] == '.' {
		return nil, str
	} else {
		// Technically not part of the spec. But we do it anyway for convenience.
		return getUnquotedPart(str)
	}
}

func getUriPart(str string) (*string, string) {
	i := 0
	for i < len(str) && str[i] != '>' {
		i += 1
	}
	if i == len(str) {
		return nil, str
	}
	part := str[0:i]
	return &part, str[i+1:]
}

func getQuotedPart(str string) (*string, string) {
	i := 0
	start := 0
	out := ""
	for i < len(str) && str[i] != '"' {
		if str[i] == '\\' {
			out += str[start:i]
			switch str[i+1] {
			case '\\':
				out += "\\"
			case 'r':
				out += "\r"
			case 'n':
				out += "\n"
			case 't':
				out += "\t"
			case '"':
				out += "\""
			default:
				return nil, str
			}
			i += 2
			start = i
			continue
		}
		i += 1
	}
	if i == len(str) {
		return nil, str
	}
	out += str[start:i]
	i += 1
	var remainder string
	if strings.HasPrefix(str[i:], "^^<") {
		// Ignore type, for now
		_, remainder = getUriPart(str[i+3:])
	} else if strings.HasPrefix(str[i:], "@") {
		_, remainder = getUnquotedPart(str[i+1:])
	} else {
		remainder = str[i:]
	}

	return &out, remainder
}

func getUnquotedPart(str string) (*string, string) {
	i := 0
	initStr := str
	out := ""
	start := 0
	for i < len(str) && !isWhitespace(str[i]) {
		if str[i] == '"' {
			part, remainder := getQuotedPart(str[i+1:])
			if part == nil {
				return part, initStr
			}
			out += str[start:i]
			str = remainder
			i = 0
			start = 0
			out += *part
		}
		i += 1
	}
	out += str[start:i]
	return &out, str[i:]
}

func ReadNQuadsFromReader(c chan *Triple, reader io.Reader) {
	bf := bufio.NewReader(reader)

	nTriples := 0
	line := ""
	for {
		l, pre, err := bf.ReadLine()
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(fmt.Errorf("Something bad happened while reading file: %v", err.Error()))
		}
		line += string(l)
		if pre {
			continue
		}
		triple := Parse(line)
		line = ""
		if triple != nil {
			nTriples++
			c <- triple
		}
	}

	close(c)
}
<commit_msg>Only process English strings.<commit_after>// Copyright 2014 The Cayley Authors. All rights reserved.
//
// 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 (
	"bufio"
	"fmt"
	"io"
	"strings"
)

const onlyLang = "en"

func isWhitespace(s uint8) bool {
	return (s == '\t' || s == '\r' || s == ' ')
}
func Parse(str string) *Triple {
	// Skip leading whitespace.
	str = skipWhitespace(str)
	// Check for a comment
	if str != "" && str[0] == '#' {
		return nil
	}
	sub, remainder := getTripleComponent(str)
	if sub == nil {
		return nil
	}
	str = skipWhitespace(remainder)
	pred, remainder := getTripleComponent(str)
	if pred == nil {
		return nil
	}
	str = skipWhitespace(remainder)
	obj, remainder := getTripleComponent(str)
	if obj == nil {
		return nil
	}
	str = skipWhitespace(remainder)
	prov_ptr, remainder := getTripleComponent(str)
	var prov string
	if prov_ptr == nil {
		prov = ""
	} else {
		prov = *prov_ptr
	}
	str = skipWhitespace(remainder)

	// fmt.Printf("line %s %s %s %s\n", *sub, *pred, *obj, prov)

	if str != "" && str[0] == '.' {
		return &Triple{[]byte(*sub), []byte(*pred), []byte(*obj), []byte(prov)}
	}
	return nil
}

func skipWhitespace(str string) string {
	i := 0
	for i < len(str) && isWhitespace(str[i]) {
		i += 1
	}
	return str[i:]
}

func getTripleComponent(str string) (*string, string) {
	if len(str) == 0 {
		return nil, str
	}
	if str[0] == '<' {
		return getUriPart(str[1:])
	} else if str[0] == '"' {
		return getQuotedPart(str[1:])
	} else if str[0] == '.' {
		return nil, str
	} else {
		// Technically not part of the spec. But we do it anyway for convenience.
		return getUnquotedPart(str)
	}
}

func getUriPart(str string) (*string, string) {
	i := 0
	for i < len(str) && str[i] != '>' {
		i += 1
	}
	if i == len(str) {
		return nil, str
	}
	part := str[0:i]
	return &part, str[i+1:]
}

func getQuotedPart(str string) (*string, string) {
	i := 0
	start := 0
	out := ""
	for i < len(str) && str[i] != '"' {
		if str[i] == '\\' {
			out += str[start:i]
			switch str[i+1] {
			case '\\':
				out += "\\"
			case 'r':
				out += "\r"
			case 'n':
				out += "\n"
			case 't':
				out += "\t"
			case '"':
				out += "\""
			default:
				return nil, str
			}
			i += 2
			start = i
			continue
		}
		i += 1
	}
	if i == len(str) {
		return nil, str
	}
	out += str[start:i]
	i += 1
	var remainder string
	if strings.HasPrefix(str[i:], "^^<") {
		// Ignore type, for now
		_, remainder = getUriPart(str[i+3:])
	} else if strings.HasPrefix(str[i:], "@") {
		_, remainder = getUnquotedPart(str[i+1:])
		lang := getLanguage(str[i:])
		if lang != onlyLang {
			return nil, ""
		}
		// out = lang + "@" + out
	} else {
		remainder = str[i:]
	}

	return &out, remainder
}

func getLanguage (str string) string {
	i := 1
	lang := ""
	for i < len(str) && !isWhitespace(str[i]) {
		lang += str[i:i+1]
		i++
	}
	return lang
}

func getUnquotedPart(str string) (*string, string) {
	i := 0
	initStr := str
	out := ""
	start := 0
	for i < len(str) && !isWhitespace(str[i]) {
		if str[i] == '"' {
			part, remainder := getQuotedPart(str[i+1:])
			if part == nil {
				return part, initStr
			}
			out += str[start:i]
			str = remainder
			i = 0
			start = 0
			out += *part
		}
		i += 1
	}
	out += str[start:i]
	return &out, str[i:]
}

func ReadNQuadsFromReader(c chan *Triple, reader io.Reader) {
	bf := bufio.NewReader(reader)

	nTriples := 0
	line := ""
	for {
		l, pre, err := bf.ReadLine()
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(fmt.Errorf("Something bad happened while reading file: %v", err.Error()))
		}
		line += string(l)
		if pre {
			continue
		}
		triple := Parse(line)
		line = ""
		if triple != nil {
			nTriples++
			c <- triple
		}
	}

	close(c)
}
<|endoftext|>


<commit_before>package file

import (
	"github.com/Shopify/go-lua"
	"github.com/fsouza/go-dockerclient"
)

func (wbs wrapBuilderState) withConfig(l *lua.State) int {
	wbs.baseConf = parseImageConfigFromLuaTable(l)
	return wrapTable(l, &wbs)
}

func parseImageConfigFromLuaTable(l *lua.State) docker.Config {
	lua.CheckType(l, -1, lua.TypeTable)

	conf := docker.Config{}

	l.PushNil()
	for l.Next(-2) {
		switch lua.CheckString(l, -2) {
		case "Hostname":
			conf.Hostname = lua.CheckString(l, -1)
		case "Domainname":
			conf.Domainname = lua.CheckString(l, -1)
		case "User":
			conf.User = lua.CheckString(l, -1)
		case "CPUSet":
			conf.CPUSet = lua.CheckString(l, -1)
		case "StopSignal":
			conf.StopSignal = lua.CheckString(l, -1)
		case "Image":
			conf.Image = lua.CheckString(l, -1)
		case "VolumeDriver":
			conf.VolumeDriver = lua.CheckString(l, -1)
		case "VolumesFrom":
			conf.VolumesFrom = lua.CheckString(l, -1)
		case "WorkingDir":
			conf.WorkingDir = lua.CheckString(l, -1)
		case "MacAddress":
			conf.MacAddress = lua.CheckString(l, -1)

		case "Memory":
			conf.Memory = int64(lua.CheckInteger(l, -1))
		case "MemorySwap":
			conf.MemorySwap = int64(lua.CheckInteger(l, -1))
		case "MemoryReservation":
			conf.MemoryReservation = int64(lua.CheckInteger(l, -1))
		case "KernelMemory":
			conf.KernelMemory = int64(lua.CheckInteger(l, -1))
		case "CPUShares":
			conf.CPUShares = int64(lua.CheckInteger(l, -1))

		case "AttachStdin":
			conf.AttachStdin = checkBoolean(l, -1)
		case "AttachStdout":
			conf.AttachStdout = checkBoolean(l, -1)
		case "AttachStderr":
			conf.AttachStderr = checkBoolean(l, -1)
		case "Tty":
			conf.Tty = checkBoolean(l, -1)
		case "OpenStdin":
			conf.OpenStdin = checkBoolean(l, -1)
		case "StdinOnce":
			conf.StdinOnce = checkBoolean(l, -1)
		case "NetworkDisabled":
			conf.NetworkDisabled = checkBoolean(l, -1)

		case "PortSpecs":
			conf.PortSpecs = checkStringArray(l, -1)
		case "Env":
			conf.Env = checkStringArray(l, -1)
		case "Cmd":
			conf.Cmd = checkStringArray(l, -1)
		case "DNS":
			conf.DNS = checkStringArray(l, -1)
		case "Entrypoint":
			conf.Entrypoint = checkStringArray(l, -1)
		case "SecurityOpts":
			conf.SecurityOpts = checkStringArray(l, -1)
		case "OnBuild":
			conf.OnBuild = checkStringArray(l, -1)
		case "Labels":
			conf.Labels = checkStringMap(l, -1)
		case "ExposedPorts":
			conf.ExposedPorts = parseExposedPorts(l, -1)
		}
		l.Pop(1)
	}

	return conf
}

/*
	Volumes           map[string]struct{}
	Mounts            []Mount
*/

func checkBoolean(l *lua.State, index int) bool {
	lua.CheckType(l, index, lua.TypeBoolean)
	return l.ToBoolean(index)
}

func checkStringArray(l *lua.State, index int) []string {
	lua.CheckType(l, index, lua.TypeTable)

	items := make([]string, 0)

	l.PushNil()
	for l.Next(-2) {
		items = append(items, lua.CheckString(l, -1))
		l.Pop(1)
	}

	return items
}

func checkStringMap(l *lua.State, index int) map[string]string {
	lua.CheckType(l, index, lua.TypeTable)
	items := make(map[string]string)

	l.PushNil()
	for l.Next(-2) {
		key := lua.CheckString(l, -2)
		val := lua.CheckString(l, -1)
		items[key] = val
		l.Pop(1)
	}

	return items
}

type emptyStruct struct {
}

func parseExposedPorts(l *lua.State, index int) map[docker.Port]struct{} {
	items := map[docker.Port]struct{}{}

	marker := emptyStruct{}
	for _, el := range checkStringArray(l, index) {
		items[docker.Port(el)] = marker
	}

	return items
}
<commit_msg>Improve options parser: case insensitive<commit_after>package file

import (
	"github.com/Shopify/go-lua"
	"github.com/fsouza/go-dockerclient"
	"strings"
)

func (wbs wrapBuilderState) withConfig(l *lua.State) int {
	wbs.baseConf = parseImageConfigFromLuaTable(l)
	return wrapTable(l, &wbs)
}

func parseImageConfigFromLuaTable(l *lua.State) docker.Config {
	lua.CheckType(l, -1, lua.TypeTable)

	conf := docker.Config{}

	l.PushNil()
	for l.Next(-2) {
		switch strings.ToLower(lua.CheckString(l, -2)) {
		case "hostname":
			conf.Hostname = lua.CheckString(l, -1)
		case "domainname":
			conf.Domainname = lua.CheckString(l, -1)
		case "user":
			conf.User = lua.CheckString(l, -1)
		case "cpusetet":
			conf.CPUSet = lua.CheckString(l, -1)
		case "stopsignal":
			conf.StopSignal = lua.CheckString(l, -1)
		case "image":
			conf.Image = lua.CheckString(l, -1)
		case "volumedriver":
			conf.VolumeDriver = lua.CheckString(l, -1)
		case "volumesfrom":
			conf.VolumesFrom = lua.CheckString(l, -1)
		case "workingdir":
			conf.WorkingDir = lua.CheckString(l, -1)
		case "macaddress":
			conf.MacAddress = lua.CheckString(l, -1)

		case "memory":
			conf.Memory = int64(lua.CheckInteger(l, -1))
		case "memoryswap":
			conf.MemorySwap = int64(lua.CheckInteger(l, -1))
		case "memoryreservation":
			conf.MemoryReservation = int64(lua.CheckInteger(l, -1))
		case "kernelmemory":
			conf.KernelMemory = int64(lua.CheckInteger(l, -1))
		case "cpushares":
			conf.CPUShares = int64(lua.CheckInteger(l, -1))

		case "attachatdin":
			conf.AttachStdin = checkBoolean(l, -1)
		case "attachatdout":
			conf.AttachStdout = checkBoolean(l, -1)
		case "attachatderr":
			conf.AttachStderr = checkBoolean(l, -1)
		case "tty":
			conf.Tty = checkBoolean(l, -1)
		case "openstdin":
			conf.OpenStdin = checkBoolean(l, -1)
		case "stdinonce":
			conf.StdinOnce = checkBoolean(l, -1)
		case "networkdisabled":
			conf.NetworkDisabled = checkBoolean(l, -1)

		case "portspecs":
			conf.PortSpecs = checkStringArray(l, -1)
		case "env":
			conf.Env = checkStringArray(l, -1)
		case "cmd":
			conf.Cmd = checkStringArray(l, -1)
		case "dns":
			conf.DNS = checkStringArray(l, -1)
		case "entrypoint":
			conf.Entrypoint = checkStringArray(l, -1)
		case "securityopts":
			conf.SecurityOpts = checkStringArray(l, -1)
		case "onbuild":
			conf.OnBuild = checkStringArray(l, -1)
		case "labels":
			conf.Labels = checkStringMap(l, -1)
		case "exposedports", "ports", "expose":
			conf.ExposedPorts = parseExposedPorts(l, -1)
		}
		l.Pop(1)
	}

	return conf
}

/*
	Volumes           map[string]struct{}
	Mounts            []Mount
*/

func checkBoolean(l *lua.State, index int) bool {
	lua.CheckType(l, index, lua.TypeBoolean)
	return l.ToBoolean(index)
}

func checkStringArray(l *lua.State, index int) []string {
	lua.CheckType(l, index, lua.TypeTable)

	items := make([]string, 0)

	l.PushNil()
	for l.Next(-2) {
		items = append(items, lua.CheckString(l, -1))
		l.Pop(1)
	}

	return items
}

func checkStringMap(l *lua.State, index int) map[string]string {
	lua.CheckType(l, index, lua.TypeTable)
	items := make(map[string]string)

	l.PushNil()
	for l.Next(-2) {
		key := lua.CheckString(l, -2)
		val := lua.CheckString(l, -1)
		items[key] = val
		l.Pop(1)
	}

	return items
}

type emptyStruct struct {
}

func parseExposedPorts(l *lua.State, index int) map[docker.Port]struct{} {
	items := map[docker.Port]struct{}{}

	marker := emptyStruct{}
	for _, el := range checkStringArray(l, index) {
		items[docker.Port(el)] = marker
	}

	return items
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"runtime"
)

func versionsSubmajorGen(major, submajor, minor int) []string {
	var versions []string

	for i := 0; i <= minor; i++ {
		v := fmt.Sprintf("%d.%d.%d", major, submajor, i)
		versions = append(versions, v)
	}
	return versions
}

func versionsGen() []string {
	var versions []string

	versionsMinor0 := []int{45, 6, 61, 14, 38, 39, 69, 55, 7}   // 0.x.x
	versionsMinor1 := []int{15, 19, 9, 16, 7, 13, 3, 12, 1, 12} // 1.x.x

	// 0.1.0 ~ 0.9.7
	for i := 0; i < 9; i++ {
		versions = append(versions, versionsSubmajorGen(0, i+1, versionsMinor0[i])...)
	}

	// 1.0.0 ~
	for i := 0; i < 10; i++ {
		versions = append(versions, versionsSubmajorGen(1, i, versionsMinor1[i])...)
	}

	return versions
}

func versionsGenOpenResty() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("openresty-%s", OPENRESTY_VERSION))

	return versions
}

func versionsGenTengine() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("tengine-%s", TENGINE_VERSION))

	return versions
}

func printNginxVersions() {
	versions := versionsGen()
	versions = append(versions, versionsGenOpenResty()...)
	versions = append(versions, versionsGenTengine()...)
	for _, v := range versions {
		fmt.Println(v)
	}
}

func printNginxBuildVersion() {
	fmt.Printf(`nginx-build %s
Compiler: %s %s
Copyright (C) 2014-2016 Tatsuhiko Kubo <cubicdaiya@gmail.com>
`,
		NGINX_BUILD_VERSION,
		runtime.Compiler,
		runtime.Version())

}

func versionCheck(version string) {
	if len(version) == 0 {
		log.Println("[warn]nginx version is not set.")
		log.Printf("[warn]nginx-build use %s.\n", NGINX_VERSION)
	}
}
<commit_msg>forgot to update versions.<commit_after>package main

import (
	"fmt"
	"log"
	"runtime"
)

func versionsSubmajorGen(major, submajor, minor int) []string {
	var versions []string

	for i := 0; i <= minor; i++ {
		v := fmt.Sprintf("%d.%d.%d", major, submajor, i)
		versions = append(versions, v)
	}
	return versions
}

func versionsGen() []string {
	var versions []string

	versionsMinor0 := []int{45, 6, 61, 14, 38, 39, 69, 55, 7}   // 0.x.x
	versionsMinor1 := []int{15, 19, 9, 16, 7, 13, 3, 12, 1, 14} // 1.x.x

	// 0.1.0 ~ 0.9.7
	for i := 0; i < 9; i++ {
		versions = append(versions, versionsSubmajorGen(0, i+1, versionsMinor0[i])...)
	}

	// 1.0.0 ~
	for i := 0; i < 10; i++ {
		versions = append(versions, versionsSubmajorGen(1, i, versionsMinor1[i])...)
	}

	return versions
}

func versionsGenOpenResty() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("openresty-%s", OPENRESTY_VERSION))

	return versions
}

func versionsGenTengine() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("tengine-%s", TENGINE_VERSION))

	return versions
}

func printNginxVersions() {
	versions := versionsGen()
	versions = append(versions, versionsGenOpenResty()...)
	versions = append(versions, versionsGenTengine()...)
	for _, v := range versions {
		fmt.Println(v)
	}
}

func printNginxBuildVersion() {
	fmt.Printf(`nginx-build %s
Compiler: %s %s
Copyright (C) 2014-2016 Tatsuhiko Kubo <cubicdaiya@gmail.com>
`,
		NGINX_BUILD_VERSION,
		runtime.Compiler,
		runtime.Version())

}

func versionCheck(version string) {
	if len(version) == 0 {
		log.Println("[warn]nginx version is not set.")
		log.Printf("[warn]nginx-build use %s.\n", NGINX_VERSION)
	}
}
<|endoftext|>


<commit_before>package main

// App version variables

// Version set in source code
const Version = "0.25.2"

// Build time filled by make on program build
var Build string

// Commit tag from git, filled in by the compiler.
var Commit string
<commit_msg>v0.25.3<commit_after>package main

// App version variables

// Version set in source code
const Version = "0.25.3"

// Build time filled by make on program build
var Build string

// Commit tag from git, filled in by the compiler.
var Commit string
<|endoftext|>


<commit_before>package gophercloud

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"

	"github.com/mitchellh/mapstructure"
	"github.com/racker/perigee"
)

var (
	// ErrPageNotAvailable is returned from a Pager when a next or previous page is requested, but does not exist.
	ErrPageNotAvailable = errors.New("The requested Collection page does not exist.")
)

// Page must be satisfied by the result type of any resource collection.
// It allows clients to interact with the resource uniformly, regardless of whether or not or how it's paginated.
type Page interface {

	// NextPageURL generates the URL for the page of data that follows this collection.
	// Return "" if no such page exists.
	NextPageURL() (string, error)
}

// Pager knows how to advance through a specific resource collection, one page at a time.
type Pager struct {
	initialURL string

	fetchNextPage func(string) (Page, error)
}

// NewPager constructs a manually-configured pager.
// Supply the URL for the first page and a function that requests a specific page given a URL.
func NewPager(initialURL string, fetchNextPage func(string) (Page, error)) Pager {
	return Pager{
		initialURL:    initialURL,
		fetchNextPage: fetchNextPage,
	}
}

// EachPage iterates over each page returned by a Pager, yielding one at a time to a handler function.
// Return "false" from the handler to prematurely stop iterating.
func (p Pager) EachPage(handler func(Page) (bool, error)) error {
	currentURL := p.initialURL
	for {
		currentPage, err := p.fetchNextPage(currentURL)
		if err != nil {
			return err
		}

		ok, err := handler(currentPage)
		if err != nil {
			return err
		}
		if !ok {
			return nil
		}

		currentURL, err = currentPage.NextPageURL()
		if err != nil {
			return err
		}
		if currentURL == "" {
			return nil
		}
	}
}

// LastHTTPResponse stores generic information derived from an HTTP response.
type LastHTTPResponse struct {
	http.Header
	Body map[string]interface{}
}

// RememberHTTPResponse parses an HTTP response as JSON and returns a LastHTTPResponse containing the results.
func RememberHTTPResponse(resp http.Response) (LastHTTPResponse, error) {
	var parsedBody map[string]interface{}

	defer resp.Body.Close()
	rawBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return LastHTTPResponse{}, err
	}
	err = json.Unmarshal(rawBody, &parsedBody)
	if err != nil {
		return LastHTTPResponse{}, err
	}

	return LastHTTPResponse{Header: resp.Header, Body: parsedBody}, err
}

func request(client *ServiceClient, url string) (http.Response, error) {
	resp, err := perigee.Request("GET", url, perigee.Options{
		MoreHeaders: client.Provider.AuthenticatedHeaders(),
		OkCodes:     []int{200},
	})
	if err != nil {
		return http.Response{}, err
	}
	return resp.HttpResponse, nil
}

// SinglePage is a page that contains all of the results from an operation.
type SinglePage LastHTTPResponse

// NextPageURL always returns "" to indicate that there are no more pages to return.
func (current SinglePage) NextPageURL() (string, error) {
	return "", nil
}

// NewSinglePager constructs a Pager that "iterates" over a single Page.
// Supply the URL to request.
func NewSinglePager(client *ServiceClient, onlyURL string) Pager {
	consumed := false
	single := func(_ string) (Page, error) {
		if !consumed {
			consumed = true
			resp, err := request(client, onlyURL)
			if err != nil {
				return SinglePage{}, err
			}

			cp, err := RememberHTTPResponse(resp)
			if err != nil {
				return SinglePage{}, err
			}
			return SinglePage(cp), nil
		}
		return SinglePage{}, ErrPageNotAvailable
	}

	return Pager{
		initialURL:    "",
		fetchNextPage: single,
	}
}

// LinkedPage is a page in a collection that provides navigational "Next" and "Previous" links within its result.
type LinkedPage LastHTTPResponse

// NextPageURL extracts the pagination structure from a JSON response and returns the "next" link, if one is present.
func (current LinkedPage) NextPageURL() (string, error) {
	type response struct {
		Links struct {
			Next *string `mapstructure:"next,omitempty"`
		} `mapstructure:"links"`
	}

	var r response
	err := mapstructure.Decode(current.Body, &r)
	if err != nil {
		return "", err
	}

	if r.Links.Next == nil {
		return "", nil
	}

	return *r.Links.Next, nil
}

// NewLinkedPager creates a Pager that uses a "links" element in the JSON response to locate the next page.
func NewLinkedPager(client *ServiceClient, initialURL string) Pager {
	fetchNextPage := func(url string) (Page, error) {
		resp, err := request(client, url)
		if err != nil {
			return nil, err
		}

		cp, err := RememberHTTPResponse(resp)
		if err != nil {
			return nil, err
		}

		return LinkedPage(cp), nil
	}

	return Pager{
		initialURL:    initialURL,
		fetchNextPage: fetchNextPage,
	}
}
<commit_msg>Shuffle around source organization.<commit_after>package gophercloud

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"

	"github.com/mitchellh/mapstructure"
	"github.com/racker/perigee"
)

var (
	// ErrPageNotAvailable is returned from a Pager when a next or previous page is requested, but does not exist.
	ErrPageNotAvailable = errors.New("The requested Collection page does not exist.")
)

// LastHTTPResponse stores generic information derived from an HTTP response.
type LastHTTPResponse struct {
	http.Header
	Body map[string]interface{}
}

// RememberHTTPResponse parses an HTTP response as JSON and returns a LastHTTPResponse containing the results.
// The main reason to do this instead of holding the response directly is that a response body can only be read once.
// Also, this centralizes the JSON decoding.
func RememberHTTPResponse(resp http.Response) (LastHTTPResponse, error) {
	var parsedBody map[string]interface{}

	defer resp.Body.Close()
	rawBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return LastHTTPResponse{}, err
	}
	err = json.Unmarshal(rawBody, &parsedBody)
	if err != nil {
		return LastHTTPResponse{}, err
	}

	return LastHTTPResponse{Header: resp.Header, Body: parsedBody}, err
}

// request performs a Perigee request and extracts the http.Response from the result.
func request(client *ServiceClient, url string) (http.Response, error) {
	resp, err := perigee.Request("GET", url, perigee.Options{
		MoreHeaders: client.Provider.AuthenticatedHeaders(),
		OkCodes:     []int{200},
	})
	if err != nil {
		return http.Response{}, err
	}
	return resp.HttpResponse, nil
}

// Page must be satisfied by the result type of any resource collection.
// It allows clients to interact with the resource uniformly, regardless of whether or not or how it's paginated.
type Page interface {

	// NextPageURL generates the URL for the page of data that follows this collection.
	// Return "" if no such page exists.
	NextPageURL() (string, error)
}

// SinglePage is a page that contains all of the results from an operation.
type SinglePage LastHTTPResponse

// NextPageURL always returns "" to indicate that there are no more pages to return.
func (current SinglePage) NextPageURL() (string, error) {
	return "", nil
}

// LinkedPage is a page in a collection that provides navigational "Next" and "Previous" links within its result.
type LinkedPage LastHTTPResponse

// NextPageURL extracts the pagination structure from a JSON response and returns the "next" link, if one is present.
func (current LinkedPage) NextPageURL() (string, error) {
	type response struct {
		Links struct {
			Next *string `mapstructure:"next,omitempty"`
		} `mapstructure:"links"`
	}

	var r response
	err := mapstructure.Decode(current.Body, &r)
	if err != nil {
		return "", err
	}

	if r.Links.Next == nil {
		return "", nil
	}

	return *r.Links.Next, nil
}

// Pager knows how to advance through a specific resource collection, one page at a time.
type Pager struct {
	initialURL string

	fetchNextPage func(string) (Page, error)
}

// NewPager constructs a manually-configured pager.
// Supply the URL for the first page and a function that requests a specific page given a URL.
func NewPager(initialURL string, fetchNextPage func(string) (Page, error)) Pager {
	return Pager{
		initialURL:    initialURL,
		fetchNextPage: fetchNextPage,
	}
}

// NewSinglePager constructs a Pager that "iterates" over a single Page.
// Supply the URL to request.
func NewSinglePager(client *ServiceClient, onlyURL string) Pager {
	consumed := false
	single := func(_ string) (Page, error) {
		if !consumed {
			consumed = true
			resp, err := request(client, onlyURL)
			if err != nil {
				return SinglePage{}, err
			}

			cp, err := RememberHTTPResponse(resp)
			if err != nil {
				return SinglePage{}, err
			}
			return SinglePage(cp), nil
		}
		return SinglePage{}, ErrPageNotAvailable
	}

	return Pager{
		initialURL:    "",
		fetchNextPage: single,
	}
}

// NewLinkedPager creates a Pager that uses a "links" element in the JSON response to locate the next page.
func NewLinkedPager(client *ServiceClient, initialURL string) Pager {
	fetchNextPage := func(url string) (Page, error) {
		resp, err := request(client, url)
		if err != nil {
			return nil, err
		}

		cp, err := RememberHTTPResponse(resp)
		if err != nil {
			return nil, err
		}

		return LinkedPage(cp), nil
	}

	return Pager{
		initialURL:    initialURL,
		fetchNextPage: fetchNextPage,
	}
}

// EachPage iterates over each page returned by a Pager, yielding one at a time to a handler function.
// Return "false" from the handler to prematurely stop iterating.
func (p Pager) EachPage(handler func(Page) (bool, error)) error {
	currentURL := p.initialURL
	for {
		currentPage, err := p.fetchNextPage(currentURL)
		if err != nil {
			return err
		}

		ok, err := handler(currentPage)
		if err != nil {
			return err
		}
		if !ok {
			return nil
		}

		currentURL, err = currentPage.NextPageURL()
		if err != nil {
			return err
		}
		if currentURL == "" {
			return nil
		}
	}
}
<|endoftext|>


<commit_before>package main
const VERSION = "0.14"
<commit_msg>Release version 0.12<commit_after>package main
const VERSION = "0.12"
<|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All Rights Reserved.
//
// 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 oauth2 contains Martini handlers to provide
// user login via an OAuth 2.0 backend.
package oauth2

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

	"code.google.com/p/goauth2/oauth"
	"github.com/codegangsta/martini"
	"github.com/martini-contrib/sessions"
)

const (
	codeRedirect = 302
	keyToken     = "oauth2_token"
	keyNextPage  = "next"
)

var (
	// Path to handle OAuth 2.0 logins.
	PathLogin = "/login"
	// Path to handle OAuth 2.0 logouts.
	PathLogout = "/logout"
	// Path to handle callback from OAuth 2.0 backend
	// to exchange credentials.
	PathCallback = "/oauth2callback"
	// Path to handle error cases.
	PathError = "/oauth2error"
)

// Represents OAuth2 backend options.
type Options struct {
	ClientId     string
	ClientSecret string
	RedirectURL  string
	Scopes       []string

	AuthUrl  string
	TokenUrl string
}

// Represents a container that contains
// user's OAuth 2.0 access and refresh tokens.
type Tokens interface {
	AccessToken() string
	RefreshToken() string
	Expiry() time.Time
}

type token struct {
	tk *oauth.Token
}

// Returns the access token.
func (t *token) AccessToken() string {
	return t.tk.AccessToken
}

// Returns the refresh token.
func (t *token) RefreshToken() string {
	return t.tk.RefreshToken
}

// Returns whether the access token is
// expired or not.
func (t *token) Expired() bool {
	return t.tk.Expired()
}

// Returns the expiry time of the user's
// access token.
func (t *token) Expiry() time.Time {
	return t.tk.Expiry
}

// Formats tokens into string.
func (t *token) String() string {
	return fmt.Sprintf("%v", t.tk)
}

// Returns a new Google OAuth 2.0 backend endpoint.
func Google(opts *Options) martini.Handler {
	opts.AuthUrl = "https://accounts.google.com/o/oauth2/auth"
	opts.TokenUrl = "https://accounts.google.com/o/oauth2/token"
	return OAuth2Provider(opts)
}

// Returns a new Github OAuth 2.0 backend endpoint.
func Github(opts *Options) martini.Handler {
	opts.AuthUrl = "https://github.com/login/oauth/authorize"
	opts.TokenUrl = "https://github.com/login/oauth/access_token"
	return OAuth2Provider(opts)
}

// Returns a generic OAuth 2.0 backend endpoint.
func OAuth2Provider(opts *Options) martini.Handler {
	config := &oauth.Config{
		ClientId:     opts.ClientId,
		ClientSecret: opts.ClientSecret,
		RedirectURL:  opts.RedirectURL,
		Scope:        strings.Join(opts.Scopes, " "),
		AuthURL:      opts.AuthUrl,
		TokenURL:     opts.TokenUrl,
	}

	transport := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}

	return func(s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			switch r.URL.Path {
			case PathLogin:
				login(transport, s, w, r)
			case PathLogout:
				logout(transport, s, w, r)
			case PathCallback:
				handleOAuth2Callback(transport, s, w, r)
			}
		}
		// Inject tokens.
		c.MapTo(unmarshallToken(s), (*Tokens)(nil))
	}
}

func login(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := r.URL.Query().Get(keyNextPage)
	if s.Get(keyToken) == nil {
		// User is not logged in.
		http.Redirect(w, r, t.Config.AuthCodeURL(next), codeRedirect)
		return
	}
	// No need to login, redirect to the next page.
	http.Redirect(w, r, next, codeRedirect)
}

func logout(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := r.URL.Query().Get(keyNextPage)
	s.Delete(keyToken)
	http.Redirect(w, r, next, codeRedirect)
}

func handleOAuth2Callback(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := r.URL.Query().Get("state")
	code := r.URL.Query().Get("code")
	tk, err := t.Exchange(code)
	if err != nil {
		// Pass the error message, or allow dev to provide its own
		// error handler.
		http.Redirect(w, r, PathError, codeRedirect)
		return
	}
	// Store the credentials in the session.
	val, _ := json.Marshal(tk)
	s.Set(keyToken, val)
	http.Redirect(w, r, next, codeRedirect)
}

func unmarshallToken(s sessions.Session) (t *token) {
	if s.Get(keyToken) == nil {
		return
	}
	data := s.Get(keyToken).([]byte)
	var tk oauth.Token
	json.Unmarshal(data, &tk)
	return &token{tk: &tk}
}
<commit_msg>Adding Facebook endpoint and a few renames.<commit_after>// Copyright 2014 Google Inc. All Rights Reserved.
//
// 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 oauth2 contains Martini handlers to provide
// user login via an OAuth 2.0 backend.
package oauth2

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

	"code.google.com/p/goauth2/oauth"
	"github.com/codegangsta/martini"
	"github.com/martini-contrib/sessions"
)

const (
	codeRedirect = 302
	keyToken     = "oauth2_token"
	keyNextPage  = "next"
)

var (
	// Path to handle OAuth 2.0 logins.
	PathLogin = "/login"
	// Path to handle OAuth 2.0 logouts.
	PathLogout = "/logout"
	// Path to handle callback from OAuth 2.0 backend
	// to exchange credentials.
	PathCallback = "/oauth2callback"
	// Path to handle error cases.
	PathError = "/oauth2error"
)

// Represents OAuth2 backend options.
type Options struct {
	ClientId     string
	ClientSecret string
	RedirectURL  string
	Scopes       []string

	AuthUrl  string
	TokenUrl string
}

// Represents a container that contains
// user's OAuth 2.0 access and refresh tokens.
type Tokens interface {
	AccessToken() string
	RefreshToken() string
	Expiry() time.Time
}

type token struct {
	tk *oauth.Token
}

// Returns the access token.
func (t *token) AccessToken() string {
	return t.tk.AccessToken
}

// Returns the refresh token.
func (t *token) RefreshToken() string {
	return t.tk.RefreshToken
}

// Returns whether the access token is
// expired or not.
func (t *token) Expired() bool {
	return t.tk.Expired()
}

// Returns the expiry time of the user's
// access token.
func (t *token) Expiry() time.Time {
	return t.tk.Expiry
}

// Formats tokens into string.
func (t *token) String() string {
	return fmt.Sprintf("%v", t.tk)
}

// Returns a new Google OAuth 2.0 backend endpoint.
func Google(opts *Options) martini.Handler {
	opts.AuthUrl = "https://accounts.google.com/o/oauth2/auth"
	opts.TokenUrl = "https://accounts.google.com/o/oauth2/token"
	return NewOAuth2Provider(opts)
}

// Returns a new Github OAuth 2.0 backend endpoint.
func Github(opts *Options) martini.Handler {
	opts.AuthUrl = "https://github.com/login/oauth/authorize"
	opts.TokenUrl = "https://github.com/login/oauth/access_token"
	return NewOAuth2Provider(opts)
}

func Facebook(opts *Options) martini.Handler {
	opts.AuthUrl = "https://www.facebook.com/dialog/oauth"
	opts.TokenUrl = "https://graph.facebook.com/oauth/access_token"
	return NewOAuth2Provider(opts)
}

// Returns a generic OAuth 2.0 backend endpoint.
func NewOAuth2Provider(opts *Options) martini.Handler {
	config := &oauth.Config{
		ClientId:     opts.ClientId,
		ClientSecret: opts.ClientSecret,
		RedirectURL:  opts.RedirectURL,
		Scope:        strings.Join(opts.Scopes, " "),
		AuthURL:      opts.AuthUrl,
		TokenURL:     opts.TokenUrl,
	}

	transport := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}

	return func(s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			switch r.URL.Path {
			case PathLogin:
				login(transport, s, w, r)
			case PathLogout:
				logout(transport, s, w, r)
			case PathCallback:
				handleOAuth2Callback(transport, s, w, r)
			}
		}
		// Inject tokens.
		c.MapTo(unmarshallToken(s), (*Tokens)(nil))
	}
}

func login(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := r.URL.Query().Get(keyNextPage)
	if s.Get(keyToken) == nil {
		// User is not logged in.
		http.Redirect(w, r, t.Config.AuthCodeURL(next), codeRedirect)
		return
	}
	// No need to login, redirect to the next page.
	http.Redirect(w, r, next, codeRedirect)
}

func logout(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := r.URL.Query().Get(keyNextPage)
	s.Delete(keyToken)
	http.Redirect(w, r, next, codeRedirect)
}

func handleOAuth2Callback(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
	next := r.URL.Query().Get("state")
	code := r.URL.Query().Get("code")
	tk, err := t.Exchange(code)
	if err != nil {
		// Pass the error message, or allow dev to provide its own
		// error handler.
		http.Redirect(w, r, PathError, codeRedirect)
		return
	}
	// Store the credentials in the session.
	val, _ := json.Marshal(tk)
	s.Set(keyToken, val)
	http.Redirect(w, r, next, codeRedirect)
}

func unmarshallToken(s sessions.Session) (t *token) {
	if s.Get(keyToken) == nil {
		return
	}
	data := s.Get(keyToken).([]byte)
	var tk oauth.Token
	json.Unmarshal(data, &tk)
	return &token{tk: &tk}
}
<|endoftext|>


<commit_before>package gobot

const version = "0.9.0"

// Version returns the current Gobot version
func Version() string {
	return version
}
<commit_msg>Update version to 0.11<commit_after>package gobot

const version = "0.11.0"

// Version returns the current Gobot version
func Version() string {
	return version
}
<|endoftext|>


<commit_before>/*
  Go only has one way of looping through things: for.
  There are three different ways of writing for, though.
*/

package main
import "fmt"
func main() {
  // The first is the basic conditional
  i := 1
  for i <= 3 {
    fmt.Println(i)
    i = i + 1
  }

  // The other is the classic initial; condition; increment
  for j := 1; j <= 3; j++ {
    fmt.Println(j)
  }

  // The last is an infinite loop
  for {
    fmt.Println("again!")
    break
  }
}
<commit_msg>Add some logic<commit_after>/*
  Go only has one way of looping through things: for.
  There are three different ways of writing for, though.
*/

package main
import "fmt"
func main() {
  // The first is the basic conditional
  i := 1
  for i <= 3 {
    fmt.Println(i)
    i = i + 1
  }

  // The other is the classic initial; condition; increment
  for j := 1; j <= 3; j++ {
    fmt.Println(j)
  }

  // The last is an infinite loop
  for {
    fmt.Println("again!")
    break
  }

  /*
    If/else if/else conditionals are similar to Javascript in Go.
    But like for loops, they don't require parenthesis.
  */

  if 7 % 2 == 0 {
    fmt.Println("7 is even")
  } else {
    fmt.Println("7 is odd")
  }

  // We can also declare variables before/in a conditional:
  if num := 9; num < 0 {
    fmt.Println(num, " is negative")
  } else if num < 10 {
    fmt.Println(num, " has 1 digit")
  } else {
    fmt.Println(num, " has multiple digits")
  }
}
<|endoftext|>