<commit_before>package stripe

import (
	"encoding/json"

	"fmt"
	"net/url"
)

// CardBrand is the list of allowed values for the card's brand.
// Allowed values are "Unknown", "Visa", "American Express", "MasterCard", "Discover"
// "JCB", "Diners Club".
type CardBrand string

// Verification is the list of allowed verification responses.
// Allowed values are "pass", "fail", "unchecked", "unavailabe".
type Verification string

// CardFunding is the list of allowed values for the card's funding.
// Allowed values are "credit", "debit", "prepaid", "unknown".
type CardFunding string

// CardParams is the set of parameters that can be used when creating or updating a card.
// For more details see https://stripe.com/docs/api#create_card and https://stripe.com/docs/api#update_card.
type CardParams struct {
	Params
	Token                                         string
	Default                                       bool
	Account, Customer, Recipient                  string
	Name, Number, Month, Year, CVC                string
	Address1, Address2, City, State, Zip, Country string
}

// CardListParams is the set of parameters that can be used when listing cards.
// For more details see https://stripe.com/docs/api#list_cards.
type CardListParams struct {
	ListParams
	Account, Customer, Recipient string
}

// Card is the resource representing a Stripe credit/debit card.
// For more details see https://stripe.com/docs/api#cards.
type Card struct {
	ID            string            `json:"id"`
	Month         uint8             `json:"exp_month"`
	Year          uint16            `json:"exp_year"`
	Fingerprint   string            `json:"fingerprint"`
	Funding       CardFunding       `json:"funding"`
	IIN           string            `json:"iin"`
	Issuer        string            `json:"issuer"`
	Description   string            `json:"description"`
	LastFour      string            `json:"last4"`
	Brand         CardBrand         `json:"brand"`
	Default       bool              `json:"default_for_currency"`
	City          string            `json:"address_city"`
	Country       string            `json:"address_country"`
	Address1      string            `json:"address_line1"`
	Address1Check Verification      `json:"address_line1_check"`
	Address2      string            `json:"address_line2"`
	State         string            `json:"address_state"`
	Zip           string            `json:"address_zip"`
	ZipCheck      Verification      `json:"address_zip_check"`
	CardCountry   string            `json:"country"`
	Customer      *Customer         `json:"customer"`
	CVCCheck      Verification      `json:"cvc_check"`
	Meta          map[string]string `json:"metadata"`
	Name          string            `json:"name"`
	Recipient     *Recipient        `json:"recipient"`
	DynLastFour   string            `json:"dynamic_last4"`
	Deleted       bool              `json:"deleted"`
}

// CardList is a list object for cards.
type CardList struct {
	ListMeta
	Values []*Card `json:"data"`
}

// AppendDetails adds the card's details to the query string values.
// When creating a new card, the parameters are passed as a dictionary, but
// on updates they are simply the parameter name.
func (c *CardParams) AppendDetails(values *url.Values, creating bool) {
	if creating {
		if len(c.Token) > 0 && len(c.Account) > 0 {
			values.Add("external_account", c.Token)
		} else if len(c.Token) > 0 {
			values.Add("card", c.Token)
		} else {
			values.Add("card[object]", "card")
			values.Add("card[number]", c.Number)

			if len(c.CVC) > 0 {
				values.Add("card[cvc]", c.CVC)
			}
		}
	}

	if len(c.Month) > 0 {
		if creating {
			values.Add("card[exp_month]", c.Month)
		} else {
			values.Add("exp_month", c.Month)
		}
	}

	if len(c.Year) > 0 {
		if creating {
			values.Add("card[exp_year]", c.Year)
		} else {
			values.Add("exp_year", c.Year)
		}
	}

	if len(c.Name) > 0 {
		if creating {
			values.Add("card[name]", c.Name)
		} else {
			values.Add("name", c.Name)
		}
	}

	if len(c.Address1) > 0 {
		if creating {
			values.Add("card[address_line1]", c.Address1)
		} else {
			values.Add("address_line1", c.Address1)
		}
	}

	if len(c.Address2) > 0 {
		if creating {
			values.Add("card[address_line2]", c.Address2)
		} else {
			values.Add("address_line2", c.Address2)
		}
	}

	if len(c.City) > 0 {
		if creating {
			values.Add("card[address_city]", c.City)
		} else {
			values.Add("address_city", c.City)
		}
	}

	if len(c.State) > 0 {
		if creating {
			values.Add("card[address_state]", c.State)
		} else {
			values.Add("address_state", c.State)
		}
	}

	if len(c.Zip) > 0 {
		if creating {
			values.Add("card[address_zip]", c.Zip)
		} else {
			values.Add("address_zip", c.Zip)
		}
	}

	if len(c.Country) > 0 {
		if creating {
			values.Add("card[address_country]", c.Country)
		} else {
			values.Add("address_country", c.Country)
		}
	}
}

// Display human readable representation of a Card.
func (c *Card) Display() string {
	return fmt.Sprintf("%s ending in %s", c.Brand, c.LastFour)
}

// UnmarshalJSON handles deserialization of a Card.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *Card) UnmarshalJSON(data []byte) error {
	type card Card
	var cc card
	err := json.Unmarshal(data, &cc)
	if err == nil {
		*c = Card(cc)
	} else {
		// the id is surrounded by "\" characters, so strip them
		c.ID = string(data[1 : len(data)-1])
	}

	return nil
}
<commit_msg>Add comments for internal fields<commit_after>package stripe

import (
	"encoding/json"

	"fmt"
	"net/url"
)

// CardBrand is the list of allowed values for the card's brand.
// Allowed values are "Unknown", "Visa", "American Express", "MasterCard", "Discover"
// "JCB", "Diners Club".
type CardBrand string

// Verification is the list of allowed verification responses.
// Allowed values are "pass", "fail", "unchecked", "unavailabe".
type Verification string

// CardFunding is the list of allowed values for the card's funding.
// Allowed values are "credit", "debit", "prepaid", "unknown".
type CardFunding string

// CardParams is the set of parameters that can be used when creating or updating a card.
// For more details see https://stripe.com/docs/api#create_card and https://stripe.com/docs/api#update_card.
type CardParams struct {
	Params
	Token                                         string
	Default                                       bool
	Account, Customer, Recipient                  string
	Name, Number, Month, Year, CVC                string
	Address1, Address2, City, State, Zip, Country string
}

// CardListParams is the set of parameters that can be used when listing cards.
// For more details see https://stripe.com/docs/api#list_cards.
type CardListParams struct {
	ListParams
	Account, Customer, Recipient string
}

// Card is the resource representing a Stripe credit/debit card.
// For more details see https://stripe.com/docs/api#cards.
type Card struct {
	ID            string            `json:"id"`
	Month         uint8             `json:"exp_month"`
	Year          uint16            `json:"exp_year"`
	Fingerprint   string            `json:"fingerprint"`
	Funding       CardFunding       `json:"funding"`
	LastFour      string            `json:"last4"`
	Brand         CardBrand         `json:"brand"`
	Default       bool              `json:"default_for_currency"`
	City          string            `json:"address_city"`
	Country       string            `json:"address_country"`
	Address1      string            `json:"address_line1"`
	Address1Check Verification      `json:"address_line1_check"`
	Address2      string            `json:"address_line2"`
	State         string            `json:"address_state"`
	Zip           string            `json:"address_zip"`
	ZipCheck      Verification      `json:"address_zip_check"`
	CardCountry   string            `json:"country"`
	Customer      *Customer         `json:"customer"`
	CVCCheck      Verification      `json:"cvc_check"`
	Meta          map[string]string `json:"metadata"`
	Name          string            `json:"name"`
	Recipient     *Recipient        `json:"recipient"`
	DynLastFour   string            `json:"dynamic_last4"`
	Deleted       bool              `json:"deleted"`

	// Description is a succinct summary of the card's information.
	//
	// Please note that this field is for internal use only and is not returned
	// as part of standard API requests.
	Description string `json:"description"`

	// IIN is the card's "Issuer Identification Number".
	//
	// Please note that this field is for internal use only and is not returned
	// as part of standard API requests.
	IIN string `json:"iin"`

	// Issuer is a bank or financial institution that provides the card.
	//
	// Please note that this field is for internal use only and is not returned
	// as part of standard API requests.
	Issuer string `json:"issuer"`
}

// CardList is a list object for cards.
type CardList struct {
	ListMeta
	Values []*Card `json:"data"`
}

// AppendDetails adds the card's details to the query string values.
// When creating a new card, the parameters are passed as a dictionary, but
// on updates they are simply the parameter name.
func (c *CardParams) AppendDetails(values *url.Values, creating bool) {
	if creating {
		if len(c.Token) > 0 && len(c.Account) > 0 {
			values.Add("external_account", c.Token)
		} else if len(c.Token) > 0 {
			values.Add("card", c.Token)
		} else {
			values.Add("card[object]", "card")
			values.Add("card[number]", c.Number)

			if len(c.CVC) > 0 {
				values.Add("card[cvc]", c.CVC)
			}
		}
	}

	if len(c.Month) > 0 {
		if creating {
			values.Add("card[exp_month]", c.Month)
		} else {
			values.Add("exp_month", c.Month)
		}
	}

	if len(c.Year) > 0 {
		if creating {
			values.Add("card[exp_year]", c.Year)
		} else {
			values.Add("exp_year", c.Year)
		}
	}

	if len(c.Name) > 0 {
		if creating {
			values.Add("card[name]", c.Name)
		} else {
			values.Add("name", c.Name)
		}
	}

	if len(c.Address1) > 0 {
		if creating {
			values.Add("card[address_line1]", c.Address1)
		} else {
			values.Add("address_line1", c.Address1)
		}
	}

	if len(c.Address2) > 0 {
		if creating {
			values.Add("card[address_line2]", c.Address2)
		} else {
			values.Add("address_line2", c.Address2)
		}
	}

	if len(c.City) > 0 {
		if creating {
			values.Add("card[address_city]", c.City)
		} else {
			values.Add("address_city", c.City)
		}
	}

	if len(c.State) > 0 {
		if creating {
			values.Add("card[address_state]", c.State)
		} else {
			values.Add("address_state", c.State)
		}
	}

	if len(c.Zip) > 0 {
		if creating {
			values.Add("card[address_zip]", c.Zip)
		} else {
			values.Add("address_zip", c.Zip)
		}
	}

	if len(c.Country) > 0 {
		if creating {
			values.Add("card[address_country]", c.Country)
		} else {
			values.Add("address_country", c.Country)
		}
	}
}

// Display human readable representation of a Card.
func (c *Card) Display() string {
	return fmt.Sprintf("%s ending in %s", c.Brand, c.LastFour)
}

// UnmarshalJSON handles deserialization of a Card.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (c *Card) UnmarshalJSON(data []byte) error {
	type card Card
	var cc card
	err := json.Unmarshal(data, &cc)
	if err == nil {
		*c = Card(cc)
	} else {
		// the id is surrounded by "\" characters, so strip them
		c.ID = string(data[1 : len(data)-1])
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"
	"strings"
	"syscall"

	"bazil.org/fuse"
	"bazil.org/fuse/fs"
)

// SubDir represents a directory in the filesystem
type SubDir struct {
	ID      int64
	Root    bool
}

// Attr retrives the attributes for this SubDir
func (SubDir) Attr() fuse.Attr {
	return fuse.Attr{
		Mode: os.ModeDir | 0555,
	}
}

// Create does nothing, because subfs is read-only
func (SubDir) Create(req *fuse.CreateRequest, res *fuse.CreateResponse, intr fs.Intr) (fs.Node, fs.Handle, fuse.Error) {
	return nil, nil, fuse.Errno(syscall.EROFS)
}

// Fsync does nothing, because subfs is read-only
func (SubDir) Fsync(req *fuse.FsyncRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Link does nothing, because subfs is read-only
func (SubDir) Link(req *fuse.LinkRequest, node fs.Node, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}

// Lookup scans the current directory for matching files or directories
func (d SubDir) Lookup(name string, intr fs.Intr) (fs.Node, fuse.Error) {
	// Lookup directory by name
	if dir, ok := nameToDir[name]; ok {
		return dir, nil
	}

	// Lookup file by name
	if f, ok := nameToFile[name]; ok {
		return f, nil
	}

	// File not found
	return nil, fuse.ENOENT
}

// ReadDir returns a list of directory entries depending on the current path
func (d SubDir) ReadDir(intr fs.Intr) ([]fuse.Dirent, fuse.Error) {
	// List of directory entries to return
	directories := make([]fuse.Dirent, 0)

	// If at root of filesystem, fetch indexes
	if d.Root {
		// If empty, wait for indexes to be available
		if len(indexCache) == 0 {
			<-indexChan
		}

		// Get index from cache
		index := indexCache

		// Iterate indices
		for _, i := range index {
			// Iterate all artists
			for _, a := range i.Artist {
				// Map artist's name to directory
				nameToDir[a.Name] = SubDir{
					ID:   a.ID,
					Root: false,
				}

				// Create a directory entry
				dir := fuse.Dirent{
					Name: a.Name,
					Type: fuse.DT_Dir,
				}

				// Append entry
				directories = append(directories, dir)
			}
		}

		return directories, nil
	}

	// Not at filesystem root, so get this directory's contents
	content, err := subsonic.GetMusicDirectory(d.ID)
	if err != nil {
		log.Printf("subfs: failed to retrieve directory %d: %s", d.ID, err.Error())
		return nil, fuse.ENOENT
	}

	// Check for available cover art IDs
	coverArt := make([]int64, 0)

	// Check if an ID is unique to a slice of IDs
	unique := func(id int64, slice []int64) bool {
		// Automatically reject ID of 0
		if id == 0 {
			return false
		}

		// Iterate the slice
		for _, item := range slice {
			// If there's a match, not unique
			if id == item {
				return false
			}
		}

		// No matches, unique item
		return true
	}

	// List of bad characters which should be replaced in filenames
	badChars := []string{"/", "\\"}

	// Iterate all returned directories
	for _, dir := range content.Directories {
		// Check for any characters which may cause trouble with filesystem display
		for _, b := range badChars {
			dir.Title = strings.Replace(dir.Title, b, "_", -1)
		}

		// Create a directory entry
		entry := fuse.Dirent{
			Name: dir.Title,
			Type: fuse.DT_Dir,
		}

		// Add SubDir directory to lookup map
		nameToDir[dir.Title] = SubDir{
			ID:   dir.ID,
			Root: false,
		}

		// Check for cover art
		if unique(dir.CoverArt, coverArt) {
			coverArt = append(coverArt, dir.CoverArt)
		}

		// Append to list
		directories = append(directories, entry)
	}

	// Iterate all returned audio
	for _, a := range content.Audio {

		// Check for lossless and lossy transcode
		transcodes := []struct {
			suffix string
			size   int64
		}{
			{a.Suffix, a.Size},
			{a.TranscodedSuffix, 0},
		}

		for _, t := range transcodes {
			// If suffix is empty (source is lossy), skip this file
			if t.suffix == "" {
				continue
			}

			// Mark file as lossless by default
			lossless := true

			// If size is empty (transcode to lossy), estimate it and mark as lossy
			if t.size == 0 {
				lossless = false

				// Since we have no idea what Subsonic's transcoding settings are, we will estimate
				// using MP3 CBR 320 as our benchmark, being that it will likely over-estimate
				// Thanks: http://www.jeffreysward.com/editorials/mp3size.htm
				t.size = ((a.DurationRaw * 320) / 8) * 1024
			}

			// Predefined audio filename format
			audioFormat := fmt.Sprintf("%02d - %s - %s.%s", a.Track, a.Artist, a.Title, t.suffix)

			// Check for any characters which may cause trouble with filesystem display
			for _, b := range badChars {
				audioFormat = strings.Replace(audioFormat, b, "_", -1)
			}

			// Create a directory entry
			dir := fuse.Dirent{
				Name: audioFormat,
				Type: fuse.DT_File,
			}

			// Add SubFile file to lookup map
			nameToFile[dir.Name] = SubFile{
				ID:       a.ID,
				Created:  a.Created,
				FileName: audioFormat,
				IsVideo:  false,
				Lossless: lossless,
				Size:     t.size,
			}

			// Check for cover art
			if unique(a.CoverArt, coverArt) {
				coverArt = append(coverArt, a.CoverArt)
			}

			// Append to list
			directories = append(directories, dir)
		}
	}

	// Iterate all returned video
	for _, v := range content.Video {
		// Predefined video filename format
		videoFormat := fmt.Sprintf("%s.%s", v.Title, v.Suffix)

		// Check for any characters which may cause trouble with filesystem display
		for _, b := range badChars {
			videoFormat = strings.Replace(videoFormat, b, "_", -1)
		}

		// Create a directory entry
		dir := fuse.Dirent{
			Name: videoFormat,
			Type: fuse.DT_File,
		}

		// Add SubFile file to lookup map
		nameToFile[dir.Name] = SubFile{
			ID:       v.ID,
			Created:  v.Created,
			FileName: videoFormat,
			Size:     v.Size,
			IsVideo:  true,
		}

		// Check for cover art
		if unique(v.CoverArt, coverArt) {
			coverArt = append(coverArt, v.CoverArt)
		}

		// Append to list
		directories = append(directories, dir)
	}

	// Iterate all cover art
	for _, c := range coverArt {
		coverArtFormat := fmt.Sprintf("%d.jpg", c)

		// Create a directory entry
		dir := fuse.Dirent{
			Name: coverArtFormat,
			Type: fuse.DT_File,
		}

		// Add SubFile file to lookup map
		nameToFile[dir.Name] = SubFile{
			ID:       c,
			FileName: coverArtFormat,
			IsArt:    true,
		}

		// Append to list
		directories = append(directories, dir)
	}

	// Return all directory entries
	return directories, nil
}

// Mkdir does nothing, because subfs is read-only
func (SubDir) Mkdir(req *fuse.MkdirRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}

// Mknod does nothing, because subfs is read-only
func (SubDir) Mknod(req *fuse.MknodRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}

// Remove does nothing, because subfs is read-only
func (SubDir) Remove(req *fuse.RemoveRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Removexattr does nothing, because subfs is read-only
func (SubDir) Removexattr(req *fuse.RemovexattrRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Rename does nothing, because subfs is read-only
func (SubDir) Rename(req *fuse.RenameRequest, node fs.Node, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Setattr does nothing, because subfs is read-only
func (SubDir) Setattr(req *fuse.SetattrRequest, res *fuse.SetattrResponse, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Setxattr does nothing, because subfs is read-only
func (SubDir) Setxattr(req *fuse.SetxattrRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Symlink does nothing, because subfs is read-only
func (SubDir) Symlink(req *fuse.SymlinkRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}
<commit_msg>Replace unique slice with goset set<commit_after>package main

import (
	"fmt"
	"log"
	"os"
	"strings"
	"syscall"

	"bazil.org/fuse"
	"bazil.org/fuse/fs"
	"github.com/mdlayher/goset"
)

// SubDir represents a directory in the filesystem
type SubDir struct {
	ID      int64
	Root    bool
}

// Attr retrives the attributes for this SubDir
func (SubDir) Attr() fuse.Attr {
	return fuse.Attr{
		Mode: os.ModeDir | 0555,
	}
}

// Create does nothing, because subfs is read-only
func (SubDir) Create(req *fuse.CreateRequest, res *fuse.CreateResponse, intr fs.Intr) (fs.Node, fs.Handle, fuse.Error) {
	return nil, nil, fuse.Errno(syscall.EROFS)
}

// Fsync does nothing, because subfs is read-only
func (SubDir) Fsync(req *fuse.FsyncRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Link does nothing, because subfs is read-only
func (SubDir) Link(req *fuse.LinkRequest, node fs.Node, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}

// Lookup scans the current directory for matching files or directories
func (d SubDir) Lookup(name string, intr fs.Intr) (fs.Node, fuse.Error) {
	// Lookup directory by name
	if dir, ok := nameToDir[name]; ok {
		return dir, nil
	}

	// Lookup file by name
	if f, ok := nameToFile[name]; ok {
		return f, nil
	}

	// File not found
	return nil, fuse.ENOENT
}

// ReadDir returns a list of directory entries depending on the current path
func (d SubDir) ReadDir(intr fs.Intr) ([]fuse.Dirent, fuse.Error) {
	// List of directory entries to return
	directories := make([]fuse.Dirent, 0)

	// If at root of filesystem, fetch indexes
	if d.Root {
		// If empty, wait for indexes to be available
		if len(indexCache) == 0 {
			<-indexChan
		}

		// Get index from cache
		index := indexCache

		// Iterate indices
		for _, i := range index {
			// Iterate all artists
			for _, a := range i.Artist {
				// Map artist's name to directory
				nameToDir[a.Name] = SubDir{
					ID:   a.ID,
					Root: false,
				}

				// Create a directory entry
				dir := fuse.Dirent{
					Name: a.Name,
					Type: fuse.DT_Dir,
				}

				// Append entry
				directories = append(directories, dir)
			}
		}

		return directories, nil
	}

	// Not at filesystem root, so get this directory's contents
	content, err := subsonic.GetMusicDirectory(d.ID)
	if err != nil {
		log.Printf("subfs: failed to retrieve directory %d: %s", d.ID, err.Error())
		return nil, fuse.ENOENT
	}

	// Check for unique, available cover art IDs
	coverArt := set.New()

	// List of bad characters which should be replaced in filenames
	badChars := []string{"/", "\\"}

	// Iterate all returned directories
	for _, dir := range content.Directories {
		// Check for any characters which may cause trouble with filesystem display
		for _, b := range badChars {
			dir.Title = strings.Replace(dir.Title, b, "_", -1)
		}

		// Create a directory entry
		entry := fuse.Dirent{
			Name: dir.Title,
			Type: fuse.DT_Dir,
		}

		// Add SubDir directory to lookup map
		nameToDir[dir.Title] = SubDir{
			ID:   dir.ID,
			Root: false,
		}

		// Check for cover art
		coverArt.Add(dir.CoverArt)

		// Append to list
		directories = append(directories, entry)
	}

	// Iterate all returned audio
	for _, a := range content.Audio {

		// Check for lossless and lossy transcode
		transcodes := []struct {
			suffix string
			size   int64
		}{
			{a.Suffix, a.Size},
			{a.TranscodedSuffix, 0},
		}

		for _, t := range transcodes {
			// If suffix is empty (source is lossy), skip this file
			if t.suffix == "" {
				continue
			}

			// Mark file as lossless by default
			lossless := true

			// If size is empty (transcode to lossy), estimate it and mark as lossy
			if t.size == 0 {
				lossless = false

				// Since we have no idea what Subsonic's transcoding settings are, we will estimate
				// using MP3 CBR 320 as our benchmark, being that it will likely over-estimate
				// Thanks: http://www.jeffreysward.com/editorials/mp3size.htm
				t.size = ((a.DurationRaw * 320) / 8) * 1024
			}

			// Predefined audio filename format
			audioFormat := fmt.Sprintf("%02d - %s - %s.%s", a.Track, a.Artist, a.Title, t.suffix)

			// Check for any characters which may cause trouble with filesystem display
			for _, b := range badChars {
				audioFormat = strings.Replace(audioFormat, b, "_", -1)
			}

			// Create a directory entry
			dir := fuse.Dirent{
				Name: audioFormat,
				Type: fuse.DT_File,
			}

			// Add SubFile file to lookup map
			nameToFile[dir.Name] = SubFile{
				ID:       a.ID,
				Created:  a.Created,
				FileName: audioFormat,
				IsVideo:  false,
				Lossless: lossless,
				Size:     t.size,
			}

			// Check for cover art
			coverArt.Add(a.CoverArt)

			// Append to list
			directories = append(directories, dir)
		}
	}

	// Iterate all returned video
	for _, v := range content.Video {
		// Predefined video filename format
		videoFormat := fmt.Sprintf("%s.%s", v.Title, v.Suffix)

		// Check for any characters which may cause trouble with filesystem display
		for _, b := range badChars {
			videoFormat = strings.Replace(videoFormat, b, "_", -1)
		}

		// Create a directory entry
		dir := fuse.Dirent{
			Name: videoFormat,
			Type: fuse.DT_File,
		}

		// Add SubFile file to lookup map
		nameToFile[dir.Name] = SubFile{
			ID:       v.ID,
			Created:  v.Created,
			FileName: videoFormat,
			Size:     v.Size,
			IsVideo:  true,
		}

		// Check for cover art
		coverArt.Add(v.CoverArt)

		// Append to list
		directories = append(directories, dir)
	}

	// Iterate all cover art
	for _, e := range coverArt.Enumerate() {
		// Type-hint to int64
		c := e.(int64)
		coverArtFormat := fmt.Sprintf("%d.jpg", c)

		// Create a directory entry
		dir := fuse.Dirent{
			Name: coverArtFormat,
			Type: fuse.DT_File,
		}

		// Add SubFile file to lookup map
		nameToFile[dir.Name] = SubFile{
			ID:       c,
			FileName: coverArtFormat,
			IsArt:    true,
		}

		// Append to list
		directories = append(directories, dir)
	}

	// Return all directory entries
	return directories, nil
}

// Mkdir does nothing, because subfs is read-only
func (SubDir) Mkdir(req *fuse.MkdirRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}

// Mknod does nothing, because subfs is read-only
func (SubDir) Mknod(req *fuse.MknodRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}

// Remove does nothing, because subfs is read-only
func (SubDir) Remove(req *fuse.RemoveRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Removexattr does nothing, because subfs is read-only
func (SubDir) Removexattr(req *fuse.RemovexattrRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Rename does nothing, because subfs is read-only
func (SubDir) Rename(req *fuse.RenameRequest, node fs.Node, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Setattr does nothing, because subfs is read-only
func (SubDir) Setattr(req *fuse.SetattrRequest, res *fuse.SetattrResponse, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Setxattr does nothing, because subfs is read-only
func (SubDir) Setxattr(req *fuse.SetxattrRequest, intr fs.Intr) fuse.Error {
	return fuse.Errno(syscall.EROFS)
}

// Symlink does nothing, because subfs is read-only
func (SubDir) Symlink(req *fuse.SymlinkRequest, intr fs.Intr) (fs.Node, fuse.Error) {
	return nil, fuse.Errno(syscall.EROFS)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/lixin9311/simplevpn/tap"
	"io"
	"log"
	"net"
	"sync"
)

const (
	MaxPacketSize = 1600
)

var (
	hub           = &Hub{Clients: map[tap.HwAddr]*Client{}, input: ether_buffer}
	BroadcastAddr = tap.HwAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
	ether_buffer  = make(chan []byte, 4000)
)

type Hub struct {
	Clients        map[tap.HwAddr]*Client
	Packet_clients map[net.Addr]*Client
	input          chan []byte
	sync.Mutex
}

func (h *Hub) Init() {
	go func() {
		var dst tap.HwAddr
		var src tap.HwAddr
		for buf := range h.input {
			copy(dst[:], buf[:6])
			copy(src[:], buf[6:12])
			if dst == BroadcastAddr {
				go h.Broadcast(buf, src)
			} else {
				go h.Unicast(buf, dst)
			}
		}
	}()
}

func (h *Hub) Connect(client *Client) {
	h.Lock()
	defer h.Unlock()
	log.Printf("Client with MacAddr %s connected.\n", client.MacAddr)
	h.Clients[client.MacAddr] = client
	if client.is_packet {
		h.Packet_clients[client.remoteAddr] = client
	}
}

func (h *Hub) Disonnect(client *Client) {
	h.Lock()
	defer h.Unlock()
	log.Printf("Client with MacAddr %s disconnected.\n", client.MacAddr)
	delete(h.Clients, client.MacAddr)
	if client.is_packet {
		delete(h.Packet_clients, client.remoteAddr)
	}
}

func (h *Hub) Broadcast(data []byte, src tap.HwAddr) {
	h.Lock()
	defer h.Unlock()
	for k, v := range h.Clients {
		if k == src {
			continue
		}
		go v.Write(data)
	}
}

func (h *Hub) Unicast(data []byte, addr tap.HwAddr) (n int, err error) {
	h.Lock()
	client_u, ok_u := h.Clients[addr]
	client_s, ok_s := h.Clients[BroadcastAddr]
	h.Unlock()
	if ok_u {
		n, err = client_u.Write(data)
	}
	if ok_s {
		go client_s.Write(data)
	}
	return
}

type Client struct {
	MacAddr    tap.HwAddr
	Conn       io.ReadWriter
	is_packet  bool
	PacketConn net.PacketConn
	input      chan []byte
	remoteAddr net.Addr
}

func (c *Client) Init() {
	go func() {
		defer hub.Disonnect(c)
		for {
			buf := make([]byte, MaxPacketSize)
			n, err := c.Read(buf)
			if err != nil {
				log.Printf("Err when read from client[%s]:%v\n", c.MacAddr, err)
				break
			}
			ether_buffer <- buf[:n]
		}
	}()
}

func (c *Client) Run() error {
	defer hub.Disonnect(c)
	for {
		buf := make([]byte, MaxPacketSize)
		n, err := c.Read(buf)
		if err != nil {
			log.Printf("Err when read from client[%s]:%v\n", c.MacAddr, err)
			return err
		}
		ether_buffer <- buf[:n]
	}
}

func (c *Client) Write(data []byte) (n int, err error) {
	if c.is_packet {
		n, err = c.PacketConn.WriteTo(data, c.remoteAddr)
	} else {
		n, err = c.Conn.Write(data)
	}
	return
}

func (c *Client) Read(data []byte) (n int, err error) {
	if c.is_packet {
		buf := <-c.input
		if len(data) < len(buf) {
			log.Println("Buffer too short:", len(buf))
			err = fmt.Errorf("Buffer too short")
			return
		}
		copy(data, buf)
		n = len(buf)
	} else {
		n, err = c.Conn.Read(data)
	}
	return
}
<commit_msg>Fix nil map.<commit_after>package main

import (
	"fmt"
	"github.com/lixin9311/simplevpn/tap"
	"io"
	"log"
	"net"
	"sync"
)

const (
	MaxPacketSize = 1600
)

var (
	hub           = &Hub{Clients: map[tap.HwAddr]*Client{}, input: ether_buffer, Packet_clients: map[net.Addr]*Client{}}
	BroadcastAddr = tap.HwAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
	ether_buffer  = make(chan []byte, 4000)
)

type Hub struct {
	Clients        map[tap.HwAddr]*Client
	Packet_clients map[net.Addr]*Client
	input          chan []byte
	sync.Mutex
}

func (h *Hub) Init() {
	go func() {
		var dst tap.HwAddr
		var src tap.HwAddr
		for buf := range h.input {
			copy(dst[:], buf[:6])
			copy(src[:], buf[6:12])
			if dst == BroadcastAddr {
				go h.Broadcast(buf, src)
			} else {
				go h.Unicast(buf, dst)
			}
		}
	}()
}

func (h *Hub) Connect(client *Client) {
	h.Lock()
	defer h.Unlock()
	log.Printf("Client with MacAddr %s connected.\n", client.MacAddr)
	h.Clients[client.MacAddr] = client
	if client.is_packet {
		h.Packet_clients[client.remoteAddr] = client
	}
}

func (h *Hub) Disonnect(client *Client) {
	h.Lock()
	defer h.Unlock()
	log.Printf("Client with MacAddr %s disconnected.\n", client.MacAddr)
	delete(h.Clients, client.MacAddr)
	if client.is_packet {
		delete(h.Packet_clients, client.remoteAddr)
	}
}

func (h *Hub) Broadcast(data []byte, src tap.HwAddr) {
	h.Lock()
	defer h.Unlock()
	for k, v := range h.Clients {
		if k == src {
			continue
		}
		go v.Write(data)
	}
}

func (h *Hub) Unicast(data []byte, addr tap.HwAddr) (n int, err error) {
	h.Lock()
	client_u, ok_u := h.Clients[addr]
	client_s, ok_s := h.Clients[BroadcastAddr]
	h.Unlock()
	if ok_u {
		n, err = client_u.Write(data)
	}
	if ok_s {
		go client_s.Write(data)
	}
	return
}

type Client struct {
	MacAddr    tap.HwAddr
	Conn       io.ReadWriter
	is_packet  bool
	PacketConn net.PacketConn
	input      chan []byte
	remoteAddr net.Addr
}

func (c *Client) Init() {
	go func() {
		defer hub.Disonnect(c)
		for {
			buf := make([]byte, MaxPacketSize)
			n, err := c.Read(buf)
			if err != nil {
				log.Printf("Err when read from client[%s]:%v\n", c.MacAddr, err)
				break
			}
			ether_buffer <- buf[:n]
		}
	}()
}

func (c *Client) Run() error {
	defer hub.Disonnect(c)
	for {
		buf := make([]byte, MaxPacketSize)
		n, err := c.Read(buf)
		if err != nil {
			log.Printf("Err when read from client[%s]:%v\n", c.MacAddr, err)
			return err
		}
		ether_buffer <- buf[:n]
	}
}

func (c *Client) Write(data []byte) (n int, err error) {
	if c.is_packet {
		n, err = c.PacketConn.WriteTo(data, c.remoteAddr)
	} else {
		n, err = c.Conn.Write(data)
	}
	return
}

func (c *Client) Read(data []byte) (n int, err error) {
	if c.is_packet {
		buf := <-c.input
		if len(data) < len(buf) {
			log.Println("Buffer too short:", len(buf))
			err = fmt.Errorf("Buffer too short")
			return
		}
		copy(data, buf)
		n = len(buf)
	} else {
		n, err = c.Conn.Read(data)
	}
	return
}
<|endoftext|>


<commit_before>package thermal

import (
	"log"
)

// Switch provides an api to create, manage, and use a Telehash switch instance
type Switch struct{}

func (*Switch) Init() {

	// basic initialization
	log.SetFlags(log.Ldate | log.Lmicroseconds)
	log.Println("Starting initialization of switch")

	// setup the cipher sets
	log.Println("Starting initialization of cipher sets")
	cpack := make(cipherPack)

	cpack["cs2a"] = new(cs2a)
	cpack["cs3a"] = new(cs3a)

	for csid, cset := range cpack {

		cset.init()

		id := cset.csid()
		log.Printf(" csid: %s :: %s\n", id, csid)

		id, fingerprint := cset.parts()
		log.Printf("parts: %s :: %s\n", id, fingerprint)

	}
	log.Println("Finished initialization of cipher sets")

	//
	log.Println("Finished initialization of switch")
	log.Println("Switch ready")

}
<commit_msg>minor adjustments to logging<commit_after>package thermal

import (
	"log"
)

// Switch provides an api to create, manage, and use a Telehash switch instance
type Switch struct{}

func (*Switch) Init() {

	// basic initialization
	log.SetFlags(log.Ldate | log.Lmicroseconds)
	log.Println("Starting initialization of switch")

	// setup the cipher sets
	log.Println("Starting initialization of cipher sets")
	cpack := make(cipherPack)

	cpack["cs2a"] = new(cs2a)
	cpack["cs3a"] = new(cs3a)

	for csid, cset := range cpack {

		log.Printf("Running init for %s\n", csid)
		cset.init()

		log.Printf(" csid: %s\n", cset.csid())

		id, fingerprint := cset.parts()
		log.Printf("parts: %s :: %s\n", id, fingerprint)

	}
	log.Println("Finished initialization of cipher sets")

	//
	log.Println("Finished initialization of switch")
	log.Println("Switch ready")

}
<|endoftext|>


<commit_before>package gorma

import (
	"fmt"
	"strings"

	"bitbucket.org/pkg/inflect"
	"github.com/goadesign/goa/design"
	"github.com/goadesign/goa/dslengine"
)

// NewRelationalFieldDefinition returns an initialized
// RelationalFieldDefinition.
func NewRelationalFieldDefinition() *RelationalFieldDefinition {
	m := &RelationalFieldDefinition{
		Mappings: make(map[string]*MapDefinition),
	}
	return m
}

// Context returns the generic definition name used in error messages.
func (f *RelationalFieldDefinition) Context() string {
	if f.FieldName != "" {
		return fmt.Sprintf("RelationalField %#v", f.FieldName)
	}
	return "unnamed RelationalField"
}

// DSL returns this object's DSL.
func (f *RelationalFieldDefinition) DSL() func() {
	return f.DefinitionDSL
}

// Children returns a slice of this objects children.
func (f RelationalFieldDefinition) Children() []dslengine.Definition {
	// no children yet
	return []dslengine.Definition{}
}

// Attribute implements the Container interface of the goa Attribute
// model.
func (f *RelationalFieldDefinition) Attribute() *design.AttributeDefinition {
	return f.a
}

// FieldDefinition returns the field's struct definition.
func (f *RelationalFieldDefinition) FieldDefinition() string {
	var comment string
	if f.Description != "" {
		comment = "// " + f.Description
	}
	def := fmt.Sprintf("%s\t%s %s %s\n", f.FieldName, goDatatype(f, true), tags(f), comment)
	return def
}

// Tags returns the sql and gorm struct tags for the Definition.
func (f *RelationalFieldDefinition) Tags() string {
	return tags(f)
}

// LowerName returns the field name as a lowercase string.
func (f *RelationalFieldDefinition) LowerName() string {
	return strings.ToLower(f.FieldName)
}

// Underscore returns the field name as a lowercase string in snake case.
func (f *RelationalFieldDefinition) Underscore() string {
	return inflect.Underscore(f.FieldName)
}
func goDatatype(f *RelationalFieldDefinition, includePtr bool) string {
	var ptr string
	if f.Nullable && includePtr {
		ptr = "*"
	}
	switch f.Datatype {
	case Boolean:
		return ptr + "bool"
	case Integer, BigInteger:
		return ptr + "int"
	case AutoInteger, AutoBigInteger:
		return ptr + "int " // sql/gorm tags later
	case Decimal, BigDecimal:
		return ptr + "float32"
	case String:
		return ptr + "string"
	case Text:
		return ptr + "string"
	case UUID:
		return ptr + "string" // what to do about UUIDS?
	case Timestamp, NullableTimestamp:
		return ptr + "time.Time"
	case BelongsTo:
		return ptr + "int"
	case HasMany:
		return fmt.Sprintf("[]%s", f.HasMany)
	case HasManyKey, HasOneKey:
		return ptr + "int"
	case HasOne:
		return fmt.Sprintf("%s", f.HasOne)
	default:

		if f.Many2Many != "" {
			return fmt.Sprintf("[]%s", f.Many2Many)
		}
	}

	return "UNKNOWN TYPE"
}

func tags(f *RelationalFieldDefinition) string {
	var sqltags []string
	if f.SQLTag != "" {
		sqltags = append(sqltags, f.SQLTag)
	}

	var gormtags []string
	if f.Alias != "" {
		gormtags = append(gormtags, "column:"+f.Alias)
	}
	if f.PrimaryKey {
		gormtags = append(gormtags, "primary_key")
	}
	if f.Many2Many != "" {
		p := strings.ToLower(f.Parent.ModelName)
		j := strings.ToLower(f.Many2Many)
		gormtags = append(gormtags, "many2many:"+p+"_"+j)
	}

	var tags []string
	if len(sqltags) > 0 {
		sqltag := "sql:\"" + strings.Join(sqltags, ";") + "\""
		tags = append(tags, sqltag)
	}
	if len(gormtags) > 0 {
		gormtag := "gorm:\"" + strings.Join(gormtags, ";") + "\""
		tags = append(tags, gormtag)
	}

	if len(tags) > 0 {
		return "`" + strings.Join(tags, " ") + "`"
	}
	return ""
}
<commit_msg>fix float bug<commit_after>package gorma

import (
	"fmt"
	"strings"

	"bitbucket.org/pkg/inflect"
	"github.com/goadesign/goa/design"
	"github.com/goadesign/goa/dslengine"
)

// NewRelationalFieldDefinition returns an initialized
// RelationalFieldDefinition.
func NewRelationalFieldDefinition() *RelationalFieldDefinition {
	m := &RelationalFieldDefinition{
		Mappings: make(map[string]*MapDefinition),
	}
	return m
}

// Context returns the generic definition name used in error messages.
func (f *RelationalFieldDefinition) Context() string {
	if f.FieldName != "" {
		return fmt.Sprintf("RelationalField %#v", f.FieldName)
	}
	return "unnamed RelationalField"
}

// DSL returns this object's DSL.
func (f *RelationalFieldDefinition) DSL() func() {
	return f.DefinitionDSL
}

// Children returns a slice of this objects children.
func (f RelationalFieldDefinition) Children() []dslengine.Definition {
	// no children yet
	return []dslengine.Definition{}
}

// Attribute implements the Container interface of the goa Attribute
// model.
func (f *RelationalFieldDefinition) Attribute() *design.AttributeDefinition {
	return f.a
}

// FieldDefinition returns the field's struct definition.
func (f *RelationalFieldDefinition) FieldDefinition() string {
	var comment string
	if f.Description != "" {
		comment = "// " + f.Description
	}
	def := fmt.Sprintf("%s\t%s %s %s\n", f.FieldName, goDatatype(f, true), tags(f), comment)
	return def
}

// Tags returns the sql and gorm struct tags for the Definition.
func (f *RelationalFieldDefinition) Tags() string {
	return tags(f)
}

// LowerName returns the field name as a lowercase string.
func (f *RelationalFieldDefinition) LowerName() string {
	return strings.ToLower(f.FieldName)
}

// Underscore returns the field name as a lowercase string in snake case.
func (f *RelationalFieldDefinition) Underscore() string {
	return inflect.Underscore(f.FieldName)
}
func goDatatype(f *RelationalFieldDefinition, includePtr bool) string {
	var ptr string
	if f.Nullable && includePtr {
		ptr = "*"
	}
	switch f.Datatype {
	case Boolean:
		return ptr + "bool"
	case Integer, BigInteger:
		return ptr + "int"
	case AutoInteger, AutoBigInteger:
		return ptr + "int " // sql/gorm tags later
	case Decimal:
		return ptr + "float32"
	case BigDecimal:
		return ptr + "float64"
	case String:
		return ptr + "string"
	case Text:
		return ptr + "string"
	case UUID:
		return ptr + "string" // what to do about UUIDS?
	case Timestamp, NullableTimestamp:
		return ptr + "time.Time"
	case BelongsTo:
		return ptr + "int"
	case HasMany:
		return fmt.Sprintf("[]%s", f.HasMany)
	case HasManyKey, HasOneKey:
		return ptr + "int"
	case HasOne:
		return fmt.Sprintf("%s", f.HasOne)
	default:

		if f.Many2Many != "" {
			return fmt.Sprintf("[]%s", f.Many2Many)
		}
	}

	return "UNKNOWN TYPE"
}

func tags(f *RelationalFieldDefinition) string {
	var sqltags []string
	if f.SQLTag != "" {
		sqltags = append(sqltags, f.SQLTag)
	}

	var gormtags []string
	if f.Alias != "" {
		gormtags = append(gormtags, "column:"+f.Alias)
	}
	if f.PrimaryKey {
		gormtags = append(gormtags, "primary_key")
	}
	if f.Many2Many != "" {
		p := strings.ToLower(f.Parent.ModelName)
		j := strings.ToLower(f.Many2Many)
		gormtags = append(gormtags, "many2many:"+p+"_"+j)
	}

	var tags []string
	if len(sqltags) > 0 {
		sqltag := "sql:\"" + strings.Join(sqltags, ";") + "\""
		tags = append(tags, sqltag)
	}
	if len(gormtags) > 0 {
		gormtag := "gorm:\"" + strings.Join(gormtags, ";") + "\""
		tags = append(tags, gormtag)
	}

	if len(tags) > 0 {
		return "`" + strings.Join(tags, " ") + "`"
	}
	return ""
}
<|endoftext|>


<commit_before>package fastly

import (
	"fmt"
	"sort"
	"time"
)

// Syslog represents a syslog response from the Fastly API.
type Syslog struct {
	ServiceID string `mapstructure:"service_id"`
	Version   string `mapstructure:"version"`

	Name              string     `mapstructure:"name"`
	Address           string     `mapstructure:"address"`
	Port              uint       `mapstructure:"port"`
	UseTLS            bool       `mapstructure:"use_tls"`
	TLSCACert         string     `mapstructure:"tls_ca_cert"`
	Token             string     `mapstructure:"token"`
	Format            string     `mapstructure:"format"`
	ResponseCondition string     `mapstructure:"response_condition"`
	CreatedAt         *time.Time `mapstructure:"created_at"`
	UpdatedAt         *time.Time `mapstructure:"updated_at"`
	DeletedAt         *time.Time `mapstructure:"deleted_at"`
}

// syslogsByName is a sortable list of syslogs.
type syslogsByName []*Syslog

// Len, Swap, and Less implement the sortable interface.
func (s syslogsByName) Len() int      { return len(s) }
func (s syslogsByName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s syslogsByName) Less(i, j int) bool {
	return s[i].Name < s[j].Name
}

// ListSyslogsInput is used as input to the ListSyslogs function.
type ListSyslogsInput struct {
	// Service is the ID of the service (required).
	Service string

	// Version is the specific configuration version (required).
	Version string
}

// ListSyslogs returns the list of syslogs for the configuration version.
func (c *Client) ListSyslogs(i *ListSyslogsInput) ([]*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog", i.Service, i.Version)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}

	var ss []*Syslog
	if err := decodeJSON(&ss, resp.Body); err != nil {
		return nil, err
	}
	sort.Stable(syslogsByName(ss))
	return ss, nil
}

// CreateSyslogInput is used as input to the CreateSyslog function.
type CreateSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	Name              string      `form:"name,omitempty"`
	Address           string      `form:"address,omitempty"`
	Port              uint        `form:"port,omitempty"`
	UseTLS            Compatibool `form:"use_tls,omitempty"`
	TLSCACert         string      `form:"tls_ca_cert,omitempty"`
	Token             string      `form:"token,omitempty"`
	Format            string      `form:"format,omitempty"`
	ResponseCondition string      `form:"response_condition,omitempty"`
}

// CreateSyslog creates a new Fastly syslog.
func (c *Client) CreateSyslog(i *CreateSyslogInput) (*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog", i.Service, i.Version)
	resp, err := c.PostForm(path, i, nil)
	if err != nil {
		return nil, err
	}

	var s *Syslog
	if err := decodeJSON(&s, resp.Body); err != nil {
		return nil, err
	}
	return s, nil
}

// GetSyslogInput is used as input to the GetSyslog function.
type GetSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	// Name is the name of the syslog to fetch.
	Name string
}

// GetSyslog gets the syslog configuration with the given parameters.
func (c *Client) GetSyslog(i *GetSyslogInput) (*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}

	var s *Syslog
	if err := decodeJSON(&s, resp.Body); err != nil {
		return nil, err
	}
	return s, nil
}

// UpdateSyslogInput is used as input to the UpdateSyslog function.
type UpdateSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	// Name is the name of the syslog to update.
	Name string

	NewName           string      `form:"name,omitempty"`
	Address           string      `form:"address,omitempty"`
	Port              uint        `form:"port,omitempty"`
	UseTLS            Compatibool `form:"use_tls,omitempty"`
	TLSCACert         string      `form:"tls_ca_cert,omitempty"`
	Token             string      `form:"token,omitempty"`
	Format            string      `form:"format,omitempty"`
	ResponseCondition string      `form:"response_condition,omitempty"`
}

// UpdateSyslog updates a specific syslog.
func (c *Client) UpdateSyslog(i *UpdateSyslogInput) (*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name)
	resp, err := c.PutForm(path, i, nil)
	if err != nil {
		return nil, err
	}

	var s *Syslog
	if err := decodeJSON(&s, resp.Body); err != nil {
		return nil, err
	}
	return s, nil
}

// DeleteSyslogInput is the input parameter to DeleteSyslog.
type DeleteSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	// Name is the name of the syslog to delete (required).
	Name string
}

// DeleteSyslog deletes the given syslog version.
func (c *Client) DeleteSyslog(i *DeleteSyslogInput) error {
	if i.Service == "" {
		return ErrMissingService
	}

	if i.Version == "" {
		return ErrMissingVersion
	}

	if i.Name == "" {
		return ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name)
	resp, err := c.Delete(path, nil)
	if err != nil {
		return err
	}

	var r *statusResp
	if err := decodeJSON(&r, resp.Body); err != nil {
		return err
	}
	if !r.Ok() {
		return fmt.Errorf("Not Ok")
	}
	return nil
}
<commit_msg>Add tls_hostname field to syslog structs.<commit_after>package fastly

import (
	"fmt"
	"sort"
	"time"
)

// Syslog represents a syslog response from the Fastly API.
type Syslog struct {
	ServiceID string `mapstructure:"service_id"`
	Version   string `mapstructure:"version"`

	Name              string     `mapstructure:"name"`
	Address           string     `mapstructure:"address"`
	Port              uint       `mapstructure:"port"`
	UseTLS            bool       `mapstructure:"use_tls"`
	TLSCACert         string     `mapstructure:"tls_ca_cert"`
	Token             string     `mapstructure:"token"`
	Format            string     `mapstructure:"format"`
	TLSHostname       string     `mapstructure:"tls_hostname"`
	ResponseCondition string     `mapstructure:"response_condition"`
	CreatedAt         *time.Time `mapstructure:"created_at"`
	UpdatedAt         *time.Time `mapstructure:"updated_at"`
	DeletedAt         *time.Time `mapstructure:"deleted_at"`
}

// syslogsByName is a sortable list of syslogs.
type syslogsByName []*Syslog

// Len, Swap, and Less implement the sortable interface.
func (s syslogsByName) Len() int      { return len(s) }
func (s syslogsByName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s syslogsByName) Less(i, j int) bool {
	return s[i].Name < s[j].Name
}

// ListSyslogsInput is used as input to the ListSyslogs function.
type ListSyslogsInput struct {
	// Service is the ID of the service (required).
	Service string

	// Version is the specific configuration version (required).
	Version string
}

// ListSyslogs returns the list of syslogs for the configuration version.
func (c *Client) ListSyslogs(i *ListSyslogsInput) ([]*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog", i.Service, i.Version)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}

	var ss []*Syslog
	if err := decodeJSON(&ss, resp.Body); err != nil {
		return nil, err
	}
	sort.Stable(syslogsByName(ss))
	return ss, nil
}

// CreateSyslogInput is used as input to the CreateSyslog function.
type CreateSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	Name              string      `form:"name,omitempty"`
	Address           string      `form:"address,omitempty"`
	Port              uint        `form:"port,omitempty"`
	UseTLS            Compatibool `form:"use_tls,omitempty"`
	TLSCACert         string      `form:"tls_ca_cert,omitempty"`
	Token             string      `form:"token,omitempty"`
	Format            string      `form:"format,omitempty"`
	TLSHostname       string      `form:"tls_hostname"`
	ResponseCondition string      `form:"response_condition,omitempty"`
}

// CreateSyslog creates a new Fastly syslog.
func (c *Client) CreateSyslog(i *CreateSyslogInput) (*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog", i.Service, i.Version)
	resp, err := c.PostForm(path, i, nil)
	if err != nil {
		return nil, err
	}

	var s *Syslog
	if err := decodeJSON(&s, resp.Body); err != nil {
		return nil, err
	}
	return s, nil
}

// GetSyslogInput is used as input to the GetSyslog function.
type GetSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	// Name is the name of the syslog to fetch.
	Name string
}

// GetSyslog gets the syslog configuration with the given parameters.
func (c *Client) GetSyslog(i *GetSyslogInput) (*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name)
	resp, err := c.Get(path, nil)
	if err != nil {
		return nil, err
	}

	var s *Syslog
	if err := decodeJSON(&s, resp.Body); err != nil {
		return nil, err
	}
	return s, nil
}

// UpdateSyslogInput is used as input to the UpdateSyslog function.
type UpdateSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	// Name is the name of the syslog to update.
	Name string

	NewName           string      `form:"name,omitempty"`
	Address           string      `form:"address,omitempty"`
	Port              uint        `form:"port,omitempty"`
	UseTLS            Compatibool `form:"use_tls,omitempty"`
	TLSCACert         string      `form:"tls_ca_cert,omitempty"`
	Token             string      `form:"token,omitempty"`
	Format            string      `form:"format,omitempty"`
	TLSHostname       string      `form:"tls_hostname"`
	ResponseCondition string      `form:"response_condition,omitempty"`
}

// UpdateSyslog updates a specific syslog.
func (c *Client) UpdateSyslog(i *UpdateSyslogInput) (*Syslog, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == "" {
		return nil, ErrMissingVersion
	}

	if i.Name == "" {
		return nil, ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name)
	resp, err := c.PutForm(path, i, nil)
	if err != nil {
		return nil, err
	}

	var s *Syslog
	if err := decodeJSON(&s, resp.Body); err != nil {
		return nil, err
	}
	return s, nil
}

// DeleteSyslogInput is the input parameter to DeleteSyslog.
type DeleteSyslogInput struct {
	// Service is the ID of the service. Version is the specific configuration
	// version. Both fields are required.
	Service string
	Version string

	// Name is the name of the syslog to delete (required).
	Name string
}

// DeleteSyslog deletes the given syslog version.
func (c *Client) DeleteSyslog(i *DeleteSyslogInput) error {
	if i.Service == "" {
		return ErrMissingService
	}

	if i.Version == "" {
		return ErrMissingVersion
	}

	if i.Name == "" {
		return ErrMissingName
	}

	path := fmt.Sprintf("/service/%s/version/%s/logging/syslog/%s", i.Service, i.Version, i.Name)
	resp, err := c.Delete(path, nil)
	if err != nil {
		return err
	}

	var r *statusResp
	if err := decodeJSON(&r, resp.Body); err != nil {
		return err
	}
	if !r.Ok() {
		return fmt.Errorf("Not Ok")
	}
	return nil
}
<|endoftext|>


<commit_before>package bundle

import (
	"path/filepath"

	"github.com/getantibody/antibody/project"
)

type zshBundle struct {
	Project project.Project
}

var zshGlobs = []string{"*.plugin.zsh", "*.zsh", "*.sh", "*.zsh-theme"}

func (bundle zshBundle) Get() (result string, err error) {
	if err := bundle.Project.Download(); err != nil {
		return result, err
	}
	for _, glob := range zshGlobs {
		files, _ := filepath.Glob(filepath.Join(bundle.Project.Folder(), glob))
		if files == nil {
			continue
		}
		for _, file := range files {
			return "source " + file, err
		}
	}
	return result, nil
}
<commit_msg>Allow many plugin.zsh files to be part of a plugin<commit_after>package bundle

import (
	"path/filepath"
	"strings"

	"github.com/getantibody/antibody/project"
)

type zshBundle struct {
	Project project.Project
}

var zshGlobs = []string{"*.plugin.zsh", "*.zsh", "*.sh", "*.zsh-theme"}

func (bundle zshBundle) Get() (result string, err error) {
	if err := bundle.Project.Download(); err != nil {
		return result, err
	}

	var lines []string
	for _, glob := range zshGlobs {
		files, _ := filepath.Glob(filepath.Join(bundle.Project.Folder(), glob))
		if files == nil {
			continue
		}
		for _, file := range files {
			lines = append(lines, "source "+file)
		}

		return strings.Join(lines, "\n"), err
	}

	return result, nil
}
<|endoftext|>


<commit_before>package mmm

import (
	"testing"
	"unsafe"
)

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

func TestBytes_BytesOf_bool(t *testing.T) {
	var v bool = true
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*bool)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for bool")
	}
}

func TestBytes_BytesOf_int(t *testing.T) {
	var v int = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int")
	}
}

func TestBytes_BytesOf_int8(t *testing.T) {
	var v int8 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int8)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int8")
	}
}

func TestBytes_BytesOf_int16(t *testing.T) {
	var v int16 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int16)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int16")
	}
}

func TestBytes_BytesOf_int32(t *testing.T) {
	var v int32 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int32)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int32")
	}
}

func TestBytes_BytesOf_int64(t *testing.T) {
	var v int64 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int64")
	}
}

func TestBytes_BytesOf_uint(t *testing.T) {
	var v uint = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint")
	}
}

func TestBytes_BytesOf_uint8(t *testing.T) {
	var v uint8 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint8)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint8")
	}
}

func TestBytes_BytesOf_uint16(t *testing.T) {
	var v uint16 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint16)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint16")
	}
}

func TestBytes_BytesOf_uint32(t *testing.T) {
	var v uint32 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint32)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint32")
	}
}

func TestBytes_BytesOf_uint64(t *testing.T) {
	var v uint64 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint64")
	}
}

func TestBytes_BytesOf_uintptr(t *testing.T) {
	var v uintptr = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uintptr)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uintptr")
	}
}

func TestBytes_BytesOf_float32(t *testing.T) {
	var v float32 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*float32)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for float32")
	}
}

func TestBytes_BytesOf_float64(t *testing.T) {
	var v float64 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*float64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for float64")
	}
}

func TestBytes_BytesOf_complex64(t *testing.T) {
	var v complex64 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*complex64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for complex64")
	}
}

func TestBytes_BytesOf_complex128(t *testing.T) {
	var v complex128 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*complex128)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for complex128")
	}
}
<commit_msg>added TestBytes_BytesOf_array_int_64<commit_after>package mmm

import (
	"testing"
	"unsafe"
)

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

func TestBytes_BytesOf_bool(t *testing.T) {
	var v bool = true
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*bool)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for bool")
	}
}

func TestBytes_BytesOf_int(t *testing.T) {
	var v int = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int")
	}
}

func TestBytes_BytesOf_int8(t *testing.T) {
	var v int8 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int8)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int8")
	}
}

func TestBytes_BytesOf_int16(t *testing.T) {
	var v int16 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int16)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int16")
	}
}

func TestBytes_BytesOf_int32(t *testing.T) {
	var v int32 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int32)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int32")
	}
}

func TestBytes_BytesOf_int64(t *testing.T) {
	var v int64 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*int64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for int64")
	}
}

func TestBytes_BytesOf_uint(t *testing.T) {
	var v uint = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint")
	}
}

func TestBytes_BytesOf_uint8(t *testing.T) {
	var v uint8 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint8)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint8")
	}
}

func TestBytes_BytesOf_uint16(t *testing.T) {
	var v uint16 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint16)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint16")
	}
}

func TestBytes_BytesOf_uint32(t *testing.T) {
	var v uint32 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint32)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint32")
	}
}

func TestBytes_BytesOf_uint64(t *testing.T) {
	var v uint64 = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uint64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uint64")
	}
}

func TestBytes_BytesOf_uintptr(t *testing.T) {
	var v uintptr = 42
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*uintptr)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for uintptr")
	}
}

func TestBytes_BytesOf_float32(t *testing.T) {
	var v float32 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*float32)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for float32")
	}
}

func TestBytes_BytesOf_float64(t *testing.T) {
	var v float64 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*float64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for float64")
	}
}

func TestBytes_BytesOf_complex64(t *testing.T) {
	var v complex64 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*complex64)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for complex64")
	}
}

func TestBytes_BytesOf_complex128(t *testing.T) {
	var v complex128 = 42.7
	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*complex128)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for complex128")
	}
}

func TestBytes_BytesOf_array_int_64(t *testing.T) {
	var v [64]int
	for i := range v {
		v[i] = i
	}

	size := unsafe.Sizeof(v)
	bytes := make([]byte, size)

	if err := BytesOf(v, bytes); err != nil {
		t.Error(err)
	}

	rv := *((*[64]int)(unsafe.Pointer(&(bytes[0]))))
	if v != rv {
		t.Error("invalid bytes for [64]int")
	}
}
<|endoftext|>


<commit_before>package auth

import (
	"github.com/qor/auth"
	"github.com/qor/auth_themes/clean"
	"github.com/qor/qor-example/app/models"
	"github.com/qor/qor-example/config"
	"github.com/qor/qor-example/db"
)

// Auth initialize auth
var Auth = clean.New(&auth.Config{
	DB:        db.DB,
	Render:    config.View,
	UserModel: models.User{},
})
<commit_msg>Add default mailer<commit_after>package auth

import (
	"bytes"
	"fmt"
	"io"
	"strings"

	"github.com/qor/auth"
	"github.com/qor/auth_themes/clean"
	"github.com/qor/mailer"
	"github.com/qor/mailer/gomailer"
	"github.com/qor/qor-example/app/models"
	"github.com/qor/qor-example/config"
	"github.com/qor/qor-example/db"
	gomail "gopkg.in/gomail.v2"
)

// Auth initialize auth
var Auth = clean.New(&auth.Config{
	DB:        db.DB,
	Render:    config.View,
	UserModel: models.User{},
})

func init() {
	sender := gomail.SendFunc(gomail.SendFunc(func(from string, to []string, msg io.WriterTo) error {
		var buf bytes.Buffer
		fmt.Printf("From: %v\n", from)
		fmt.Printf("To: %v\n", strings.Join(to, ", "))
		msg.WriteTo(&buf)
		fmt.Println(buf.String())
		return nil
	}))

	Auth.Config.Mailer = mailer.New(&mailer.Config{
		Sender: gomailer.New(&gomailer.Config{Sender: sender}),
	})
}
<|endoftext|>


<commit_before>package cache

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
)

var blobNameSHA256 = regexp.MustCompile("^/?([a-f0-9]{64})$")

// HTTPCache ...
type HTTPCache interface {
	Serve()
}

type httpCache struct {
	addr         string
	cache        Cache
	ensureSpacer EnsureSpacer
}

// NewHTTPCache ...
func NewHTTPCache(listenAddr string, cacheDir string, maxBytes int64, ensureSpacer EnsureSpacer) HTTPCache {
	ensureCacheDir(cacheDir)
	initialSize := directorySize(cacheDir)
	cache := NewCache(cacheDir, maxBytes, initialSize)
	return &httpCache{listenAddr, cache, ensureSpacer}
}

// Serve ...
func (h *httpCache) Serve() {
	s := &http.Server{
		Addr:    h.addr,
		Handler: h,
	}
	log.Fatal(s.ListenAndServe())
}

func ensureCacheDir(path string) {
	d, err := os.Open(path)
	if err != nil {
		err := os.MkdirAll(path, os.FileMode(0644))
		if err != nil {
			log.Fatal(err)
		}
	}
	d.Close()
}

func directorySize(path string) (size int64) {
	size = 0
	filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			size += info.Size()
		}
		return nil
	})
	return size
}

func (h *httpCache) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	hash, err := blobName(r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	switch m := r.Method; m {
	case http.MethodGet:
		http.ServeFile(w, r, h.filePath(hash))
	case http.MethodPut:
		if !h.ensureSpacer.EnsureSpace(h.cache, r.ContentLength) {
			http.Error(w, "Cache full.", http.StatusInsufficientStorage)
			return
		}
		written, err := h.saveToDisk(r.Body, hash)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		} else {
			// TODO: Fix if the same file is uploaded twice, the size is incorrect.
			h.cache.AddCurrSize(written)
			w.WriteHeader(http.StatusOK)
		}
		log.Print(h.cache.CurrSize())
	case http.MethodHead:
		// TODO: Use a map or so
		f, err := os.Open(h.filePath(hash))
		if err != nil {
			if os.IsNotExist(err) {
				http.Error(w, err.Error(), http.StatusNotFound)
			} else {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			return
		}
		f.Close()
		w.WriteHeader(http.StatusOK)
	default:
		msg := fmt.Sprintf("Method '%s' not supported.", m)
		http.Error(w, msg, http.StatusMethodNotAllowed)
	}
}

func blobName(name string) (string, error) {
	m := blobNameSHA256.FindStringSubmatch(name)
	if m == nil {
		msg := fmt.Sprintf("Resource name must be a SHA256 hash in hex. "+
			"Got '%s'.", name)
		return "", errors.New(msg)
	}
	return m[1], nil
}

func (h *httpCache) saveToDisk(content io.Reader, hash string) (written int64,
	err error) {
	f, err := ioutil.TempFile(h.cache.Dir(), "upload")
	if err != nil {
		return 0, err
	}
	tmpName := f.Name()
	written, err = io.Copy(f, content)
	if err != nil {
		return 0, err
	}
	f.Close()
	err2 := os.Rename(tmpName, h.filePath(hash))
	if err2 != nil {
		return 0, err2
	}
	return written, nil
}

func (h httpCache) filePath(hash string) string {
	return fmt.Sprintf("%s%c%s", h.cache.Dir(), os.PathSeparator, hash)
}
<commit_msg>http: remove debug print<commit_after>package cache

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
)

var blobNameSHA256 = regexp.MustCompile("^/?([a-f0-9]{64})$")

// HTTPCache ...
type HTTPCache interface {
	Serve()
}

type httpCache struct {
	addr         string
	cache        Cache
	ensureSpacer EnsureSpacer
}

// NewHTTPCache ...
func NewHTTPCache(listenAddr string, cacheDir string, maxBytes int64, ensureSpacer EnsureSpacer) HTTPCache {
	ensureCacheDir(cacheDir)
	initialSize := directorySize(cacheDir)
	cache := NewCache(cacheDir, maxBytes, initialSize)
	return &httpCache{listenAddr, cache, ensureSpacer}
}

// Serve ...
func (h *httpCache) Serve() {
	s := &http.Server{
		Addr:    h.addr,
		Handler: h,
	}
	log.Fatal(s.ListenAndServe())
}

func ensureCacheDir(path string) {
	d, err := os.Open(path)
	if err != nil {
		err := os.MkdirAll(path, os.FileMode(0644))
		if err != nil {
			log.Fatal(err)
		}
	}
	d.Close()
}

func directorySize(path string) (size int64) {
	size = 0
	filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
		if !info.IsDir() {
			size += info.Size()
		}
		return nil
	})
	return size
}

func (h *httpCache) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	hash, err := blobName(r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	switch m := r.Method; m {
	case http.MethodGet:
		http.ServeFile(w, r, h.filePath(hash))
	case http.MethodPut:
		if !h.ensureSpacer.EnsureSpace(h.cache, r.ContentLength) {
			http.Error(w, "Cache full.", http.StatusInsufficientStorage)
			return
		}
		written, err := h.saveToDisk(r.Body, hash)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		} else {
			// TODO: Fix if the same file is uploaded twice, the size is incorrect.
			h.cache.AddCurrSize(written)
			w.WriteHeader(http.StatusOK)
		}
	case http.MethodHead:
		// TODO: Use a map or so
		f, err := os.Open(h.filePath(hash))
		if err != nil {
			if os.IsNotExist(err) {
				http.Error(w, err.Error(), http.StatusNotFound)
			} else {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			return
		}
		f.Close()
		w.WriteHeader(http.StatusOK)
	default:
		msg := fmt.Sprintf("Method '%s' not supported.", m)
		http.Error(w, msg, http.StatusMethodNotAllowed)
	}
}

func blobName(name string) (string, error) {
	m := blobNameSHA256.FindStringSubmatch(name)
	if m == nil {
		msg := fmt.Sprintf("Resource name must be a SHA256 hash in hex. "+
			"Got '%s'.", name)
		return "", errors.New(msg)
	}
	return m[1], nil
}

func (h *httpCache) saveToDisk(content io.Reader, hash string) (written int64,
	err error) {
	f, err := ioutil.TempFile(h.cache.Dir(), "upload")
	if err != nil {
		return 0, err
	}
	tmpName := f.Name()
	written, err = io.Copy(f, content)
	if err != nil {
		return 0, err
	}
	f.Close()
	err2 := os.Rename(tmpName, h.filePath(hash))
	if err2 != nil {
		return 0, err2
	}
	return written, nil
}

func (h httpCache) filePath(hash string) string {
	return fmt.Sprintf("%s%c%s", h.cache.Dir(), os.PathSeparator, hash)
}
<|endoftext|>


<commit_before>package cert

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"time"

	"github.com/golang/go/src/pkg/text/template"
)

const defaultTempl = `{{range .}}DomainName: {{.DomainName}}
Issuer:     {{.Issuer}}
NotBefore:  {{.NotBefore}}
NotAfter:   {{.NotAfter}}
CommonName: {{.CommonName}}
SANs:       {{.SANs}}

{{end}}
`

const markdownTempl = `DomainName | Issuer | NotBefore | NotAfter | CN | SANs
--- | --- | --- | --- | --- | ---
{{range .}}{{.DomainName}} | {{.Issuer}} | {{.NotBefore}} | {{.NotAfter}} | {{.CommonName}} | {{range .SANs}}{{.}}
{{end}} {{end}}
`

type Certs []*Cert

type Cert struct {
	DomainName string
	Issuer     string
	CommonName string
	SANs       []string
	NotBefore  string
	NotAfter   string
}

func NewCerts(s []string) (Certs, error) {
	if len(s) < 1 {
		return nil, fmt.Errorf("Input at least one domain name.")
	}
	certs := Certs{}
	for _, d := range s[:] {
		c, err := NewCert(d)
		if err != nil {
			return nil, err
		}
		certs = append(certs, c)
	}
	return certs, nil
}

func (certs Certs) String() string {
	var b bytes.Buffer
	t, err := template.New("default").Parse(defaultTempl)
	if err != nil {
		panic(err)
	}
	if err := t.Execute(&b, certs); err != nil {
		panic(err)
	}
	return b.String()
}

func (certs Certs) Markdown() string {
	var b bytes.Buffer
	t, err := template.New("markdown").Parse(markdownTempl)
	if err != nil {
		panic(err)
	}
	if err := t.Execute(&b, certs); err != nil {
		panic(err)
	}
	return b.String()
}

func NewCert(d string) (*Cert, error) {
	conn, err := tls.Dial("tcp", d+":443", &tls.Config{})
	if err != nil {
		return nil, err
	}
	cert := conn.ConnectionState().PeerCertificates[0]
	conn.Close()
	return &Cert{
		DomainName: d,
		Issuer:     cert.Issuer.Organization[0],
		CommonName: cert.Subject.CommonName,
		SANs:       cert.DNSNames,
		NotBefore:  cert.NotBefore.In(time.Local).Format("2006/01/02 15:04:05"),
		NotAfter:   cert.NotAfter.In(time.Local).Format("2006/01/02 15:04:05"),
	}, nil
}
<commit_msg>Add new line<commit_after>package cert

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"time"

	"github.com/golang/go/src/pkg/text/template"
)

const defaultTempl = `{{range .}}DomainName: {{.DomainName}}
Issuer:     {{.Issuer}}
NotBefore:  {{.NotBefore}}
NotAfter:   {{.NotAfter}}
CommonName: {{.CommonName}}
SANs:       {{.SANs}}

{{end}}
`

const markdownTempl = `DomainName | Issuer | NotBefore | NotAfter | CN | SANs
--- | --- | --- | --- | --- | ---
{{range .}}{{.DomainName}} | {{.Issuer}} | {{.NotBefore}} | {{.NotAfter}} | {{.CommonName}} | {{range .SANs}}{{.}}
{{end}}
{{end}}
`

type Certs []*Cert

type Cert struct {
	DomainName string
	Issuer     string
	CommonName string
	SANs       []string
	NotBefore  string
	NotAfter   string
}

func NewCerts(s []string) (Certs, error) {
	if len(s) < 1 {
		return nil, fmt.Errorf("Input at least one domain name.")
	}
	certs := Certs{}
	for _, d := range s[:] {
		c, err := NewCert(d)
		if err != nil {
			return nil, err
		}
		certs = append(certs, c)
	}
	return certs, nil
}

func (certs Certs) String() string {
	var b bytes.Buffer
	t, err := template.New("default").Parse(defaultTempl)
	if err != nil {
		panic(err)
	}
	if err := t.Execute(&b, certs); err != nil {
		panic(err)
	}
	return b.String()
}

func (certs Certs) Markdown() string {
	var b bytes.Buffer
	t, err := template.New("markdown").Parse(markdownTempl)
	if err != nil {
		panic(err)
	}
	if err := t.Execute(&b, certs); err != nil {
		panic(err)
	}
	return b.String()
}

func NewCert(d string) (*Cert, error) {
	conn, err := tls.Dial("tcp", d+":443", &tls.Config{})
	if err != nil {
		return nil, err
	}
	cert := conn.ConnectionState().PeerCertificates[0]
	conn.Close()
	return &Cert{
		DomainName: d,
		Issuer:     cert.Issuer.Organization[0],
		CommonName: cert.Subject.CommonName,
		SANs:       cert.DNSNames,
		NotBefore:  cert.NotBefore.In(time.Local).Format("2006/01/02 15:04:05"),
		NotAfter:   cert.NotAfter.In(time.Local).Format("2006/01/02 15:04:05"),
	}, nil
}
<|endoftext|>