<commit_before>package resource

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

	"github.com/google/go-github/github"
)

type OutCommand struct {
	github GitHub
	writer io.Writer
}

func NewOutCommand(github GitHub, writer io.Writer) *OutCommand {
	return &OutCommand{
		github: github,
		writer: writer,
	}
}

func (c *OutCommand) Run(sourceDir string, request OutRequest) (OutResponse, error) {
	params := request.Params

	name, err := c.fileContents(filepath.Join(sourceDir, request.Params.NamePath))
	if err != nil {
		return OutResponse{}, err
	}

	tag, err := c.fileContents(filepath.Join(sourceDir, request.Params.TagPath))
	if err != nil {
		return OutResponse{}, err
	}

	tag = request.Params.TagPrefix + tag

	var body string
	bodySpecified := false
	if request.Params.BodyPath != "" {
		bodySpecified = true

		body, err = c.fileContents(filepath.Join(sourceDir, request.Params.BodyPath))
		if err != nil {
			return OutResponse{}, err
		}
	}

	targetCommitish := ""
	if request.Params.CommitishPath != "" {
		targetCommitish, err = c.fileContents(filepath.Join(sourceDir, request.Params.CommitishPath))
		if err != nil {
			return OutResponse{}, err
		}
	}

	draft := request.Source.Drafts

	release := &github.RepositoryRelease{
		Name:            github.String(name),
		TagName:         github.String(tag),
		Body:            github.String(body),
		Draft:           github.Bool(draft),
		TargetCommitish: github.String(targetCommitish),
	}

	existingReleases, err := c.github.ListReleases()
	if err != nil {
		return OutResponse{}, err
	}

	var existingRelease *github.RepositoryRelease
	for _, e := range existingReleases {
		if e.TagName != nil && *e.TagName == tag {
			existingRelease = e
			break
		}
	}

	if existingRelease != nil {
		releaseAssets, err := c.github.ListReleaseAssets(*existingRelease)
		if err != nil {
			return OutResponse{}, err
		}

		existingRelease.Name = github.String(name)
		existingRelease.TargetCommitish = github.String(targetCommitish)
		existingRelease.Draft = github.Bool(draft)

		if bodySpecified {
			existingRelease.Body = github.String(body)
		} else {
			existingRelease.Body = nil
		}

		for _, asset := range releaseAssets {
			fmt.Fprintf(c.writer, "clearing existing asset: %s\n", *asset.Name)

			err := c.github.DeleteReleaseAsset(*asset)
			if err != nil {
				return OutResponse{}, err
			}
		}

		fmt.Fprintf(c.writer, "updating release %s\n", name)

		release, err = c.github.UpdateRelease(*existingRelease)
		if err != nil {
			return OutResponse{}, err
		}
	} else {
		fmt.Fprintf(c.writer, "creating release %s\n", name)
		release, err = c.github.CreateRelease(*release)
		if err != nil {
			return OutResponse{}, err
		}
	}

	for _, fileGlob := range params.Globs {
		matches, err := filepath.Glob(filepath.Join(sourceDir, fileGlob))
		if err != nil {
			return OutResponse{}, err
		}

		if len(matches) == 0 {
			return OutResponse{}, fmt.Errorf("could not find file that matches glob '%s'", fileGlob)
		}

		for _, filePath := range matches {
			err := c.upload(release, filePath)
			if err != nil {
				return OutResponse{}, err
			}
		}
	}

	return OutResponse{
		Version:  versionFromRelease(release),
		Metadata: metadataFromRelease(release),
	}, nil
}

func (c *OutCommand) fileContents(path string) (string, error) {
	contents, err := ioutil.ReadFile(path)
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(contents)), nil
}

func (c *OutCommand) upload(release *github.RepositoryRelease, filePath string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}

	defer file.Close()

	fmt.Fprintf(c.writer, "uploading %s\n", filePath)

	name := filepath.Base(filePath)

	var retryErr error
	for i := 0; i < 10; i++ {
		file, err := os.Open(filePath)
		if err != nil {
			return err
		}

		defer file.Close()

		retryErr = c.github.UploadReleaseAsset(*release, name, file)
		if retryErr == nil {
			break
		}

		assets, err := c.github.ListReleaseAssets(*release)
		if err != nil {
			return err
		}

		for _, asset := range assets {
			if asset.Name != nil && *asset.Name == name {
				err = c.github.DeleteReleaseAsset(*asset)
				if err != nil {
					return err
				}
				break
			}
		}
	}

	if retryErr != nil {
		return retryErr
	}

	return nil
}
<commit_msg>fix redundant file open/close<commit_after>package resource

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

	"github.com/google/go-github/github"
)

type OutCommand struct {
	github GitHub
	writer io.Writer
}

func NewOutCommand(github GitHub, writer io.Writer) *OutCommand {
	return &OutCommand{
		github: github,
		writer: writer,
	}
}

func (c *OutCommand) Run(sourceDir string, request OutRequest) (OutResponse, error) {
	params := request.Params

	name, err := c.fileContents(filepath.Join(sourceDir, request.Params.NamePath))
	if err != nil {
		return OutResponse{}, err
	}

	tag, err := c.fileContents(filepath.Join(sourceDir, request.Params.TagPath))
	if err != nil {
		return OutResponse{}, err
	}

	tag = request.Params.TagPrefix + tag

	var body string
	bodySpecified := false
	if request.Params.BodyPath != "" {
		bodySpecified = true

		body, err = c.fileContents(filepath.Join(sourceDir, request.Params.BodyPath))
		if err != nil {
			return OutResponse{}, err
		}
	}

	targetCommitish := ""
	if request.Params.CommitishPath != "" {
		targetCommitish, err = c.fileContents(filepath.Join(sourceDir, request.Params.CommitishPath))
		if err != nil {
			return OutResponse{}, err
		}
	}

	draft := request.Source.Drafts

	release := &github.RepositoryRelease{
		Name:            github.String(name),
		TagName:         github.String(tag),
		Body:            github.String(body),
		Draft:           github.Bool(draft),
		TargetCommitish: github.String(targetCommitish),
	}

	existingReleases, err := c.github.ListReleases()
	if err != nil {
		return OutResponse{}, err
	}

	var existingRelease *github.RepositoryRelease
	for _, e := range existingReleases {
		if e.TagName != nil && *e.TagName == tag {
			existingRelease = e
			break
		}
	}

	if existingRelease != nil {
		releaseAssets, err := c.github.ListReleaseAssets(*existingRelease)
		if err != nil {
			return OutResponse{}, err
		}

		existingRelease.Name = github.String(name)
		existingRelease.TargetCommitish = github.String(targetCommitish)
		existingRelease.Draft = github.Bool(draft)

		if bodySpecified {
			existingRelease.Body = github.String(body)
		} else {
			existingRelease.Body = nil
		}

		for _, asset := range releaseAssets {
			fmt.Fprintf(c.writer, "clearing existing asset: %s\n", *asset.Name)

			err := c.github.DeleteReleaseAsset(*asset)
			if err != nil {
				return OutResponse{}, err
			}
		}

		fmt.Fprintf(c.writer, "updating release %s\n", name)

		release, err = c.github.UpdateRelease(*existingRelease)
		if err != nil {
			return OutResponse{}, err
		}
	} else {
		fmt.Fprintf(c.writer, "creating release %s\n", name)
		release, err = c.github.CreateRelease(*release)
		if err != nil {
			return OutResponse{}, err
		}
	}

	for _, fileGlob := range params.Globs {
		matches, err := filepath.Glob(filepath.Join(sourceDir, fileGlob))
		if err != nil {
			return OutResponse{}, err
		}

		if len(matches) == 0 {
			return OutResponse{}, fmt.Errorf("could not find file that matches glob '%s'", fileGlob)
		}

		for _, filePath := range matches {
			err := c.upload(release, filePath)
			if err != nil {
				return OutResponse{}, err
			}
		}
	}

	return OutResponse{
		Version:  versionFromRelease(release),
		Metadata: metadataFromRelease(release),
	}, nil
}

func (c *OutCommand) fileContents(path string) (string, error) {
	contents, err := ioutil.ReadFile(path)
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(contents)), nil
}

func (c *OutCommand) upload(release *github.RepositoryRelease, filePath string) error {
	fmt.Fprintf(c.writer, "uploading %s\n", filePath)

	name := filepath.Base(filePath)

	var retryErr error
	for i := 0; i < 10; i++ {
		file, err := os.Open(filePath)
		if err != nil {
			return err
		}

		defer file.Close()

		retryErr = c.github.UploadReleaseAsset(*release, name, file)
		if retryErr == nil {
			break
		}

		assets, err := c.github.ListReleaseAssets(*release)
		if err != nil {
			return err
		}

		for _, asset := range assets {
			if asset.Name != nil && *asset.Name == name {
				err = c.github.DeleteReleaseAsset(*asset)
				if err != nil {
					return err
				}
				break
			}
		}
	}

	if retryErr != nil {
		return retryErr
	}

	return nil
}
<|endoftext|>


<commit_before>package margopher

import (
	"bytes"
	"strings"
)

type margopher struct {
	states map[[2]string][]string
}

// Margopher constructor
func NewMargopher() *margopher {
	return &margopher{states: make(map[[2]string][]string)}
}

// Generate margopher senetence based on a given length
func (m *margopher) Generate(sentenceLength int) string {

	var sentence bytes.Buffer

	// Initialize prefix with a random key
	prefix := m.getRandomPrefix([2]string{"", ""})
	sentence.WriteString(strings.Join(prefix[:], " ") + " ")

	for i := 1; i < sentenceLength; i++ {
		suffix := getRandomWord(m.states[prefix])
		sentence.WriteString(suffix + " ")

		// Break the loop if suffix ends in "." and senetenceLength is enough
		if isTerminalWord(suffix) && i > sentenceLength {
			break
		}

		prefix = [2]string{prefix[1], suffix}
	}

	return sentence.String()
}
<commit_msg>Remove snetenceLength from Generate() method<commit_after>package margopher

import (
	"bytes"
	"strings"
)

type margopher struct {
	states map[[2]string][]string
}

// Margopher constructor
func NewMargopher() *margopher {
	return &margopher{states: make(map[[2]string][]string)}
}

// Generate margopher senetence based on a given length
func (m *margopher) Generate() string {

	var sentence bytes.Buffer

	// Initialize prefix with a random key
	prefix := m.getRandomPrefix([2]string{"", ""})
	sentence.WriteString(strings.Join(prefix[:], " ") + " ")

	for {
		suffix := getRandomWord(m.states[prefix])
		sentence.WriteString(suffix + " ")

		// Break the loop if suffix ends in "." and senetenceLength is enough
		if isTerminalWord(suffix) {
			break
		}

		prefix = [2]string{prefix[1], suffix}
	}

	return sentence.String()
}
<|endoftext|>


<commit_before>package mc

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	p2p_crypto "github.com/libp2p/go-libp2p-crypto"
	multihash "github.com/multiformats/go-multihash"
	"log"
	"net/http"
	"os/exec"
	"regexp"
	"strings"
)

var (
	MalformedEntityId = errors.New("Malformed entity id")
	UnknownIdProvider = errors.New("Unknwon identity provider")
	EntityKeyNotFound = errors.New("Entity key not found")
)

type EntityId struct {
	KeyId string `json:"keyId"` // public key multihash
	Key   []byte `json:"key"`   // marshalled public key
}

func LookupEntityKey(entity string, keyId string) (p2p_crypto.PubKey, error) {
	ix := strings.Index(entity, ":")
	if ix < 0 {
		return nil, MalformedEntityId
	}

	prov := entity[:ix]
	user := entity[ix+1:]

	lookup, ok := idProviders[prov]
	if ok {
		return lookup(user, keyId)
	}

	return nil, UnknownIdProvider
}

type LookupKeyFunc func(user, keyId string) (p2p_crypto.PubKey, error)

var bsrx *regexp.Regexp

func init() {
	rx, err := regexp.Compile("^[a-zA-Z0-9.-]+$")
	if err != nil {
		log.Fatal(err)
	}
	bsrx = rx
}

func lookupBlockstack(user, keyId string) (p2p_crypto.PubKey, error) {
	if !bsrx.Match([]byte(user)) {
		return nil, MalformedEntityId
	}

	khash, err := multihash.FromB58String(keyId)
	if err != nil {
		return nil, err
	}

	out, err := exec.Command("blockstack", "lookup", user).Output()
	if err != nil {
		xerr, ok := err.(*exec.ExitError)
		if ok {
			return nil, fmt.Errorf("blockstack error: %s", string(xerr.Stderr))
		}
		return nil, err
	}

	var res map[string]interface{}
	err = json.Unmarshal(out, &res)
	if err != nil {
		return nil, err
	}

	prof, ok := res["profile"].(map[string]interface{})
	if !ok {
		return nil, EntityKeyNotFound
	}

	accts, ok := prof["account"].([]interface{})
	if !ok {
		return nil, EntityKeyNotFound
	}

	for _, acct := range accts {
		xacct, ok := acct.(map[string]interface{})
		if !ok {
			continue
		}

		svc, ok := xacct["service"].(string)
		if !ok {
			continue
		}

		if svc != "mediachain" {
			continue
		}

		key, ok := xacct["identifier"].(string)
		if !ok {
			break
		}

		return unmarshalEntityKey(key, khash)
	}

	return nil, EntityKeyNotFound
}

func lookupKeybase(user, keyId string) (p2p_crypto.PubKey, error) {
	if !bsrx.Match([]byte(user)) {
		return nil, MalformedEntityId
	}

	khash, err := multihash.FromB58String(keyId)
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("https://%s.keybase.pub/mediachain.json", user)

	res, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	switch {
	case res.StatusCode == 404:
		return nil, EntityKeyNotFound

	case res.StatusCode != 200:
		return nil, fmt.Errorf("keybase error: %d %s", res.StatusCode, res.Status)
	}

	var pub EntityId
	err = json.NewDecoder(res.Body).Decode(&pub)
	if err != nil {
		return nil, err
	}

	if pub.KeyId != keyId {
		return nil, EntityKeyNotFound
	}

	return unmarshalEntityKeyBytes(pub.Key, khash)
}

var idProviders = map[string]LookupKeyFunc{
	"blockstack": lookupBlockstack,
	"keybase":    lookupKeybase,
}

func unmarshalEntityKey(key string, khash multihash.Multihash) (p2p_crypto.PubKey, error) {
	data, err := base64.StdEncoding.DecodeString(key)
	if err != nil {
		return nil, err
	}

	return unmarshalEntityKeyBytes(data, khash)
}

func unmarshalEntityKeyBytes(key []byte, khash multihash.Multihash) (p2p_crypto.PubKey, error) {
	hash := Hash(key)
	if !bytes.Equal(hash, khash) {
		return nil, EntityKeyNotFound
	}

	return p2p_crypto.UnmarshalPublicKey(key)
}
<commit_msg>mc: use same hash type as argument in key verification<commit_after>package mc

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	p2p_crypto "github.com/libp2p/go-libp2p-crypto"
	multihash "github.com/multiformats/go-multihash"
	"log"
	"net/http"
	"os/exec"
	"regexp"
	"strings"
)

var (
	MalformedEntityId = errors.New("Malformed entity id")
	UnknownIdProvider = errors.New("Unknwon identity provider")
	EntityKeyNotFound = errors.New("Entity key not found")
)

type EntityId struct {
	KeyId string `json:"keyId"` // public key multihash
	Key   []byte `json:"key"`   // marshalled public key
}

func LookupEntityKey(entity string, keyId string) (p2p_crypto.PubKey, error) {
	ix := strings.Index(entity, ":")
	if ix < 0 {
		return nil, MalformedEntityId
	}

	prov := entity[:ix]
	user := entity[ix+1:]

	lookup, ok := idProviders[prov]
	if ok {
		return lookup(user, keyId)
	}

	return nil, UnknownIdProvider
}

type LookupKeyFunc func(user, keyId string) (p2p_crypto.PubKey, error)

var bsrx *regexp.Regexp

func init() {
	rx, err := regexp.Compile("^[a-zA-Z0-9.-]+$")
	if err != nil {
		log.Fatal(err)
	}
	bsrx = rx
}

func lookupBlockstack(user, keyId string) (p2p_crypto.PubKey, error) {
	if !bsrx.Match([]byte(user)) {
		return nil, MalformedEntityId
	}

	khash, err := multihash.FromB58String(keyId)
	if err != nil {
		return nil, err
	}

	out, err := exec.Command("blockstack", "lookup", user).Output()
	if err != nil {
		xerr, ok := err.(*exec.ExitError)
		if ok {
			return nil, fmt.Errorf("blockstack error: %s", string(xerr.Stderr))
		}
		return nil, err
	}

	var res map[string]interface{}
	err = json.Unmarshal(out, &res)
	if err != nil {
		return nil, err
	}

	prof, ok := res["profile"].(map[string]interface{})
	if !ok {
		return nil, EntityKeyNotFound
	}

	accts, ok := prof["account"].([]interface{})
	if !ok {
		return nil, EntityKeyNotFound
	}

	for _, acct := range accts {
		xacct, ok := acct.(map[string]interface{})
		if !ok {
			continue
		}

		svc, ok := xacct["service"].(string)
		if !ok {
			continue
		}

		if svc != "mediachain" {
			continue
		}

		key, ok := xacct["identifier"].(string)
		if !ok {
			break
		}

		return unmarshalEntityKey(key, khash)
	}

	return nil, EntityKeyNotFound
}

func lookupKeybase(user, keyId string) (p2p_crypto.PubKey, error) {
	if !bsrx.Match([]byte(user)) {
		return nil, MalformedEntityId
	}

	khash, err := multihash.FromB58String(keyId)
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("https://%s.keybase.pub/mediachain.json", user)

	res, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	switch {
	case res.StatusCode == 404:
		return nil, EntityKeyNotFound

	case res.StatusCode != 200:
		return nil, fmt.Errorf("keybase error: %d %s", res.StatusCode, res.Status)
	}

	var pub EntityId
	err = json.NewDecoder(res.Body).Decode(&pub)
	if err != nil {
		return nil, err
	}

	if pub.KeyId != keyId {
		return nil, EntityKeyNotFound
	}

	return unmarshalEntityKeyBytes(pub.Key, khash)
}

var idProviders = map[string]LookupKeyFunc{
	"blockstack": lookupBlockstack,
	"keybase":    lookupKeybase,
}

func unmarshalEntityKey(key string, khash multihash.Multihash) (p2p_crypto.PubKey, error) {
	data, err := base64.StdEncoding.DecodeString(key)
	if err != nil {
		return nil, err
	}

	return unmarshalEntityKeyBytes(data, khash)
}

func unmarshalEntityKeyBytes(key []byte, khash multihash.Multihash) (p2p_crypto.PubKey, error) {
	hash, err := multihash.Sum(key, int(khash[0]), -1)
	if err != nil {
		return nil, err
	}

	if !bytes.Equal(hash, khash) {
		return nil, EntityKeyNotFound
	}

	return p2p_crypto.UnmarshalPublicKey(key)
}
<|endoftext|>


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

package prototype

import pref "github.com/golang/protobuf/v2/reflect/protoreflect"

// X provides functionality internal to the protobuf module.
//
// WARNING: The compatibility agreement covers nothing except for functionality
// needed to keep existing generated messages operational. The Go authors
// are not responsible for breakages that occur due to unauthorized usages.
var X internal

type internal struct{}

// optionTypes contains typed nil-pointers to each of the options types.
// These are populated at init time by the descriptor package.
var optionTypes struct {
	File           pref.ProtoMessage
	Enum           pref.ProtoMessage
	EnumValue      pref.ProtoMessage
	Message        pref.ProtoMessage
	Field          pref.ProtoMessage
	Oneof          pref.ProtoMessage
	ExtensionRange pref.ProtoMessage
	Service        pref.ProtoMessage
	Method         pref.ProtoMessage
}

func (internal) RegisterFileOptions(m pref.ProtoMessage)           { optionTypes.File = m }
func (internal) RegisterEnumOptions(m pref.ProtoMessage)           { optionTypes.Enum = m }
func (internal) RegisterEnumValueOptions(m pref.ProtoMessage)      { optionTypes.EnumValue = m }
func (internal) RegisterMessageOptions(m pref.ProtoMessage)        { optionTypes.Message = m }
func (internal) RegisterFieldOptions(m pref.ProtoMessage)          { optionTypes.Field = m }
func (internal) RegisterOneofOptions(m pref.ProtoMessage)          { optionTypes.Oneof = m }
func (internal) RegisterExtensionRangeOptions(m pref.ProtoMessage) { optionTypes.ExtensionRange = m }
func (internal) RegisterServiceOptions(m pref.ProtoMessage)        { optionTypes.Service = m }
func (internal) RegisterMethodOptions(m pref.ProtoMessage)         { optionTypes.Method = m }
<commit_msg>reflect/prototype: change registered option types to interface{}<commit_after>// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package prototype

// X provides functionality internal to the protobuf module.
//
// WARNING: The compatibility agreement covers nothing except for functionality
// needed to keep existing generated messages operational. The Go authors
// are not responsible for breakages that occur due to unauthorized usages.
var X internal

type internal struct{}

// optionTypes contains typed nil-pointers to each of the options types.
// These are populated at init time by the descriptor package.
var optionTypes struct {
	File           interface{}
	Enum           interface{}
	EnumValue      interface{}
	Message        interface{}
	Field          interface{}
	Oneof          interface{}
	ExtensionRange interface{}
	Service        interface{}
	Method         interface{}
}

func (internal) RegisterFileOptions(m interface{})           { optionTypes.File = m }
func (internal) RegisterEnumOptions(m interface{})           { optionTypes.Enum = m }
func (internal) RegisterEnumValueOptions(m interface{})      { optionTypes.EnumValue = m }
func (internal) RegisterMessageOptions(m interface{})        { optionTypes.Message = m }
func (internal) RegisterFieldOptions(m interface{})          { optionTypes.Field = m }
func (internal) RegisterOneofOptions(m interface{})          { optionTypes.Oneof = m }
func (internal) RegisterExtensionRangeOptions(m interface{}) { optionTypes.ExtensionRange = m }
func (internal) RegisterServiceOptions(m interface{})        { optionTypes.Service = m }
func (internal) RegisterMethodOptions(m interface{})         { optionTypes.Method = m }
<|endoftext|>


<commit_before>package checkpostgresql

import (
	"fmt"
	"os"
	"strings"

	// PostgreSQL Driver
	_ "github.com/lib/pq"
	"github.com/mackerelio/checkers"
)

var commands = map[string](func([]string) *checkers.Checker){
	"connection": checkConnection,
}

type postgresqlSetting struct {
	Host     string `short:"H" long:"host" default:"localhost" description:"Hostname"`
	Port     string `short:"p" long:"port" default:"5432" description:"Port"`
	User     string `short:"u" long:"user" default:"postgres" description:"Username"`
	Password string `short:"P" long:"password" default:"" description:"Password"`
	Database string `short:"d" long:"dbname" description:"DBname"`
	SSLmode  string `short:"s" long:"sslmode" default:"disable" description:"SSLmode"`
	Timeout  int    `short:"t" long:"timeout" default:"5" description:"Maximum wait for connection, in seconds."`
}

func (p postgresqlSetting) getDriverAndDataSourceName() (string, string) {
	dataSourceName := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s connect_timeout=%d", p.User, p.Password, p.Host, p.Port, p.Database, p.SSLmode, p.Timeout)
	return "postgres", dataSourceName
}

func separateSub(argv []string) (string, []string) {
	if len(argv) == 0 || strings.HasPrefix(argv[0], "-") {
		return "", argv
	}
	return argv[0], argv[1:]
}

// Do the plugin
func Do() {
	subCmd, argv := separateSub(os.Args[1:])
	fn, ok := commands[subCmd]
	if !ok {
		fmt.Println(`Usage:
  check-postgresql [subcommand] [OPTIONS]

SubCommands:`)
		for k := range commands {
			fmt.Printf("  %s\n", k)
		}
		os.Exit(1)
	}
	ckr := fn(argv)
	ckr.Name = fmt.Sprintf("PostgreSQL %s", strings.Title(subCmd))
	ckr.Exit()
}
<commit_msg>Add default<commit_after>package checkpostgresql

import (
	"fmt"
	"os"
	"strings"

	// PostgreSQL Driver
	_ "github.com/lib/pq"
	"github.com/mackerelio/checkers"
)

var commands = map[string](func([]string) *checkers.Checker){
	"connection": checkConnection,
}

type postgresqlSetting struct {
	Host     string `short:"H" long:"host" default:"localhost" description:"Hostname"`
	Port     string `short:"p" long:"port" default:"5432" description:"Port"`
	User     string `short:"u" long:"user" default:"postgres" description:"Username"`
	Password string `short:"P" long:"password" default:"" description:"Password"`
	Database string `short:"d" long:"dbname" default:"postgres" description:"DBname"`
	SSLmode  string `short:"s" long:"sslmode" default:"disable" description:"SSLmode"`
	Timeout  int    `short:"t" long:"timeout" default:"5" description:"Maximum wait for connection, in seconds."`
}

func (p postgresqlSetting) getDriverAndDataSourceName() (string, string) {
	dataSourceName := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s connect_timeout=%d", p.User, p.Password, p.Host, p.Port, p.Database, p.SSLmode, p.Timeout)
	return "postgres", dataSourceName
}

func separateSub(argv []string) (string, []string) {
	if len(argv) == 0 || strings.HasPrefix(argv[0], "-") {
		return "", argv
	}
	return argv[0], argv[1:]
}

// Do the plugin
func Do() {
	subCmd, argv := separateSub(os.Args[1:])
	fn, ok := commands[subCmd]
	if !ok {
		fmt.Println(`Usage:
  check-postgresql [subcommand] [OPTIONS]

SubCommands:`)
		for k := range commands {
			fmt.Printf("  %s\n", k)
		}
		os.Exit(1)
	}
	ckr := fn(argv)
	ckr.Name = fmt.Sprintf("PostgreSQL %s", strings.Title(subCmd))
	ckr.Exit()
}
<|endoftext|>


<commit_before>// +build integration

package factual_test

import (
  "os"
  "encoding/json"
  "testing"
  "net/url"

  "github.com/ainsleyc/factual"
  "github.com/bitly/go-simplejson"
)

const testValidPath = "/t/place-categories"
var testEmptyParams = url.Values{}

type testConfig struct {
  Key string
  Secret string
}

func getTestConfig() (conf testConfig, err error) {
  config := testConfig{}
  file, err := os.Open("conf.json")
  if err != nil {
    return config, err
  }

  decoder := json.NewDecoder(file)
  err = decoder.Decode(&config)
  if err != nil {
    return config, err
  }

  return config, nil
}

func testGet(t *testing.T, path string, params url.Values) {
  config, _:= getTestConfig()
  client := factual.NewClient(config.Key, config.Secret)

  resp, err := client.Get(path, params)
  if err != nil {
    t.Error("Get returned error for valid url, Factual API may be unavailable")
  }

  json, _ := simplejson.NewJson(resp)
  data := json.Get("response").Get("data")
  if len(data.MustArray()) <= 0 {
    t.Error("Valid Get query returned no results")
  }
}

func TestGet_ConfigFile_ShouldExist(t *testing.T) {
  _, err := getTestConfig()
  if err != nil {
    switch err.(type) {
    default:
      t.Error("conf.json has an unknown error")
    case *os.PathError:
      t.Error("conf.json does not exist")
    case *json.SyntaxError:
      t.Error("conf.json is not a valid json")
    }
  }
}

func TestGet_ConfigFile_ShouldHaveRequiredFields(t *testing.T) {
  config, _:= getTestConfig()
  if config.Key == "" {
    t.Error("conf.json is missing Key")
  }
  if config.Secret == "" {
    t.Error("conf.json is missing Secret")
  }
}

func TestGet_InvalidCredentials_ShouldReturnError(t *testing.T) {
  client := factual.NewClient("blah", "blah")
  _, err := client.Get(testValidPath, testEmptyParams)
  if err == nil {
    t.Error("Did not return error for invalid credentials")
  }
}

func TestGet_ReadWithQuery_ShouldReturnResults(t *testing.T) {
  path := "/t/places-us"
  params := url.Values{}
  params.Set("q", "starbucks")

  testGet(t, path, params)
}

func TestGet_ReadWithSingleFilter_ShouldReturnResults(t *testing.T) {
  path := "/t/places-us"
  params := url.Values{}
  filters, _ := factual.NewFilter(
    "name",
    factual.Eq,
    "starbucks",
  ).MarshalJSON()
  params.Set("filters", string(filters))

  testGet(t, path, params)
}

<commit_msg>Added comments to examples<commit_after>// +build integration

package factual_test

import (
  "os"
  "encoding/json"
  "testing"
  "net/url"

  "github.com/ainsleyc/factual"
  "github.com/bitly/go-simplejson"
)

const testValidPath = "/t/place-categories"
var testEmptyParams = url.Values{}

type testConfig struct {
  Key string
  Secret string
}

func getTestConfig() (conf testConfig, err error) {
  config := testConfig{}
  file, err := os.Open("conf.json")
  if err != nil {
    return config, err
  }

  decoder := json.NewDecoder(file)
  err = decoder.Decode(&config)
  if err != nil {
    return config, err
  }

  return config, nil
}

func testGet(t *testing.T, path string, params url.Values) {
  config, _:= getTestConfig()
  client := factual.NewClient(config.Key, config.Secret)

  resp, err := client.Get(path, params)
  if err != nil {
    t.Error("Get returned error for valid url, Factual API may be unavailable")
  }

  json, _ := simplejson.NewJson(resp)
  data := json.Get("response").Get("data")
  if len(data.MustArray()) <= 0 {
    t.Error("Valid Get query returned no results")
  }
}

func TestGet_ConfigFile_ShouldExist(t *testing.T) {
  _, err := getTestConfig()
  if err != nil {
    switch err.(type) {
    default:
      t.Error("conf.json has an unknown error")
    case *os.PathError:
      t.Error("conf.json does not exist")
    case *json.SyntaxError:
      t.Error("conf.json is not a valid json")
    }
  }
}

func TestGet_ConfigFile_ShouldHaveRequiredFields(t *testing.T) {
  config, _:= getTestConfig()
  if config.Key == "" {
    t.Error("conf.json is missing Key")
  }
  if config.Secret == "" {
    t.Error("conf.json is missing Secret")
  }
}

func TestGet_InvalidCredentials_ShouldReturnError(t *testing.T) {
  client := factual.NewClient("blah", "blah")
  _, err := client.Get(testValidPath, testEmptyParams)
  if err == nil {
    t.Error("Did not return error for invalid credentials")
  }
}

// /t/places-us?q=starbucks
func TestGet_ReadWithQuery_ShouldReturnResults(t *testing.T) {
  path := "/t/places-us"
  params := url.Values{}
  params.Set("q", "starbucks")

  testGet(t, path, params)
}

// /t/places-us?filters={"name":{"$eq":"starbucks"}}
func TestGet_ReadWithSingleFilter_ShouldReturnResults(t *testing.T) {
  path := "/t/places-us"
  params := url.Values{}
  filters, _ := factual.NewFilter(
    "name",
    factual.Eq,
    "starbucks",
  ).MarshalJSON()
  params.Set("filters", string(filters))

  testGet(t, path, params)
}

<|endoftext|>


<commit_before>package niso

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	"golang.org/x/oauth2"
)

const (
	clientID     = "test_client"
	clientSecret = "notsecure"
	redirectURI  = "http://localhost/callback"
	testAuthCode = "9999"
)

type NisoIntegrationTestSuite struct {
	suite.Suite
	testAuthorizeURL string
	testAccessURL    string
	oauthConfig      *oauth2.Config
}

func (s *NisoIntegrationTestSuite) SetupSuite() {
	config := NewServerConfig()
	config.AllowedAccessTypes = AllowedAccessTypes{AUTHORIZATION_CODE}
	server := newTestServer(config)
	server.Storage = newIntegrationTestStorage()

	authServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.TODO()

		if ar, err := server.GenerateAuthorizeRequest(ctx, r); err != nil {
			WriteErrorResponse(w, err)
		} else {
			ar.Authorized = true
			resp, err := server.FinishAuthorizeRequest(ctx, ar)
			if err != nil {
				WriteErrorResponse(w, err)
			} else {
				WriteJSONResponse(w, resp)
			}
		}
	}))
	s.testAuthorizeURL = authServer.URL

	accessServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.TODO()
		ar, err := server.GenerateAccessRequest(ctx, r)
		if err != nil {
			WriteErrorResponse(w, err)
			return
		}

		ar.Authorized = true
		resp, err := server.FinishAccessRequest(ctx, ar)
		if err != nil {
			WriteErrorResponse(w, err)
			return
		}

		WriteJSONResponse(w, resp)
	}))
	s.testAccessURL = accessServer.URL

	s.oauthConfig = newOAuthConfig(s.testAuthorizeURL, s.testAccessURL)
}

func (s *NisoIntegrationTestSuite) TestAuthCodeCallbackSuccess() {
	client := http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	authCodeURL := s.oauthConfig.AuthCodeURL("kappa")

	resp, err := client.Get(authCodeURL)
	require.NoError(s.T(), err)

	assert.Equal(s.T(), 302, resp.StatusCode)
	assert.Equal(s.T(), "http://localhost/callback?code=1&state=kappa", resp.Header["Location"][0])
}

func (s *NisoIntegrationTestSuite) TestAccessTokenExchangeSuccess() {
	tok, err := s.oauthConfig.Exchange(context.TODO(), testAuthCode)
	require.NoError(s.T(), err)
	assert.Equal(s.T(), "r1", tok.RefreshToken)
	assert.Equal(s.T(), "1", tok.AccessToken)
}

func (s *NisoIntegrationTestSuite) TestAccessTokenExchangeFail() {
	_, err := s.oauthConfig.Exchange(context.TODO(), "invalid")
	assert.Error(s.T(), err)
	assert.Contains(s.T(), err.Error(), "invalid_grant")
}

func TestNisoIntegrationTestSuite(t *testing.T) {
	suite.Run(t, new(NisoIntegrationTestSuite))
}

func newOAuthConfig(authURL string, tokenURL string) *oauth2.Config {
	return &oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURL:  redirectURI,
		Scopes:       []string{"scope1", "scope2"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  authURL,
			TokenURL: tokenURL,
		},
	}
}

func newIntegrationTestStorage() Storage {
	r := &TestingStorage{
		clients:   make(map[string]*ClientData),
		authorize: make(map[string]*AuthorizeData),
		access:    make(map[string]*AccessData),
		refresh:   make(map[string]*RefreshTokenData),
	}

	r.clients[clientID] = &ClientData{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURI:  redirectURI,
	}

	r.authorize[testAuthCode] = &AuthorizeData{
		ClientData:  r.clients[clientID],
		Code:        testAuthCode,
		ExpiresIn:   3600,
		CreatedAt:   time.Now(),
		RedirectURI: redirectURI,
	}

	return r
}
<commit_msg>Go back to early return style<commit_after>package niso

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	"golang.org/x/oauth2"
)

const (
	clientID     = "test_client"
	clientSecret = "notsecure"
	redirectURI  = "http://localhost/callback"
	testAuthCode = "9999"
)

type NisoIntegrationTestSuite struct {
	suite.Suite
	testAuthorizeURL string
	testAccessURL    string
	oauthConfig      *oauth2.Config
}

func (s *NisoIntegrationTestSuite) SetupSuite() {
	config := NewServerConfig()
	config.AllowedAccessTypes = AllowedAccessTypes{AUTHORIZATION_CODE}
	server := newTestServer(config)
	server.Storage = newIntegrationTestStorage()

	authServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.TODO()
		ar, err := server.GenerateAuthorizeRequest(ctx, r)
		if err != nil {
			WriteErrorResponse(w, err)
			return
		}

		ar.Authorized = true
		resp, err := server.FinishAuthorizeRequest(ctx, ar)
		if err != nil {
			WriteErrorResponse(w, err)
			return
		}

		WriteJSONResponse(w, resp)
	}))
	s.testAuthorizeURL = authServer.URL

	accessServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.TODO()
		ar, err := server.GenerateAccessRequest(ctx, r)
		if err != nil {
			WriteErrorResponse(w, err)
			return
		}

		ar.Authorized = true
		resp, err := server.FinishAccessRequest(ctx, ar)
		if err != nil {
			WriteErrorResponse(w, err)
			return
		}

		WriteJSONResponse(w, resp)
	}))
	s.testAccessURL = accessServer.URL

	s.oauthConfig = newOAuthConfig(s.testAuthorizeURL, s.testAccessURL)
}

func (s *NisoIntegrationTestSuite) TestAuthCodeCallbackSuccess() {
	client := http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	authCodeURL := s.oauthConfig.AuthCodeURL("kappa")

	resp, err := client.Get(authCodeURL)
	require.NoError(s.T(), err)

	assert.Equal(s.T(), 302, resp.StatusCode)
	assert.Equal(s.T(), "http://localhost/callback?code=1&state=kappa", resp.Header["Location"][0])
}

func (s *NisoIntegrationTestSuite) TestAccessTokenExchangeSuccess() {
	tok, err := s.oauthConfig.Exchange(context.TODO(), testAuthCode)
	require.NoError(s.T(), err)
	assert.Equal(s.T(), "r1", tok.RefreshToken)
	assert.Equal(s.T(), "1", tok.AccessToken)
}

func (s *NisoIntegrationTestSuite) TestAccessTokenExchangeFail() {
	_, err := s.oauthConfig.Exchange(context.TODO(), "invalid")
	assert.Error(s.T(), err)
	assert.Contains(s.T(), err.Error(), "invalid_grant")
}

func TestNisoIntegrationTestSuite(t *testing.T) {
	suite.Run(t, new(NisoIntegrationTestSuite))
}

func newOAuthConfig(authURL string, tokenURL string) *oauth2.Config {
	return &oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURL:  redirectURI,
		Scopes:       []string{"scope1", "scope2"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  authURL,
			TokenURL: tokenURL,
		},
	}
}

func newIntegrationTestStorage() Storage {
	r := &TestingStorage{
		clients:   make(map[string]*ClientData),
		authorize: make(map[string]*AuthorizeData),
		access:    make(map[string]*AccessData),
		refresh:   make(map[string]*RefreshTokenData),
	}

	r.clients[clientID] = &ClientData{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURI:  redirectURI,
	}

	r.authorize[testAuthCode] = &AuthorizeData{
		ClientData:  r.clients[clientID],
		Code:        testAuthCode,
		ExpiresIn:   3600,
		CreatedAt:   time.Now(),
		RedirectURI: redirectURI,
	}

	return r
}
<|endoftext|>


<commit_before>package messenger

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

const (
	WebhookURL = "/webhook"
)

type MessengerOptions struct {
	Verify      bool
	VerifyToken string
	Token       string
}

type MessageHandler func(Message, *Response)
type DeliveryHandler func(Delivery, *Response)

type Messenger struct {
	mux              *http.ServeMux
	messageHandlers  []MessageHandler
	deliveryHandlers []DeliveryHandler
	token            string
}

func New(mo MessengerOptions) *Messenger {
	m := &Messenger{
		mux:   http.NewServeMux(),
		token: mo.Token,
	}

	if mo.Verify {
		m.mux.HandleFunc(WebhookURL, newVerifyHandler(mo.VerifyToken))
	} else {
		m.mux.HandleFunc(WebhookURL, m.handle)
	}

	return m
}

func (m *Messenger) HandleMessage(f MessageHandler) {
	m.messageHandlers = append(m.messageHandlers, f)
}

func (m *Messenger) HandleDelivery(f DeliveryHandler) {
	m.deliveryHandlers = append(m.deliveryHandlers, f)
}

func (m *Messenger) Handler() http.Handler {
	return m.mux
}

func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) {
	var rec Receive

	err := json.NewDecoder(r.Body).Decode(&rec)
	if err != nil {
		fmt.Println(err)

		fmt.Fprintln(w, `{status: 'not ok'}`)
		return
	}

	if rec.Object != "page" {
		fmt.Println("Object is not page, undefined behaviour. Got", rec.Object)
	}

	m.dispatch(rec)

	fmt.Fprintln(w, `{status: 'ok'}`)
}

func (m *Messenger) dispatch(r Receive) {
	for _, entry := range r.Entry {
		for _, info := range entry.Messaging {
			a := m.classify(info, entry)
			if a == UnknownAction {
				fmt.Println("Unknown action:", info)
				continue
			}

			resp := &Response{
				to:    Recipient{info.Sender.ID},
				token: m.token,
			}

			switch a {
			case TextAction:
				for _, f := range m.messageHandlers {
					message := *info.Message
					message.Sender = info.Sender
					message.Recipient = info.Recipient
					message.Time = time.Unix(info.Timestamp, 0)

					f(message, resp)
				}
			case DeliveryAction:
				for _, f := range m.deliveryHandlers {
					f(*info.Delivery, resp)
				}
			}
		}
	}
}

func (m *Messenger) classify(info MessageInfo, e Entry) Action {
	if info.Message != nil {
		return TextAction
	} else if info.Delivery != nil {
		return DeliveryAction
	}

	return UnknownAction
}

func newVerifyHandler(token string) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.FormValue("hub.verify_token") == token {
			fmt.Fprintln(w, r.FormValue("hub.challenge"))
			return
		}

		fmt.Fprintln(w, "Incorrect verify token.")
	}
}
<commit_msg>Add documentation to Messenger<commit_after>package messenger

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

const (
	// WebhookURL is where the Messenger client should listen for webhook events.
	WebhookURL = "/webhook"
)

// MessengerOptions are the settings used when creating a Messenger client.
type MessengerOptions struct {
	// Verify sets whether or not to be in the "verify" mode. Used for
	// verifying webhooks on the Facebook Developer Portal.
	Verify bool
	// VerifyToken is the token to be used when verifying the webhook. Is set
	// when the webhook is created.
	VerifyToken string
	// Token is the access token of the Facebook page to send messages from.
	Token string
}

// MessageHandler is a handler used for responding to a message containing text.
type MessageHandler func(Message, *Response)

// DeliveryHandler is a handler used for responding to a read receipt.
type DeliveryHandler func(Delivery, *Response)

// Messenger is the client which manages communication with the Messenger Platform API.
type Messenger struct {
	mux              *http.ServeMux
	messageHandlers  []MessageHandler
	deliveryHandlers []DeliveryHandler
	token            string
}

// New creates a new Messenger. You pass in MessengerOptions in order to affect settings.
func New(mo MessengerOptions) *Messenger {
	m := &Messenger{
		mux:   http.NewServeMux(),
		token: mo.Token,
	}

	if mo.Verify {
		m.mux.HandleFunc(WebhookURL, newVerifyHandler(mo.VerifyToken))
	} else {
		m.mux.HandleFunc(WebhookURL, m.handle)
	}

	return m
}

// HandleMessage adds a new MessageHandler to the Messenger which will be triggered
// when a message is recieved by the client.
func (m *Messenger) HandleMessage(f MessageHandler) {
	m.messageHandlers = append(m.messageHandlers, f)
}

// HandleDelivery adds a new DeliveryHandler to the Messenger which will be triggered
// when a previously sent message is read by the recipient.
func (m *Messenger) HandleDelivery(f DeliveryHandler) {
	m.deliveryHandlers = append(m.deliveryHandlers, f)
}

// Handler returns the Messenger in HTTP client form.
func (m *Messenger) Handler() http.Handler {
	return m.mux
}

// handle is the internal HTTP handler for the webhooks.
func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) {
	var rec Receive

	err := json.NewDecoder(r.Body).Decode(&rec)
	if err != nil {
		fmt.Println(err)

		fmt.Fprintln(w, `{status: 'not ok'}`)
		return
	}

	if rec.Object != "page" {
		fmt.Println("Object is not page, undefined behaviour. Got", rec.Object)
	}

	m.dispatch(rec)

	fmt.Fprintln(w, `{status: 'ok'}`)
}

// dispatch triggers all of the relevant handlers when a webhook event is received.
func (m *Messenger) dispatch(r Receive) {
	for _, entry := range r.Entry {
		for _, info := range entry.Messaging {
			a := m.classify(info, entry)
			if a == UnknownAction {
				fmt.Println("Unknown action:", info)
				continue
			}

			resp := &Response{
				to:    Recipient{info.Sender.ID},
				token: m.token,
			}

			switch a {
			case TextAction:
				for _, f := range m.messageHandlers {
					message := *info.Message
					message.Sender = info.Sender
					message.Recipient = info.Recipient
					message.Time = time.Unix(info.Timestamp, 0)

					f(message, resp)
				}
			case DeliveryAction:
				for _, f := range m.deliveryHandlers {
					f(*info.Delivery, resp)
				}
			}
		}
	}
}

// classify determines what type of message a webhook event is.
func (m *Messenger) classify(info MessageInfo, e Entry) Action {
	if info.Message != nil {
		return TextAction
	} else if info.Delivery != nil {
		return DeliveryAction
	}

	return UnknownAction
}

// newVerifyHandler returns a function which can be used to handle webhook verification
func newVerifyHandler(token string) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.FormValue("hub.verify_token") == token {
			fmt.Fprintln(w, r.FormValue("hub.challenge"))
			return
		}

		fmt.Fprintln(w, "Incorrect verify token.")
	}
}
<|endoftext|>


<commit_before>// Copyright 2018 The Ebiten 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 bsp offers binary space partitioning algorithm.
package bsp

const (
	MaxSize = 1024
	minSize = 4
)

type Page struct {
	root *Node
}

type Node struct {
	x      int
	y      int
	width  int
	height int

	used   bool
	parent *Node
	child0 *Node
	child1 *Node
}

func (n *Node) canFree() bool {
	if n.used {
		return false
	}
	if n.child0 == nil && n.child1 == nil {
		return true
	}
	return n.child0.canFree() && n.child1.canFree()
}

func (n *Node) Region() (x, y, width, height int) {
	return n.x, n.y, n.width, n.height
}

// square returns a float value indicating how much the given rectangle is close to a square.
// If the given rectangle is square, this return 1 (maximum value).
// Otherwise, this returns a value in [0, 1).
func square(width, height int) float64 {
	if width == 0 && height == 0 {
		return 0
	}
	if width <= height {
		return float64(width) / float64(height)
	}
	return float64(height) / float64(width)
}

func (n *Node) alloc(width, height int) *Node {
	if n.width < width || n.height < height {
		return nil
	}
	if n.used {
		return nil
	}
	if n.child0 == nil && n.child1 == nil {
		if n.width == width && n.height == height {
			n.used = true
			return n
		}
		if square(n.width-width, n.height) >= square(n.width, n.height-height) {
			// Split vertically
			n.child0 = &Node{
				x:      n.x,
				y:      n.y,
				width:  width,
				height: n.height,
				parent: n,
			}
			n.child1 = &Node{
				x:      n.x + width,
				y:      n.y,
				width:  n.width - width,
				height: n.height,
				parent: n,
			}
			return n.child0.alloc(width, height)
		} else {
			// Split holizontally
			n.child0 = &Node{
				x:      n.x,
				y:      n.y,
				width:  n.width,
				height: height,
				parent: n,
			}
			n.child1 = &Node{
				x:      n.x,
				y:      n.y + height,
				width:  n.width,
				height: n.height - height,
				parent: n,
			}
			return n.child0.alloc(width, height)
		}
	}
	if n.child0 == nil || n.child1 == nil {
		panic("not reached")
	}
	if node := n.child0.alloc(width, height); node != nil {
		return node
	}
	if node := n.child1.alloc(width, height); node != nil {
		return node
	}
	return nil
}

func (p *Page) Alloc(width, height int) *Node {
	if width <= 0 || height <= 0 {
		panic("bsp: width and height must > 0")
	}
	if p.root == nil {
		p.root = &Node{
			width:  MaxSize,
			height: MaxSize,
		}
	}
	if width < minSize {
		width = minSize
	}
	if height < minSize {
		height = minSize
	}
	return p.root.alloc(width, height)
}

func (p *Page) Free(node *Node) {
	if node.child0 != nil || node.child1 != nil {
		panic("bsp: can't free the node including children")
	}
	node.used = false
	if node.parent == nil {
		return
	}
	if node.parent.child0 == nil || node.parent.child1 == nil {
		panic("not reached")
	}
	if node.parent.child0.canFree() && node.parent.child1.canFree() {
		node.parent.child0 = nil
		node.parent.child1 = nil
		p.Free(node.parent)
	}
}
<commit_msg>internal/bsp: Allow 1 pixel<commit_after>// Copyright 2018 The Ebiten 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 bsp offers binary space partitioning algorithm.
package bsp

const (
	MaxSize = 1024
	minSize = 1
)

type Page struct {
	root *Node
}

type Node struct {
	x      int
	y      int
	width  int
	height int

	used   bool
	parent *Node
	child0 *Node
	child1 *Node
}

func (n *Node) canFree() bool {
	if n.used {
		return false
	}
	if n.child0 == nil && n.child1 == nil {
		return true
	}
	return n.child0.canFree() && n.child1.canFree()
}

func (n *Node) Region() (x, y, width, height int) {
	return n.x, n.y, n.width, n.height
}

// square returns a float value indicating how much the given rectangle is close to a square.
// If the given rectangle is square, this return 1 (maximum value).
// Otherwise, this returns a value in [0, 1).
func square(width, height int) float64 {
	if width == 0 && height == 0 {
		return 0
	}
	if width <= height {
		return float64(width) / float64(height)
	}
	return float64(height) / float64(width)
}

func (n *Node) alloc(width, height int) *Node {
	if n.width < width || n.height < height {
		return nil
	}
	if n.used {
		return nil
	}
	if n.child0 == nil && n.child1 == nil {
		if n.width == width && n.height == height {
			n.used = true
			return n
		}
		if square(n.width-width, n.height) >= square(n.width, n.height-height) {
			// Split vertically
			n.child0 = &Node{
				x:      n.x,
				y:      n.y,
				width:  width,
				height: n.height,
				parent: n,
			}
			n.child1 = &Node{
				x:      n.x + width,
				y:      n.y,
				width:  n.width - width,
				height: n.height,
				parent: n,
			}
			return n.child0.alloc(width, height)
		} else {
			// Split holizontally
			n.child0 = &Node{
				x:      n.x,
				y:      n.y,
				width:  n.width,
				height: height,
				parent: n,
			}
			n.child1 = &Node{
				x:      n.x,
				y:      n.y + height,
				width:  n.width,
				height: n.height - height,
				parent: n,
			}
			return n.child0.alloc(width, height)
		}
	}
	if n.child0 == nil || n.child1 == nil {
		panic("not reached")
	}
	if node := n.child0.alloc(width, height); node != nil {
		return node
	}
	if node := n.child1.alloc(width, height); node != nil {
		return node
	}
	return nil
}

func (p *Page) Alloc(width, height int) *Node {
	if width <= 0 || height <= 0 {
		panic("bsp: width and height must > 0")
	}
	if p.root == nil {
		p.root = &Node{
			width:  MaxSize,
			height: MaxSize,
		}
	}
	if width < minSize {
		width = minSize
	}
	if height < minSize {
		height = minSize
	}
	return p.root.alloc(width, height)
}

func (p *Page) Free(node *Node) {
	if node.child0 != nil || node.child1 != nil {
		panic("bsp: can't free the node including children")
	}
	node.used = false
	if node.parent == nil {
		return
	}
	if node.parent.child0 == nil || node.parent.child1 == nil {
		panic("not reached")
	}
	if node.parent.child0.canFree() && node.parent.child1.canFree() {
		node.parent.child0 = nil
		node.parent.child1 = nil
		p.Free(node.parent)
	}
}
<|endoftext|>


<commit_before>package luar

import (
	"reflect"

	"github.com/yuin/gopher-lua"
)

// Metatable is the Lua metatable for a Go type.
type Metatable struct {
	*lua.LTable
}

// MT returns the metatable for value's type. nil is returned if value's type
// does not use a custom metatable.
func MT(L *lua.LState, value interface{}) *Metatable {
	val := reflect.ValueOf(value)
	switch val.Type().Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct:
		return &Metatable{
			LTable: getMetatableFromValue(L, val),
		}
	default:
		return nil
	}
}

func (m *Metatable) method(name string) lua.LValue {
	methods := m.RawGetString("methods").(*lua.LTable)
	if fn := methods.RawGetString(name); fn != lua.LNil {
		return fn
	}
	return nil
}

func (m *Metatable) fieldIndex(name string) []int {
	fields := m.RawGetString("fields").(*lua.LTable)
	if index := fields.RawGetString(name); index != lua.LNil {
		return index.(*lua.LUserData).Value.([]int)
	}
	return nil
}
<commit_msg>simplify MT<commit_after>package luar

import (
	"reflect"

	"github.com/yuin/gopher-lua"
)

// Metatable is the Lua metatable for a Go type.
type Metatable struct {
	*lua.LTable
}

// MT returns the metatable for value's type. nil is returned if value's type
// does not use a custom metatable.
func MT(L *lua.LState, value interface{}) *Metatable {
	switch val := reflect.ValueOf(value); val.Type().Kind() {
	case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct:
		return &Metatable{
			LTable: getMetatableFromValue(L, val),
		}
	}
	return nil
}

func (m *Metatable) method(name string) lua.LValue {
	methods := m.RawGetString("methods").(*lua.LTable)
	if fn := methods.RawGetString(name); fn != lua.LNil {
		return fn
	}
	return nil
}

func (m *Metatable) fieldIndex(name string) []int {
	fields := m.RawGetString("fields").(*lua.LTable)
	if index := fields.RawGetString(name); index != lua.LNil {
		return index.(*lua.LUserData).Value.([]int)
	}
	return nil
}
<|endoftext|>


<commit_before>package filelock_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"

	"testing"
)

func TestFilelock(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Filelock Suite")
}

const demoPackagePath = "github.com/rosenhouse/filelock/demo"

var pathToBinary string

var _ = SynchronizedBeforeSuite(func() []byte {
	var err error
	pathToBinary, err = gexec.Build(demoPackagePath)
	Expect(err).NotTo(HaveOccurred())
	return []byte(pathToBinary)
}, func(crossNodeData []byte) {
	pathToBinary = string(crossNodeData)
})

var _ = SynchronizedAfterSuite(func() {}, func() {
	gexec.CleanupBuildArtifacts()
})
<commit_msg>Fix up demo package path used in external process test<commit_after>package filelock_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"

	"testing"
)

func TestFilelock(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Filelock Suite")
}

const demoPackagePath = "github.com/rosenhouse/filelock/filelock-demo"

var pathToBinary string

var _ = SynchronizedBeforeSuite(func() []byte {
	var err error
	pathToBinary, err = gexec.Build(demoPackagePath)
	Expect(err).NotTo(HaveOccurred())
	return []byte(pathToBinary)
}, func(crossNodeData []byte) {
	pathToBinary = string(crossNodeData)
})

var _ = SynchronizedAfterSuite(func() {}, func() {
	gexec.CleanupBuildArtifacts()
})
<|endoftext|>


<commit_before>/*
Copyright IBM Corp. 2016 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

//WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of
//calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has
//to be modified as well with the new ID of chaincode_example02.
//chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of
//hard-coding.

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return nil, errors.New("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	B = args[2]
	Bval, err = strconv.Atoi(args[3])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function == "delete" {
		// Deletes an entity from its state
		return t.delete(stub, args)
	}

	if function == "addTable" {
		// Deletes an entity from its state
		return t.addTable(stub, args)
	}

	if function == "getTable" {
		// Deletes an entity from its state
		return t.getTable(stub, args)
	}

	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var X int          // Transaction value
	var err error

	if len(args) != 3 {
		return nil, errors.New("Incorrect number of arguments. Expecting 3")
	}

	A = args[0]
	B = args[1]

	// Get the state from the ledger
	// TODO: will be nice to have a GetAllState call to ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Avalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Aval, _ = strconv.Atoi(string(Avalbytes))

	Bvalbytes, err := stub.GetState(B)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Bvalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Bval, _ = strconv.Atoi(string(Bvalbytes))

	// Perform the execution
	X, err = strconv.Atoi(args[2])
	if err != nil {
		return nil, errors.New("Invalid transaction amount, expecting a integer value")
	}
	Aval = Aval - X
	Bval = Bval + X
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state back to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) addTable(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	err := stub.CreateTable(“TableName”, []*shim.ColumnDefinition{
	&shim.ColumnDefinition{Name: “Customer_ID”, Type: shim.ColumnDefinition_STRING, Key: true},
	&shim.ColumnDefinition{Name: "Customer_Name", Type: shim.ColumnDefinition_STRING, Key: false},
	&shim.ColumnDefinition{Name: "Customer_Gender", Type: shim.ColumnDefinition_STRING, Key: false},
	})

	success, err := stub.InsertRow("Customer", shim.Row{
	Columns: []*shim.Column{
	&shim.Column{Value: &shim.Column_String_{String_: C1001}},
	&shim.Column{Value: &shim.Column_String_{String_: Vivek}},
	&shim.Column{Value: &shim.Column_String_{String_: Male}},
	},
	})

	success, err := stub.InsertRow("Customer", shim.Row{
	Columns: []*shim.Column{
	&shim.Column{Value: &shim.Column_String_{String_: C1002}},
	&shim.Column{Value: &shim.Column_String_{String_: John}},
	&shim.Column{Value: &shim.Column_String_{String_: Male}},
	},
	})

	success, err := stub.InsertRow("Customer", shim.Row{
	Columns: []*shim.Column{
	&shim.Column{Value: &shim.Column_String_{String_: C1003}},
	&shim.Column{Value: &shim.Column_String_{String_: Simone}},
	&shim.Column{Value: &shim.Column_String_{String_: Female}},
	},
	})
	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) getTable(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: C1001}}
	columns = append(columns, col1)

	row, err := stub.GetRow("Customer", columns)
	if err != nil {
		return shim.Error(fmt.Sprintf("Failed retrieving asset [%s]: [%s]", C1001, err))
	}

	var columns2 []shim.Column
	col2 := shim.Column{Value: &shim.Column_String_{String_: Male}}
	columns = append(columns2, col2)

	rowChannel, err := stub.GetRows("Customer", columns2)
	if err != nil {
		return nil, fmt.Errorf("getRows operation failed. %s", err)
	}
	var rows []shim.Row
		for {
			select {
			case row, ok := <-rowChannel:
				if !ok {
					rowChannel = nil
				} else {
					rows = append(rows, row)
				}
			}
			if rowChannel == nil {
				break
			}
		}

	jsonRows, err := json.Marshal(rows)
		if err != nil {
			return nil, fmt.Errorf("getRows operation failed. Error marshaling JSON: %s", err)
		}

	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	A := args[0]

	// Delete the key from the state in ledger
	err := stub.DelState(A)
	if err != nil {
		return nil, errors.New("Failed to delete state")
	}

	return nil, nil
}

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function != "query" {
		return nil, errors.New("Invalid query function name. Expecting \"query\"")
	}
	var A string // Entities
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the person to query")
	}

	A = args[0]

	// Get the state from the ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return Avalbytes, nil
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
<commit_msg>Update accumshare.go<commit_after>/*
Copyright IBM Corp. 2016 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

//WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of
//calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has
//to be modified as well with the new ID of chaincode_example02.
//chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of
//hard-coding.

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return nil, errors.New("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	B = args[2]
	Bval, err = strconv.Atoi(args[3])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function == "delete" {
		// Deletes an entity from its state
		return t.delete(stub, args)
	}

	if function == "addTable" {
		// Deletes an entity from its state
		return t.addTable(stub, args)
	}

	if function == "getTable" {
		// Deletes an entity from its state
		return t.getTable(stub, args)
	}

	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var X int          // Transaction value
	var err error

	if len(args) != 3 {
		return nil, errors.New("Incorrect number of arguments. Expecting 3")
	}

	A = args[0]
	B = args[1]

	// Get the state from the ledger
	// TODO: will be nice to have a GetAllState call to ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Avalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Aval, _ = strconv.Atoi(string(Avalbytes))

	Bvalbytes, err := stub.GetState(B)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Bvalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Bval, _ = strconv.Atoi(string(Bvalbytes))

	// Perform the execution
	X, err = strconv.Atoi(args[2])
	if err != nil {
		return nil, errors.New("Invalid transaction amount, expecting a integer value")
	}
	Aval = Aval - X
	Bval = Bval + X
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state back to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) addTable(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	err := stub.CreateTable("Customer", []*shim.ColumnDefinition{
	&shim.ColumnDefinition{Name: "Customer_ID", Type: shim.ColumnDefinition_STRING, Key: true},
	&shim.ColumnDefinition{Name: "Customer_Name", Type: shim.ColumnDefinition_STRING, Key: false},
	&shim.ColumnDefinition{Name: "Customer_Gender", Type: shim.ColumnDefinition_STRING, Key: false},
	})

	success, err := stub.InsertRow("Customer", shim.Row{
	Columns: []*shim.Column{
	&shim.Column{Value: &shim.Column_String_{String_: C1001}},
	&shim.Column{Value: &shim.Column_String_{String_: Vivek}},
	&shim.Column{Value: &shim.Column_String_{String_: Male}},
	},
	})

	success, err := stub.InsertRow("Customer", shim.Row{
	Columns: []*shim.Column{
	&shim.Column{Value: &shim.Column_String_{String_: C1002}},
	&shim.Column{Value: &shim.Column_String_{String_: John}},
	&shim.Column{Value: &shim.Column_String_{String_: Male}},
	},
	})

	success, err := stub.InsertRow("Customer", shim.Row{
	Columns: []*shim.Column{
	&shim.Column{Value: &shim.Column_String_{String_: C1003}},
	&shim.Column{Value: &shim.Column_String_{String_: Simone}},
	&shim.Column{Value: &shim.Column_String_{String_: Female}},
	},
	})
	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) getTable(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: C1001}}
	columns = append(columns, col1)

	row, err := stub.GetRow("Customer", columns)
	if err != nil {
		return shim.Error(fmt.Sprintf("Failed retrieving asset [%s]: [%s]", C1001, err))
	}

	var columns2 []shim.Column
	col2 := shim.Column{Value: &shim.Column_String_{String_: Male}}
	columns = append(columns2, col2)

	rowChannel, err := stub.GetRows("Customer", columns2)
	if err != nil {
		return nil, fmt.Errorf("getRows operation failed. %s", err)
	}
	var rows []shim.Row
		for {
			select {
			case row, ok := <-rowChannel:
				if !ok {
					rowChannel = nil
				} else {
					rows = append(rows, row)
				}
			}
			if rowChannel == nil {
				break
			}
		}

	jsonRows, err := json.Marshal(rows)
		if err != nil {
			return nil, fmt.Errorf("getRows operation failed. Error marshaling JSON: %s", err)
		}

	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	A := args[0]

	// Delete the key from the state in ledger
	err := stub.DelState(A)
	if err != nil {
		return nil, errors.New("Failed to delete state")
	}

	return nil, nil
}

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function != "query" {
		return nil, errors.New("Invalid query function name. Expecting \"query\"")
	}
	var A string // Entities
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the person to query")
	}

	A = args[0]

	// Get the state from the ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return Avalbytes, nil
}

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


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/lambrospetrou/gomicroblog/gen"
	"log"
	"path/filepath"
	"runtime"
)

func main() {
	fmt.Println("Go Microblog service started!")

	// use all the available cores
	runtime.GOMAXPROCS(runtime.NumCPU())

	var dir_site = flag.String("site", "", "specify a directory that contains the site to generate")
	flag.Parse()

	log.Println("site:", *dir_site)
	if len(*dir_site) > 0 {
		err := gen.GenerateSite(*dir_site, filepath.Join(*dir_site, "config.json"))
		if err != nil {
			panic(err)
		}
		return
	} else {
		log.Fatalln("Site source directory not given")
		return
	}
}
<commit_msg>refactorings<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"path/filepath"
	"runtime"

	"github.com/lambrospetrou/gomicroblog/gen"
)

func main() {
	fmt.Println("Go Microblog service started!")

	// use all the available cores
	runtime.GOMAXPROCS(runtime.NumCPU())

	var dirSite = flag.String("site", "", "specify a directory that contains the site to generate")
	flag.Parse()

	log.Println("site:", *dirSite)
	if len(*dirSite) > 0 {
		err := gen.GenerateSite(*dirSite, filepath.Join(*dirSite, "config.json"))
		if err != nil {
			panic(err)
		}
		return
	}
	log.Fatalln("Site source directory not given")
	return
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.

package watch

import (
	"github.com/howeyc/fsnotify"
	"os"
	"path/filepath"
	"launchpad.net/tomb"
)

// InotifyFileWatcher uses inotify to monitor file changes.
type InotifyFileWatcher struct {
	Filename string
	Size     int64
}

func NewInotifyFileWatcher(filename string) *InotifyFileWatcher {
	fw := &InotifyFileWatcher{filename, 0}
	return fw
}

func (fw *InotifyFileWatcher) BlockUntilExists(t tomb.Tomb) error {
	w, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}
	defer w.Close()

	dirname := filepath.Dir(fw.Filename)

	// Watch for new files to be created in the parent directory.
	err = w.WatchFlags(dirname, fsnotify.FSN_CREATE)
	if err != nil {
		return err
	}
	defer w.RemoveWatch(filepath.Dir(fw.Filename))

	// Do a real check now as the file might have been created before
	// calling `WatchFlags` above.
	if _, err = os.Stat(fw.Filename); !os.IsNotExist(err) {
		// file exists, or stat returned an error.
		return err
	}

	for {
		select {
		case evt := <-w.Event:
			if evt.Name == fw.Filename {
				return nil
			}
		case <-t.Dying():
			return tomb.ErrDying
		}
	}
	panic("unreachable")
}

func (fw *InotifyFileWatcher) ChangeEvents(t tomb.Tomb, fi os.FileInfo) *FileChanges {
	changes := NewFileChanges()

	w, err := fsnotify.NewWatcher()
	if err != nil {
		panic(err)
	}
	err = w.Watch(fw.Filename)
	if err != nil {
		panic(err)
	}

	fw.Size = fi.Size()

	go func() {
		defer w.Close()
		defer w.RemoveWatch(fw.Filename)
		defer changes.Close()

		for {
			prevSize := fw.Size

			var evt *fsnotify.FileEvent

			select {
			case evt = <-w.Event:
			case <-t.Dying():
				return
			}

			switch {
			case evt.IsDelete():
				fallthrough

			case evt.IsRename():
				changes.NotifyDeleted()
				return

			case evt.IsModify():
				fi, err := os.Stat(fw.Filename)
				if err != nil {
					// XXX: no panic here
					panic(err)
				}
				fw.Size = fi.Size()

				if prevSize > 0 && prevSize > fw.Size {
					changes.NotifyTruncated()
				}else{
					changes.NotifyModified()
				}
				prevSize = fw.Size
			}
		}
	}()

	return changes
}
<commit_msg>fix race/panic on modify+delete<commit_after>// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.

package watch

import (
	"github.com/howeyc/fsnotify"
	"os"
	"path/filepath"
	"launchpad.net/tomb"
)

// InotifyFileWatcher uses inotify to monitor file changes.
type InotifyFileWatcher struct {
	Filename string
	Size     int64
}

func NewInotifyFileWatcher(filename string) *InotifyFileWatcher {
	fw := &InotifyFileWatcher{filename, 0}
	return fw
}

func (fw *InotifyFileWatcher) BlockUntilExists(t tomb.Tomb) error {
	w, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}
	defer w.Close()

	dirname := filepath.Dir(fw.Filename)

	// Watch for new files to be created in the parent directory.
	err = w.WatchFlags(dirname, fsnotify.FSN_CREATE)
	if err != nil {
		return err
	}
	defer w.RemoveWatch(filepath.Dir(fw.Filename))

	// Do a real check now as the file might have been created before
	// calling `WatchFlags` above.
	if _, err = os.Stat(fw.Filename); !os.IsNotExist(err) {
		// file exists, or stat returned an error.
		return err
	}

	for {
		select {
		case evt := <-w.Event:
			if evt.Name == fw.Filename {
				return nil
			}
		case <-t.Dying():
			return tomb.ErrDying
		}
	}
	panic("unreachable")
}

func (fw *InotifyFileWatcher) ChangeEvents(t tomb.Tomb, fi os.FileInfo) *FileChanges {
	changes := NewFileChanges()

	w, err := fsnotify.NewWatcher()
	if err != nil {
		panic(err)
	}
	err = w.Watch(fw.Filename)
	if err != nil {
		panic(err)
	}

	fw.Size = fi.Size()

	go func() {
		defer w.Close()
		defer w.RemoveWatch(fw.Filename)
		defer changes.Close()

		for {
			prevSize := fw.Size

			var evt *fsnotify.FileEvent

			select {
			case evt = <-w.Event:
			case <-t.Dying():
				return
			}

			switch {
			case evt.IsDelete():
				fallthrough

			case evt.IsRename():
				changes.NotifyDeleted()
				return

			case evt.IsModify():
				fi, err := os.Stat(fw.Filename)
				if err != nil {
					if os.IsNotExist(err) {
						changes.NotifyDeleted()
						return
					}
					// XXX: no panic here
					panic(err)
				}
				fw.Size = fi.Size()

				if prevSize > 0 && prevSize > fw.Size {
					changes.NotifyTruncated()
				}else{
					changes.NotifyModified()
				}
				prevSize = fw.Size
			}
		}
	}()

	return changes
}
<|endoftext|>


<commit_before>package node

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/gincorp/gin/taskmanager"
	"github.com/streadway/amqp"
)

// Node ...
// Nodes are the powerhouse of the tool; they receive messages
// from RabbitMQ (*Consumer), push messages into RabbitMQ (*Producer)
// and handle what those individual messages are (TaskManager)
type Node struct {
	Consumer    *Consumer
	Producer    *Producer
	TaskManager taskmanager.TaskManager
}

var (
	consumerKey, producerKey string
)

// NewNode ...
// Return a Node container
func NewNode(uri, redisURI, nodeMode string) (n Node) {
	switch nodeMode {
	case "job":
		consumerKey = "job"
		producerKey = "master"

		n.TaskManager = taskmanager.NewJobManager()
	case "master":
		consumerKey = "master"
		producerKey = "job"

		n.TaskManager = taskmanager.NewMasterManager(redisURI)
	}

	c := NewConsumer(uri, consumerKey)
	p := NewProducer(uri, producerKey)

	n.Consumer = c
	n.Producer = p

	return
}

// ConsumerLoop ...
// Connect to RabbitMQ based on a *Consumer and route messages
func (n *Node) ConsumerLoop() (err error) {
	if n.Consumer.conn, err = amqp.Dial(n.Consumer.uri); err != nil {
		return fmt.Errorf("Dial: %s", err)
	}

	go func() {
		fmt.Printf("closing: %s", <-n.Consumer.conn.NotifyClose(make(chan *amqp.Error)))
	}()

	log.Printf("got Connection, getting Channel")
	if n.Consumer.channel, err = n.Consumer.conn.Channel(); err != nil {
		return fmt.Errorf("Channel: %s", err)
	}

	log.Printf("got Channel, declaring Exchange (%q)", n.Consumer.exch)
	if err = n.Consumer.channel.ExchangeDeclare(
		n.Consumer.exch, // name of the exchange
		"direct",        // type
		true,            // durable
		false,           // delete when complete
		false,           // internal
		false,           // noWait
		nil,             // arguments
	); err != nil {
		return fmt.Errorf("Exchange Declare: %s", err)
	}

	log.Printf("declared Exchange, declaring Queue (%q)", n.Consumer.queue)
	queue, err := n.Consumer.channel.QueueDeclare(
		n.Consumer.queue, // name of the queue
		true,             // durable
		false,            // delete when usused
		false,            // exclusive
		false,            // noWait
		nil,              // arguments
	)
	if err != nil {
		return fmt.Errorf("Queue Declare: %s", err)
	}

	log.Printf("declared Queue (%q %d messages, %d consumers), binding to Exchange (key %q)",
		queue.Name, queue.Messages, queue.Consumers, n.Consumer.key)

	if err = n.Consumer.channel.QueueBind(
		queue.Name,      // name of the queue
		n.Consumer.key,  // bindingKey
		n.Consumer.exch, // sourceExchange
		false,           // noWait
		nil,             // arguments
	); err != nil {
		return fmt.Errorf("Queue Bind: %s", err)
	}

	log.Printf("Queue bound to Exchange, starting Consume (consumer tag %q)", n.Consumer.tag)
	deliveries, err := n.Consumer.channel.Consume(
		queue.Name,     // name
		n.Consumer.tag, // consumerTag,
		false,          // noAck
		false,          // exclusive
		false,          // noLocal
		false,          // noWait
		nil,            // arguments
	)
	if err != nil {
		return fmt.Errorf("Queue Consume: %s", err)
	}

	go n.Consume(deliveries, n.Consumer.done)

	select {}
}

// Consume ...
// Consume messages off a channel provided by `Node.ConsumerLoop`
// This function blocks on tasks, but not when delivering
func (n *Node) Consume(deliveries <-chan amqp.Delivery, done chan error) {
	for d := range deliveries {
		log.Printf("[%v] : %q received %q", d.DeliveryTag, n.Consumer.queue, d.Body)

		output, err := n.TaskManager.Consume(string(d.Body))
		if err != nil {
			log.Printf("[%v] : errors %q", d.DeliveryTag, err)

		}

		if len(output) > 0 {
			go func() {
				log.Printf("[%v] : responding with %q", d.DeliveryTag, output)

				if err := n.Deliver(output); err != nil {
					log.Printf("[%v] : response errored: %q", d.DeliveryTag, err)

					d.Ack(false)
				} else {
					log.Printf("[%v] : responded", d.DeliveryTag)

					d.Ack(true)
				}
			}()
		} else {
			d.Ack(true)
		}
	}
	log.Printf("handle: deliveries channel closed")
	done <- nil
}

// Deliver ...
// Turn a message into json and use a producer to send it
func (n *Node) Deliver(message interface{}) error {
	j, err := json.Marshal(message)

	if err != nil {
		return err
	}

	return n.Producer.Send(j)
}
<commit_msg>Unexport unneccesarily exported fucntions<commit_after>package node

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/gincorp/gin/taskmanager"
	"github.com/streadway/amqp"
)

// Node creates a Node.
// Nodes are the powerhouse of the tool; they receive messages
// from RabbitMQ (*Consumer), push messages into RabbitMQ (*Producer)
// and handle what those individual messages are (TaskManager)
type Node struct {
	Consumer    *Consumer
	Producer    *Producer
	TaskManager taskmanager.TaskManager
}

var (
	consumerKey, producerKey string
)

// NewNode returns a Node container
func NewNode(uri, redisURI, nodeMode string) (n Node) {
	switch nodeMode {
	case "job":
		consumerKey = "job"
		producerKey = "master"

		n.TaskManager = taskmanager.NewJobManager()
	case "master":
		consumerKey = "master"
		producerKey = "job"

		n.TaskManager = taskmanager.NewMasterManager(redisURI)
	}

	c := NewConsumer(uri, consumerKey)
	p := NewProducer(uri, producerKey)

	n.Consumer = c
	n.Producer = p

	return
}

// ConsumerLoop connects to RabbitMQ based on a *Consumer and route messages
func (n *Node) ConsumerLoop() (err error) {
	if n.Consumer.conn, err = amqp.Dial(n.Consumer.uri); err != nil {
		return fmt.Errorf("Dial: %s", err)
	}

	go func() {
		fmt.Printf("closing: %s", <-n.Consumer.conn.NotifyClose(make(chan *amqp.Error)))
	}()

	log.Printf("got Connection, getting Channel")
	if n.Consumer.channel, err = n.Consumer.conn.Channel(); err != nil {
		return fmt.Errorf("Channel: %s", err)
	}

	log.Printf("got Channel, declaring Exchange (%q)", n.Consumer.exch)
	if err = n.Consumer.channel.ExchangeDeclare(
		n.Consumer.exch, // name of the exchange
		"direct",        // type
		true,            // durable
		false,           // delete when complete
		false,           // internal
		false,           // noWait
		nil,             // arguments
	); err != nil {
		return fmt.Errorf("Exchange Declare: %s", err)
	}

	log.Printf("declared Exchange, declaring Queue (%q)", n.Consumer.queue)
	queue, err := n.Consumer.channel.QueueDeclare(
		n.Consumer.queue, // name of the queue
		true,             // durable
		false,            // delete when usused
		false,            // exclusive
		false,            // noWait
		nil,              // arguments
	)
	if err != nil {
		return fmt.Errorf("Queue Declare: %s", err)
	}

	log.Printf("declared Queue (%q %d messages, %d consumers), binding to Exchange (key %q)",
		queue.Name, queue.Messages, queue.Consumers, n.Consumer.key)

	if err = n.Consumer.channel.QueueBind(
		queue.Name,      // name of the queue
		n.Consumer.key,  // bindingKey
		n.Consumer.exch, // sourceExchange
		false,           // noWait
		nil,             // arguments
	); err != nil {
		return fmt.Errorf("Queue Bind: %s", err)
	}

	log.Printf("Queue bound to Exchange, starting Consume (consumer tag %q)", n.Consumer.tag)
	deliveries, err := n.Consumer.channel.Consume(
		queue.Name,     // name
		n.Consumer.tag, // consumerTag,
		false,          // noAck
		false,          // exclusive
		false,          // noLocal
		false,          // noWait
		nil,            // arguments
	)
	if err != nil {
		return fmt.Errorf("Queue Consume: %s", err)
	}

	go n.consume(deliveries, n.Consumer.done)

	select {}
}

// Consume consumes messages off a channel provided by `Node.ConsumerLoop`
// This function blocks on tasks, but not when delivering
func (n *Node) consume(deliveries <-chan amqp.Delivery, done chan error) {
	for d := range deliveries {
		log.Printf("[%v] : %q received %q", d.DeliveryTag, n.Consumer.queue, d.Body)

		output, err := n.TaskManager.Consume(string(d.Body))
		if err != nil {
			log.Printf("[%v] : errors %q", d.DeliveryTag, err)

		}

		if len(output) > 0 {
			go func() {
				log.Printf("[%v] : responding with %q", d.DeliveryTag, output)

				if err := n.deliver(output); err != nil {
					log.Printf("[%v] : response errored: %q", d.DeliveryTag, err)

					d.Ack(false)
				} else {
					log.Printf("[%v] : responded", d.DeliveryTag)

					d.Ack(true)
				}
			}()
		} else {
			d.Ack(true)
		}
	}
	log.Printf("handle: deliveries channel closed")
	done <- nil
}

// Deliver turns a message into json and use a producer to send it
func (n *Node) deliver(message interface{}) error {
	j, err := json.Marshal(message)

	if err != nil {
		return err
	}

	return n.Producer.Send(j)
}
<|endoftext|>


<commit_before>package pages

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

	"github.com/datasektionen/taitan/anchor"

	log "github.com/Sirupsen/logrus"
	"github.com/russross/blackfriday"
)

// Resp is the response we serve for file queries.
type Resp struct {
	Title     string          `json:"title"`      // Human-readable title.
	Slug      string          `json:"slug"`       // URL-slug.
	UpdatedAt string          `json:"updated_at"` // Body update time.
	Image     string          `json:"image"`      // Path/URL/Placeholder to image.
	Body      string          `json:"body"`       // Main content of the page.
	Sidebar   string          `json:"sidebar"`    // The sidebar of the page.
	Anchors   []anchor.Anchor `json:"anchors"`    // The list of anchors to headers in the body.
}

// Load intializes a root directory and serves all sub-folders.
func Load(root string) (pages map[string]*Resp, err error) {
	var dirs []string
	err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
		// We only search for article directories.
		if !fi.IsDir() {
			return nil
		}
		// Ignore our .git folder.
		if fi.IsDir() && fi.Name() == ".git" {
			return filepath.SkipDir
		}
		dirs = append(dirs, path)
		return nil
	})
	if err != nil {
		return nil, err
	}
	return parseDirs(root, dirs)
}

// stripRoot removes root level of a directory.
// This is because when a user requests:
// `/sektionen/om-oss` the actual path is: `root/sektionen/om-oss`
func stripRoot(root string, dir string) string {
	return strings.Replace(dir, root, "/", 1)
}

// parseDirs parses each directory into a response. Returns a map from requested
// urls into responses.
func parseDirs(root string, dirs []string) (pages map[string]*Resp, err error) {
	pages = map[string]*Resp{}
	for _, dir := range dirs {
		r, err := parseDir(dir)
		if err != nil {
			return nil, err
		}
		pages[stripRoot(root, dir)] = r
		log.WithFields(log.Fields{
			"Resp": r,
			"dir":  dir,
		}).Debug("Our parsed response\n")
	}
	return pages, nil
}

// toHTML reads a markdown file and returns a HTML string.
func toHTML(filename string) (string, error) {
	buf, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	// Use standard HTML rendering.
	renderer := blackfriday.HtmlRenderer(blackfriday.HTML_USE_XHTML, "", "")
	// Parse markdown where all id's are created from the values inside
	// the element tag.
	buf = blackfriday.MarkdownOptions(buf, renderer, blackfriday.Options{
		Extensions: blackfriday.EXTENSION_AUTO_HEADER_IDS,
	})
	return string(buf), nil
}

// parseDir creates a response for a directory.
func parseDir(dir string) (*Resp, error) {
	log.WithField("dir", dir).Debug("Parsing directory:")

	// Our content files.
	bodyPath := filepath.Join(dir, "body.md")
	sidebarPath := filepath.Join(dir, "sidebar.md")

	// Parse markdown to HTML.
	body, err := toHTML(bodyPath)
	if err != nil {
		return nil, err
	}
	log.WithField("body", body).Debug("HTML of body.md")

	// Parse sidebar to HTML.
	sidebar, err := toHTML(sidebarPath)
	if err != nil {
		return nil, err
	}
	log.WithField("sidebar", sidebar).Debug("HTML of sidebar.md")

	// Parse modified at.
	fi, err := os.Stat(bodyPath)
	if err != nil {
		return nil, err
	}
	// Parse anchors in the body.
	anchs, err := anchor.Anchors(body)
	if err != nil {
		return nil, err
	}
	// Title of the page (first anchor value).
	title := ""
	if len(anchs) > 0 {
		title = anchs[0].Value
	}
	const iso8601DateTime = "2006-01-02T15:04:05Z"
	return &Resp{
		Title:     title,
		Slug:      filepath.Base(dir),
		UpdatedAt: fi.ModTime().Format(iso8601DateTime),
		Image:     "unimplemented",
		Body:      body,
		Sidebar:   sidebar,
		Anchors:   anchs,
	}, nil
}
<commit_msg>fix stripRoot<commit_after>package pages

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

	"github.com/datasektionen/taitan/anchor"

	log "github.com/Sirupsen/logrus"
	"github.com/russross/blackfriday"
)

// Resp is the response we serve for file queries.
type Resp struct {
	Title     string          `json:"title"`      // Human-readable title.
	Slug      string          `json:"slug"`       // URL-slug.
	UpdatedAt string          `json:"updated_at"` // Body update time.
	Image     string          `json:"image"`      // Path/URL/Placeholder to image.
	Body      string          `json:"body"`       // Main content of the page.
	Sidebar   string          `json:"sidebar"`    // The sidebar of the page.
	Anchors   []anchor.Anchor `json:"anchors"`    // The list of anchors to headers in the body.
}

// Load intializes a root directory and serves all sub-folders.
func Load(root string) (pages map[string]*Resp, err error) {
	var dirs []string
	err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
		// We only search for article directories.
		if !fi.IsDir() {
			return nil
		}
		// Ignore our .git folder.
		if fi.IsDir() && fi.Name() == ".git" {
			return filepath.SkipDir
		}
		dirs = append(dirs, path)
		return nil
	})
	if err != nil {
		return nil, err
	}
	return parseDirs(root, dirs)
}

// stripRoot removes root level of a directory.
// This is because when a user requests:
// `/sektionen/om-oss` the actual path is: `root/sektionen/om-oss`
func stripRoot(root string, dir string) string {
	return filepath.Clean(strings.Replace(dir, root, "/", 1))
}

// parseDirs parses each directory into a response. Returns a map from requested
// urls into responses.
func parseDirs(root string, dirs []string) (pages map[string]*Resp, err error) {
	pages = map[string]*Resp{}
	for _, dir := range dirs {
		r, err := parseDir(dir)
		if err != nil {
			return nil, err
		}
		pages[stripRoot(root, dir)] = r
		log.WithFields(log.Fields{
			"Resp": r,
			"dir":  dir,
		}).Debug("Our parsed response\n")
	}
	return pages, nil
}

// toHTML reads a markdown file and returns a HTML string.
func toHTML(filename string) (string, error) {
	buf, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	// Use standard HTML rendering.
	renderer := blackfriday.HtmlRenderer(blackfriday.HTML_USE_XHTML, "", "")
	// Parse markdown where all id's are created from the values inside
	// the element tag.
	buf = blackfriday.MarkdownOptions(buf, renderer, blackfriday.Options{
		Extensions: blackfriday.EXTENSION_AUTO_HEADER_IDS,
	})
	return string(buf), nil
}

// parseDir creates a response for a directory.
func parseDir(dir string) (*Resp, error) {
	log.WithField("dir", dir).Debug("Parsing directory:")

	// Our content files.
	bodyPath := filepath.Join(dir, "body.md")
	sidebarPath := filepath.Join(dir, "sidebar.md")

	// Parse markdown to HTML.
	body, err := toHTML(bodyPath)
	if err != nil {
		return nil, err
	}
	log.WithField("body", body).Debug("HTML of body.md")

	// Parse sidebar to HTML.
	sidebar, err := toHTML(sidebarPath)
	if err != nil {
		return nil, err
	}
	log.WithField("sidebar", sidebar).Debug("HTML of sidebar.md")

	// Parse modified at.
	fi, err := os.Stat(bodyPath)
	if err != nil {
		return nil, err
	}
	// Parse anchors in the body.
	anchs, err := anchor.Anchors(body)
	if err != nil {
		return nil, err
	}
	// Title of the page (first anchor value).
	title := ""
	if len(anchs) > 0 {
		title = anchs[0].Value
	}
	const iso8601DateTime = "2006-01-02T15:04:05Z"
	return &Resp{
		Title:     title,
		Slug:      filepath.Base(dir),
		UpdatedAt: fi.ModTime().Format(iso8601DateTime),
		Image:     "unimplemented",
		Body:      body,
		Sidebar:   sidebar,
		Anchors:   anchs,
	}, nil
}
<|endoftext|>