<commit_before>package maas

import (
	"launchpad.net/juju-core/environs"
	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/log"
)

type maasEnvironProvider struct{}

var _ environs.EnvironProvider = (*maasEnvironProvider)(nil)

func (*maasEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {
	log.Printf("environs/maas: opening environment %q.", cfg.Name())
	return NewEnviron(cfg)
}

func (*maasEnvironProvider) Validate(cfg, old *config.Config) (*config.Config, error) {
	return cfg, nil
}

func (*maasEnvironProvider) SecretAttrs(*config.Config) (map[string]interface{}, error) {
	panic("Not implemented")
}

func (*maasEnvironProvider) PublicAddress() (string, error) {
	panic("Not implemented")
}

func (*maasEnvironProvider) PrivateAddress() (string, error) {
	panic("Not implemented")
}
<commit_msg>Regularize spelling of 'Not implemented.'<commit_after>package maas

import (
	"launchpad.net/juju-core/environs"
	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/log"
)

type maasEnvironProvider struct{}

var _ environs.EnvironProvider = (*maasEnvironProvider)(nil)

func (*maasEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {
	log.Printf("environs/maas: opening environment %q.", cfg.Name())
	return NewEnviron(cfg)
}

func (*maasEnvironProvider) Validate(cfg, old *config.Config) (*config.Config, error) {
	return cfg, nil
}

func (*maasEnvironProvider) SecretAttrs(*config.Config) (map[string]interface{}, error) {
	panic("Not implemented.")
}

func (*maasEnvironProvider) PublicAddress() (string, error) {
	panic("Not implemented.")
}

func (*maasEnvironProvider) PrivateAddress() (string, error) {
	panic("Not implemented.")
}
<|endoftext|>


<commit_before>package wechat

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/cookiejar"
	"net/http/httputil"
	"os"
	"strings"
	"time"

	"github.com/KevinGong2013/ggbot/utils"
	log "github.com/Sirupsen/logrus"
)

var logger = log.WithFields(log.Fields{
	"module": "wechat",
})

// Debug is a flag, if turn it on, will record all wx `send` api result to json file.
var Debug = true

// Version is wechat's main version
var Version = `0.9.0`

const httpOK = `200`

var debugPath = `.ggbot/debug/`

// BaseRequest is a base for all wx api request.
type BaseRequest struct {
	XMLName xml.Name `xml:"error" json:"-"`

	Ret        int    `xml:"ret" json:"-"`
	Message    string `xml:"message" json:"-"`
	Wxsid      string `xml:"wxsid" json:"Sid"`
	Skey       string `xml:"skey"`
	DeviceID   string `xml:"-"`
	Wxuin      int64  `xml:"wxuin" json:"Uin"`
	PassTicket string `xml:"pass_ticket" json:"-"`
}

// Caller is a interface, All response need implement this.
type Caller interface {
	IsSuccess() bool
	Error() error
}

// Response is a wrapper.
type Response struct {
	BaseResponse *BaseResponse
}

// IsSuccess flag this request is success or failed.
func (response *Response) IsSuccess() bool {
	return response.BaseResponse.Ret == 0
}

// response's error msg.
func (response *Response) Error() error {
	return fmt.Errorf("error message:[%s]", response.BaseResponse.ErrMsg)
}

// BaseResponse for all api resp.
type BaseResponse struct {
	Ret    int
	ErrMsg string
}

// WeChat container a default http client and base request.
type WeChat struct {
	Client        *http.Client
	BaseURL       string
	BaseRequest   *BaseRequest
	UUIDProcessor UUIDProcessor
	MySelf        Contact
	IsLogin       bool
	cache         *cache
	syncKey       map[string]interface{}
	syncHost      string
}

// NewWeChat is desined for Create a new Wechat instance.
func newWeChat(up UUIDProcessor) (*WeChat, error) {

	if up == nil {
		return nil, errors.New(`UUID Processor must be not nil`)
	}
	if _, err := os.Stat(debugPath); err != nil {
		if os.IsNotExist(err) {
			err = os.MkdirAll(debugPath, os.ModePerm)
			if err != nil {
				return nil, err
			}
		} else {
			return nil, err
		}
	}

	client, err := newClient()
	if err != nil {
		return nil, err
	}

	baseReq := new(BaseRequest)
	baseReq.Ret = 1
	baseReq.DeviceID = `e999471493880231`

	wechat := &WeChat{
		Client:        client,
		BaseRequest:   baseReq,
		UUIDProcessor: up,
		IsLogin:       false,
		cache:         newCache(`.ggbot`),
	}

	return wechat, nil
}

func newClient() (*http.Client, error) {

	jar, err := cookiejar.New(nil)
	if err != nil {
		return nil, err
	}

	transport := http.Transport{
		Dial: (&net.Dialer{
			Timeout: 1 * time.Minute,
		}).Dial,
		TLSHandshakeTimeout: 1 * time.Minute,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}

	client := &http.Client{
		Transport: &transport,
		Jar:       jar,
		Timeout:   1 * time.Minute,
	}

	return client, nil
}

// WakeUp is start point for wx bot.
func WakeUp(up UUIDProcessor) (*WeChat, error) {

	if up == nil {
		up = new(defaultUUIDProcessor)
	}

	wechat, err := newWeChat(up)
	if err != nil {
		return nil, err
	}

	// 处理群消息的
	wechat.RegisterModule(newFlatten(wechat))
	// 处理多媒体消息
	wechat.RegisterModule(newMediaMsgMap(wechat))

	wechat.handleServerEvent()
	wechat.keepAlive()

	return wechat, nil
}

// ExcuteRequest is desined for perform http request
func (wechat *WeChat) ExcuteRequest(req *http.Request, call Caller) error {

	ps := strings.Split(req.URL.Path, `/`)
	lastP := strings.Split(ps[len(ps)-1], `?`)[0][5:]
	filename := debugPath + lastP

	if Debug {
		reqData, _ := httputil.DumpRequestOut(req, false)
		utils.CreateFile(filename+`_req.json`, reqData, false)
		c, _ := json.Marshal(wechat.Client.Jar.Cookies(req.URL))
		utils.CreateFile(filename+`_req.json`, c, true)
	}

	resp, err := wechat.Client.Do(req)

	if err != nil {
		return err
	}
	defer resp.Body.Close()

	reader := resp.Body.(io.Reader)

	if Debug {

		data, e := ioutil.ReadAll(reader)
		if e != nil {
			return e
		}

		utils.CreateFile(filename+`_resp.json`, data, true)
		reader = bytes.NewReader(data)
	}

	if err = json.NewDecoder(reader).Decode(call); err != nil {
		return err
	}

	if !call.IsSuccess() {
		return call.Error()
	}

	wechat.refreshBaseInfo()
	wechat.refreshCookieCache(resp.Cookies())

	return nil
}

// Excute a http request by default http client.
func (wechat *WeChat) Excute(path string, body io.Reader, call Caller) error {
	method := "GET"
	if body != nil {
		method = "POST"
	}
	req, err := http.NewRequest(method, path, body)
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json; charset=UTF-8")
	req.Header.Set(`User-Agent`, `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/602.3.12 (KHTML, like Gecko) Version/10.0.2 Safari/602.3.12`)

	return wechat.ExcuteRequest(req, call)
}

// PassTicketKV return a string like `pass_ticket=sdfewsvdwd=`
func (wechat *WeChat) PassTicketKV() string {
	return fmt.Sprintf(`pass_ticket=%s`, wechat.BaseRequest.PassTicket)
}

// SkeyKV return a string like `skey=ewfwoefjwofjskfwes`
func (wechat *WeChat) SkeyKV() string {
	return fmt.Sprintf(`skey=%s`, wechat.BaseRequest.Skey)
}
<commit_msg>Move contact cache file to debug folder.<commit_after>package wechat

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/cookiejar"
	"net/http/httputil"
	"os"
	"strings"
	"time"

	"github.com/KevinGong2013/ggbot/utils"
	log "github.com/Sirupsen/logrus"
)

var logger = log.WithFields(log.Fields{
	"module": "wechat",
})

// Debug is a flag, if turn it on, will record all wx `send` api result to json file.
var Debug = true

// Version is wechat's main version
var Version = `0.9.0`

const httpOK = `200`

var debugPath = `.ggbot/debug/`

// BaseRequest is a base for all wx api request.
type BaseRequest struct {
	XMLName xml.Name `xml:"error" json:"-"`

	Ret        int    `xml:"ret" json:"-"`
	Message    string `xml:"message" json:"-"`
	Wxsid      string `xml:"wxsid" json:"Sid"`
	Skey       string `xml:"skey"`
	DeviceID   string `xml:"-"`
	Wxuin      int64  `xml:"wxuin" json:"Uin"`
	PassTicket string `xml:"pass_ticket" json:"-"`
}

// Caller is a interface, All response need implement this.
type Caller interface {
	IsSuccess() bool
	Error() error
}

// Response is a wrapper.
type Response struct {
	BaseResponse *BaseResponse
}

// IsSuccess flag this request is success or failed.
func (response *Response) IsSuccess() bool {
	return response.BaseResponse.Ret == 0
}

// response's error msg.
func (response *Response) Error() error {
	return fmt.Errorf("error message:[%s]", response.BaseResponse.ErrMsg)
}

// BaseResponse for all api resp.
type BaseResponse struct {
	Ret    int
	ErrMsg string
}

// WeChat container a default http client and base request.
type WeChat struct {
	Client        *http.Client
	BaseURL       string
	BaseRequest   *BaseRequest
	UUIDProcessor UUIDProcessor
	MySelf        Contact
	IsLogin       bool
	cache         *cache
	syncKey       map[string]interface{}
	syncHost      string
}

// NewWeChat is desined for Create a new Wechat instance.
func newWeChat(up UUIDProcessor) (*WeChat, error) {

	if up == nil {
		return nil, errors.New(`UUID Processor must be not nil`)
	}
	if _, err := os.Stat(debugPath); err != nil {
		if os.IsNotExist(err) {
			err = os.MkdirAll(debugPath, os.ModePerm)
			if err != nil {
				return nil, err
			}
		} else {
			return nil, err
		}
	}

	client, err := newClient()
	if err != nil {
		return nil, err
	}

	baseReq := new(BaseRequest)
	baseReq.Ret = 1
	baseReq.DeviceID = `e999471493880231`

	wechat := &WeChat{
		Client:        client,
		BaseRequest:   baseReq,
		UUIDProcessor: up,
		IsLogin:       false,
		cache:         newCache(`.ggbot/debug`),
	}

	return wechat, nil
}

func newClient() (*http.Client, error) {

	jar, err := cookiejar.New(nil)
	if err != nil {
		return nil, err
	}

	transport := http.Transport{
		Dial: (&net.Dialer{
			Timeout: 1 * time.Minute,
		}).Dial,
		TLSHandshakeTimeout: 1 * time.Minute,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}

	client := &http.Client{
		Transport: &transport,
		Jar:       jar,
		Timeout:   1 * time.Minute,
	}

	return client, nil
}

// WakeUp is start point for wx bot.
func WakeUp(up UUIDProcessor) (*WeChat, error) {

	if up == nil {
		up = new(defaultUUIDProcessor)
	}

	wechat, err := newWeChat(up)
	if err != nil {
		return nil, err
	}

	// 处理群消息的
	wechat.RegisterModule(newFlatten(wechat))
	// 处理多媒体消息
	wechat.RegisterModule(newMediaMsgMap(wechat))

	wechat.handleServerEvent()
	wechat.keepAlive()

	return wechat, nil
}

// ExcuteRequest is desined for perform http request
func (wechat *WeChat) ExcuteRequest(req *http.Request, call Caller) error {

	ps := strings.Split(req.URL.Path, `/`)
	lastP := strings.Split(ps[len(ps)-1], `?`)[0][5:]
	filename := debugPath + lastP

	if Debug {
		reqData, _ := httputil.DumpRequestOut(req, false)
		utils.CreateFile(filename+`_req.json`, reqData, false)
		c, _ := json.Marshal(wechat.Client.Jar.Cookies(req.URL))
		utils.CreateFile(filename+`_req.json`, c, true)
	}

	resp, err := wechat.Client.Do(req)

	if err != nil {
		return err
	}
	defer resp.Body.Close()

	reader := resp.Body.(io.Reader)

	if Debug {

		data, e := ioutil.ReadAll(reader)
		if e != nil {
			return e
		}

		utils.CreateFile(filename+`_resp.json`, data, true)
		reader = bytes.NewReader(data)
	}

	if err = json.NewDecoder(reader).Decode(call); err != nil {
		return err
	}

	if !call.IsSuccess() {
		return call.Error()
	}

	wechat.refreshBaseInfo()
	wechat.refreshCookieCache(resp.Cookies())

	return nil
}

// Excute a http request by default http client.
func (wechat *WeChat) Excute(path string, body io.Reader, call Caller) error {
	method := "GET"
	if body != nil {
		method = "POST"
	}
	req, err := http.NewRequest(method, path, body)
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json; charset=UTF-8")
	req.Header.Set(`User-Agent`, `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/602.3.12 (KHTML, like Gecko) Version/10.0.2 Safari/602.3.12`)

	return wechat.ExcuteRequest(req, call)
}

// PassTicketKV return a string like `pass_ticket=sdfewsvdwd=`
func (wechat *WeChat) PassTicketKV() string {
	return fmt.Sprintf(`pass_ticket=%s`, wechat.BaseRequest.PassTicket)
}

// SkeyKV return a string like `skey=ewfwoefjwofjskfwes`
func (wechat *WeChat) SkeyKV() string {
	return fmt.Sprintf(`skey=%s`, wechat.BaseRequest.Skey)
}
<|endoftext|>


<commit_before>package tmp006

import (
	"errors"
	"fmt"
	"log"
	"math"
	"sync"
	"time"

	"github.com/kid0m4n/go-rpi/i2c"
)

const (
	b0   = -0.0000294
	b1   = -0.00000057
	b2   = 0.00000000463
	c2   = 13.4
	tref = 298.15
	a2   = -0.00001678
	a1   = 0.00175
	s0   = 6.4

	vObjReg    = 0x00
	tempAmbReg = 0x01
	configReg  = 0x02
	manIdReg   = 0xFE
	manId      = 0x5449
	devIdReg   = 0xFF
	devId      = 0x0067

	reset  = 0x8000
	modeOn = 0x7000
	drdyEn = 0x0100

	configRegDefault = modeOn | drdyEn
)

type SampleRate struct {
	enabler      uint16
	samples      int
	timeRequired float64
}

var (
	SR1  = &SampleRate{0x0000, 1, 0.25} // 1 sample, 0.25 second between measurements.
	SR2  = &SampleRate{0x0200, 2, 0.5}  // 2 samples, 0.5 second between measurements.
	SR4  = &SampleRate{0x0400, 4, 1}    // 4 samples, 1 second between measurements.
	SR8  = &SampleRate{0x0600, 8, 2}    // 8 samples, 2 seconds between measurements.
	SR16 = &SampleRate{0x0800, 16, 4}   // 16 samples, 4 seconds between measurements.
)

// Device represents a TMP006 thermopile sensor.
type Device struct {
	// Bus to communicate over.
	Bus i2c.Bus
	// Addr of the sensor.
	Addr byte
	// Debug turns on additional debug output.
	Debug bool
	// SampleRate specifies the sampling rate for the sensor.
	SampleRate *SampleRate

	initialized bool
	mu          sync.RWMutex

	rawDieTemps chan float64
	objTemps    chan float64
	closing     chan chan struct{}
}

// New creates a new TMP006 sensor.
func New(bus i2c.Bus, addr byte) *Device {
	return &Device{
		Bus:  bus,
		Addr: addr,
	}
}

func (d *Device) validate() error {
	if d.Bus == nil {
		return errors.New("tmp006: bus is nil")
	}
	if d.Addr == 0x00 {
		return fmt.Errorf("tmp006: %#x is not a valid address", d.Addr)
	}
	return nil
}

// Close puts the device into low power mode.
func (d *Device) Close() (err error) {
	if err = d.setup(); err != nil {
		return
	}
	if d.closing != nil {
		waitc := make(chan struct{})
		d.closing <- waitc
		<-waitc
	}
	if d.Debug {
		log.Print("tmp006: resetting")
	}
	if err = d.Bus.WriteWordToReg(d.Addr, configReg, reset); err != nil {
		return
	}
	return
}

// Present checks if the device is present at the given address.
func (d *Device) Present() (status bool, err error) {
	if err = d.validate(); err != nil {
		return
	}
	var mid, did uint16
	if mid, err = d.Bus.ReadWordFromReg(d.Addr, manIdReg); err != nil {
		return
	}
	if d.Debug {
		log.Printf("tmp006: got manufacturer id %#04x", mid)
	}
	if mid != manId {
		err = fmt.Errorf("tmp006: not found at %#02x, manufacturer id mismatch", d.Addr)
		return
	}
	if did, err = d.Bus.ReadWordFromReg(d.Addr, devIdReg); err != nil {
		return
	}
	if d.Debug {
		log.Printf("tmp006: got device id %#04x", did)
	}
	if did != devId {
		err = fmt.Errorf("tmp006: not found at %#02x, device id mismatch", d.Addr)
		return
	}

	status = true

	return
}

func (d *Device) setup() (err error) {
	d.mu.RLock()
	if d.initialized {
		d.mu.RUnlock()
		return
	}
	d.mu.RUnlock()

	d.mu.Lock()
	defer d.mu.Unlock()

	if err = d.validate(); err != nil {
		return
	}
	if d.SampleRate == nil {
		if d.Debug {
			log.Printf("tmp006: sample rate = nil, using SR16")
		}
		d.SampleRate = SR16
	}
	if d.Debug {
		log.Printf("tmp006: configuring with %#04x", configRegDefault|d.SampleRate.enabler)
	}
	if err = d.Bus.WriteWordToReg(d.Addr, configReg, configRegDefault|d.SampleRate.enabler); err != nil {
		return
	}

	d.initialized = true

	return
}

func (d *Device) measureRawDieTemp() (temp float64, err error) {
	if err = d.setup(); err != nil {
		return
	}
	var raw uint16
	if raw, err = d.Bus.ReadWordFromReg(d.Addr, tempAmbReg); err != nil {
		return
	}
	raw >>= 2
	if d.Debug {
		log.Printf("tmp006: raw die temp %#04x", raw)
	}

	temp = float64(int16(raw)) * 0.03125

	return
}

func (d *Device) measureRawVoltage() (volt int16, err error) {
	if err = d.setup(); err != nil {
		return
	}
	var vlt uint16
	if vlt, err = d.Bus.ReadWordFromReg(d.Addr, vObjReg); err != nil {
		return
	}
	volt = int16(vlt)
	if d.Debug {
		log.Printf("tmp006: raw voltage %#04x", volt)
	}
	return
}

func (d *Device) measureObjTemp() (temp float64, err error) {
	if err = d.setup(); err != nil {
		return
	}
	tDie, err := d.measureRawDieTemp()
	if err != nil {
		return
	}
	if d.Debug {
		log.Printf("tmp006: tdie = %.2f C", tDie)
	}
	tDie += 273.15 // Convert to K
	vo, err := d.measureRawVoltage()
	if err != nil {
		return
	}
	vObj := float64(vo)
	vObj *= 156.25 // 156.25 nV per LSB
	vObj /= 1000   // nV -> uV
	if d.Debug {
		log.Printf("tmp006: vObj = %.5f uV", vObj)
	}
	vObj /= 1000 // uV -> mV
	vObj /= 1000 // mV -> V

	tdie_tref := tDie - tref
	s := 1 + a1*tdie_tref + a2*tdie_tref*tdie_tref
	s *= s0
	s /= 10000000
	s /= 10000000

	Vos := b0 + b1*tdie_tref + b2*tdie_tref*tdie_tref
	fVobj := (vObj - Vos) + c2*(vObj-Vos)*(vObj-Vos)

	temp = math.Sqrt(math.Sqrt(tDie*tDie*tDie*tDie + fVobj/s))
	temp -= 273.15

	return
}

// RawDieTemp returns the current raw die temp reading.
func (d *Device) RawDieTemp() (temp float64, err error) {
	select {
	case temp = <-d.rawDieTemps:
		return
	default:
		return d.measureRawDieTemp()
	}
}

// RawDieTemps returns a channel to get future raw die temps from.
func (d *Device) RawDieTemps() <-chan float64 {
	return d.rawDieTemps
}

// ObjTemp returns the current obj temp reading.
func (d *Device) ObjTemp() (temp float64, err error) {
	select {
	case temp = <-d.objTemps:
		return
	default:
		return d.measureObjTemp()
	}
}

// ObjTemps returns a channel to fetch obj temps from.
func (d *Device) ObjTemps() <-chan float64 {
	return d.objTemps
}

// Start starts the data acquisition loop.
func (d *Device) Start() (err error) {
	if err = d.setup(); err != nil {
		return
	}

	d.rawDieTemps = make(chan float64)
	d.objTemps = make(chan float64)

	go func() {
		var rawDieTemp, objTemp float64
		var rdtAvlb, otAvlb bool
		var err error
		var timer <-chan time.Time
		resetTimer := func() {
			timer = time.After(time.Duration(d.SampleRate.timeRequired*1000) * time.Millisecond)
		}
		resetTimer()

		for {
			var rawDieTemps, objTemps chan float64

			if rdtAvlb {
				rawDieTemps = d.rawDieTemps
			}
			if otAvlb {
				objTemps = d.objTemps
			}

			select {
			case <-timer:
				var rdt float64
				if rdt, err = d.measureRawDieTemp(); err != nil {
					log.Printf("tmp006: %v", err)
				} else {
					rawDieTemp = rdt
					rdtAvlb = true
				}
				var ot float64
				if ot, err = d.measureObjTemp(); err != nil {
					log.Printf("tmp006: %v", err)
				} else {
					objTemp = ot
					otAvlb = true
				}
				resetTimer()
			case rawDieTemps <- rawDieTemp:
				rdtAvlb = false
			case objTemps <- objTemp:
				otAvlb = false
			case waitc := <-d.closing:
				waitc <- struct{}{}
				close(d.rawDieTemps)
				close(d.objTemps)
				return
			}
		}
	}()

	return
}
<commit_msg>refactor<commit_after>// Package tmp006 allows interfacing with the TMP006 thermopile.
package tmp006

import (
	"errors"
	"fmt"
	"log"
	"math"
	"sync"
	"time"

	"github.com/kid0m4n/go-rpi/i2c"
)

const (
	b0   = -0.0000294
	b1   = -0.00000057
	b2   = 0.00000000463
	c2   = 13.4
	tref = 298.15
	a2   = -0.00001678
	a1   = 0.00175
	s0   = 6.4

	vObjReg    = 0x00
	tempAmbReg = 0x01
	configReg  = 0x02
	manIdReg   = 0xFE
	manId      = 0x5449
	devIdReg   = 0xFF
	devId      = 0x0067

	reset  = 0x8000
	modeOn = 0x7000
	drdyEn = 0x0100

	configRegDefault = modeOn | drdyEn
)

type SampleRate struct {
	enabler      uint16
	samples      int
	timeRequired float64
}

var (
	SR1  = &SampleRate{0x0000, 1, 0.25} // 1 sample, 0.25 second between measurements.
	SR2  = &SampleRate{0x0200, 2, 0.5}  // 2 samples, 0.5 second between measurements.
	SR4  = &SampleRate{0x0400, 4, 1}    // 4 samples, 1 second between measurements.
	SR8  = &SampleRate{0x0600, 8, 2}    // 8 samples, 2 seconds between measurements.
	SR16 = &SampleRate{0x0800, 16, 4}   // 16 samples, 4 seconds between measurements.
)

// TMP006 represents a TMP006 thermopile sensor.
type TMP006 struct {
	// Bus to communicate over.
	Bus i2c.Bus
	// Addr of the sensor.
	Addr byte
	// Debug turns on additional debug output.
	Debug bool
	// SampleRate specifies the sampling rate for the sensor.
	SampleRate *SampleRate

	initialized bool
	mu          sync.RWMutex

	rawDieTemps chan float64
	objTemps    chan float64
	closing     chan chan struct{}
}

// New creates a new TMP006 sensor.
func New(bus i2c.Bus, addr byte) *TMP006 {
	return &TMP006{
		Bus:  bus,
		Addr: addr,
	}
}

func (d *TMP006) validate() error {
	if d.Bus == nil {
		return errors.New("tmp006: bus is nil")
	}
	if d.Addr == 0x00 {
		return fmt.Errorf("tmp006: %#x is not a valid address", d.Addr)
	}
	return nil
}

// Close puts the device into low power mode.
func (d *TMP006) Close() (err error) {
	if err = d.setup(); err != nil {
		return
	}
	if d.closing != nil {
		waitc := make(chan struct{})
		d.closing <- waitc
		<-waitc
	}
	if d.Debug {
		log.Print("tmp006: resetting")
	}
	if err = d.Bus.WriteWordToReg(d.Addr, configReg, reset); err != nil {
		return
	}
	return
}

// Present checks if the device is present at the given address.
func (d *TMP006) Present() (status bool, err error) {
	if err = d.validate(); err != nil {
		return
	}
	var mid, did uint16
	if mid, err = d.Bus.ReadWordFromReg(d.Addr, manIdReg); err != nil {
		return
	}
	if d.Debug {
		log.Printf("tmp006: got manufacturer id %#04x", mid)
	}
	if mid != manId {
		err = fmt.Errorf("tmp006: not found at %#02x, manufacturer id mismatch", d.Addr)
		return
	}
	if did, err = d.Bus.ReadWordFromReg(d.Addr, devIdReg); err != nil {
		return
	}
	if d.Debug {
		log.Printf("tmp006: got device id %#04x", did)
	}
	if did != devId {
		err = fmt.Errorf("tmp006: not found at %#02x, device id mismatch", d.Addr)
		return
	}

	status = true

	return
}

func (d *TMP006) setup() (err error) {
	d.mu.RLock()
	if d.initialized {
		d.mu.RUnlock()
		return
	}
	d.mu.RUnlock()

	d.mu.Lock()
	defer d.mu.Unlock()

	if err = d.validate(); err != nil {
		return
	}
	if d.SampleRate == nil {
		if d.Debug {
			log.Printf("tmp006: sample rate = nil, using SR16")
		}
		d.SampleRate = SR16
	}
	if d.Debug {
		log.Printf("tmp006: configuring with %#04x", configRegDefault|d.SampleRate.enabler)
	}
	if err = d.Bus.WriteWordToReg(d.Addr, configReg, configRegDefault|d.SampleRate.enabler); err != nil {
		return
	}

	d.initialized = true

	return
}

func (d *TMP006) measureRawDieTemp() (temp float64, err error) {
	if err = d.setup(); err != nil {
		return
	}
	var raw uint16
	if raw, err = d.Bus.ReadWordFromReg(d.Addr, tempAmbReg); err != nil {
		return
	}
	raw >>= 2
	if d.Debug {
		log.Printf("tmp006: raw die temp %#04x", raw)
	}

	temp = float64(int16(raw)) * 0.03125

	return
}

func (d *TMP006) measureRawVoltage() (volt int16, err error) {
	if err = d.setup(); err != nil {
		return
	}
	var vlt uint16
	if vlt, err = d.Bus.ReadWordFromReg(d.Addr, vObjReg); err != nil {
		return
	}
	volt = int16(vlt)
	if d.Debug {
		log.Printf("tmp006: raw voltage %#04x", volt)
	}
	return
}

func (d *TMP006) measureObjTemp() (temp float64, err error) {
	if err = d.setup(); err != nil {
		return
	}
	tDie, err := d.measureRawDieTemp()
	if err != nil {
		return
	}
	if d.Debug {
		log.Printf("tmp006: tdie = %.2f C", tDie)
	}
	tDie += 273.15 // Convert to K
	vo, err := d.measureRawVoltage()
	if err != nil {
		return
	}
	vObj := float64(vo)
	vObj *= 156.25 // 156.25 nV per LSB
	vObj /= 1000   // nV -> uV
	if d.Debug {
		log.Printf("tmp006: vObj = %.5f uV", vObj)
	}
	vObj /= 1000 // uV -> mV
	vObj /= 1000 // mV -> V

	tdie_tref := tDie - tref
	s := 1 + a1*tdie_tref + a2*tdie_tref*tdie_tref
	s *= s0
	s /= 10000000
	s /= 10000000

	Vos := b0 + b1*tdie_tref + b2*tdie_tref*tdie_tref
	fVobj := (vObj - Vos) + c2*(vObj-Vos)*(vObj-Vos)

	temp = math.Sqrt(math.Sqrt(tDie*tDie*tDie*tDie + fVobj/s))
	temp -= 273.15

	return
}

// RawDieTemp returns the current raw die temp reading.
func (d *TMP006) RawDieTemp() (temp float64, err error) {
	select {
	case temp = <-d.rawDieTemps:
		return
	default:
		return d.measureRawDieTemp()
	}
}

// RawDieTemps returns a channel to get future raw die temps from.
func (d *TMP006) RawDieTemps() <-chan float64 {
	return d.rawDieTemps
}

// ObjTemp returns the current obj temp reading.
func (d *TMP006) ObjTemp() (temp float64, err error) {
	select {
	case temp = <-d.objTemps:
		return
	default:
		return d.measureObjTemp()
	}
}

// ObjTemps returns a channel to fetch obj temps from.
func (d *TMP006) ObjTemps() <-chan float64 {
	return d.objTemps
}

// Start starts the data acquisition loop.
func (d *TMP006) Start() (err error) {
	if err = d.setup(); err != nil {
		return
	}

	d.rawDieTemps = make(chan float64)
	d.objTemps = make(chan float64)

	go func() {
		var rawDieTemp, objTemp float64
		var rdtAvlb, otAvlb bool
		var err error
		var timer <-chan time.Time
		resetTimer := func() {
			timer = time.After(time.Duration(d.SampleRate.timeRequired*1000) * time.Millisecond)
		}
		resetTimer()

		for {
			var rawDieTemps, objTemps chan float64

			if rdtAvlb {
				rawDieTemps = d.rawDieTemps
			}
			if otAvlb {
				objTemps = d.objTemps
			}

			select {
			case <-timer:
				var rdt float64
				if rdt, err = d.measureRawDieTemp(); err != nil {
					log.Printf("tmp006: %v", err)
				} else {
					rawDieTemp = rdt
					rdtAvlb = true
				}
				var ot float64
				if ot, err = d.measureObjTemp(); err != nil {
					log.Printf("tmp006: %v", err)
				} else {
					objTemp = ot
					otAvlb = true
				}
				resetTimer()
			case rawDieTemps <- rawDieTemp:
				rdtAvlb = false
			case objTemps <- objTemp:
				otAvlb = false
			case waitc := <-d.closing:
				waitc <- struct{}{}
				close(d.rawDieTemps)
				close(d.objTemps)
				return
			}
		}
	}()

	return
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"

	"github.com/urfave/cli"

	"github.com/arigatomachine/cli/api"
	"github.com/arigatomachine/cli/errs"
	"github.com/arigatomachine/cli/identity"
	"github.com/arigatomachine/cli/pathexp"
)

func init() {
	ls := cli.Command{
		Name:      "ls",
		ArgsUsage: "[cpath]",
		Usage:     "Explore all objects your account has access to",
		Category:  "SECRETS",
		Flags: []cli.Flag{
			orgFlag("Use this organization.", false),
			projectFlag("Use this project.", false),
			newSlicePlaceholder("environment, e", "ENV", "Use this environment.",
				"*", "TORUS_ENVIRONMENT", false),
			newSlicePlaceholder("service, s", "SERVICE", "Use this service.",
				"default", "TORUS_SERVICE", false),
			newSlicePlaceholder("user, u", "USER", "Use this user (identity).",
				"*", "TORUS_USER", false),
			newSlicePlaceholder("instance, i", "INSTANCE", "Use this instance.",
				"*", "TORUS_INSTANCE", false),
		},
		Action: chain(
			ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
			checkRequiredFlags, listObjects,
		),
	}
	Cmds = append(Cmds, ls)
}

func listObjects(ctx *cli.Context) error {
	args := ctx.Args()

	var useFlags bool

	// Try to be helpful and detect when a wildcard isn't quoted
	if len(args) > 1 {
		return errs.NewUsageExitError("Invalid path supplied.\n"+
			"Note: arguments containing wildcards must be wrapped in qutoes.", ctx)
	}

	var cpathObj *pathexp.PathExp
	var count int
	var err error

	hasPath := len(args) > 0
	emptyOrg := ctx.String("org") == ""
	emptyProj := ctx.String("project") == ""
	emptyOrgOrProject := len(args) == 0 && (emptyOrg || emptyProj)

	if hasPath || emptyOrgOrProject {
		var path string
		if hasPath {
			// User has supplied a path
			path = args[0]
		} else if emptyProj {
			// Context enabled, no project supplied
			path = "/" + ctx.String("org")
		} else {
			// Context enabled, no org supplied
			path = "/"
		}

		// Construct the target from single path supplied
		obj, segmentCount, err := pathexp.NewPartialFromPath(path)
		cpathObj = obj
		count = *segmentCount
		if err != nil {
			return err
		}
	} else {
		// Construct the target path through flags
		obj, _, err := pathexp.NewPartial(ctx.String("org"), ctx.String("project"),
			ctx.StringSlice("environment"), ctx.StringSlice("service"),
			ctx.StringSlice("user"), ctx.StringSlice("instance"),
		)
		cpathObj = obj
		count = 6
		if err != nil {
			return err
		}
		useFlags = true
	}

	// When using flag composition, require org and project at minimum
	if useFlags && count < 1 {
		return errs.NewUsageExitError("Org must be supplied", ctx)
	}
	if useFlags && count < 2 {
		return errs.NewUsageExitError("Project must be supplied", ctx)
	}
	if count > 3 && cpathObj.Org() == "*" {
		return errs.NewUsageExitError("Org must be supplied to view secrets", ctx)
	}
	if count > 3 && cpathObj.Project() == "*" {
		return errs.NewUsageExitError("Project must be supplied to view secrets", ctx)
	}

	var paths []string
	var pathErr error

	showing := "Listing objects for path"
	switch count {
	case 0:
		showing = "Listing orgs:"
		paths, err = orgPaths()
		if err != nil {
			pathErr = errs.NewExitError("Failed to list orgs.")
		}
	case 1:
		partial := "/" + cpathObj.Org()
		showing = "Listing projects within path: " + partial
		paths, err = projectPaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list projects.")
		}
	case 2:
		partial := "/" + cpathObj.Org() + "/" + cpathObj.Project()
		showing = "Listing environments within path: " + partial
		paths, err = envPaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list environments.")
		}
	case 3:
		partial := "/" + cpathObj.Org() + "/" + cpathObj.Project() + "/*"
		showing = "Listing services within path: " + partial
		paths, err = servicePaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list services.")
		}
	default:
		showing = "Listing secrets within path: " + cpathObj.String()
		paths, err = secretPaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list secrets.")
		}
	}

	// Print the path and object type of the output
	fmt.Println(showing)

	// Must replace Envs with * when only 3 segments supplied
	if count == 3 && cpathObj.Envs() != "*" {
		fmt.Println("Note: environment exchanged for *")
		fmt.Println("")
	} else {
		fmt.Println("")
	}

	if pathErr != nil {
		return pathErr
	}
	for _, path := range paths {
		fmt.Println(path)
	}

	return nil
}

// generate all paths for /
func orgPaths() ([]string, error) {
	var paths []string

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	for _, org := range orgs {
		paths = append(paths, "/"+org.Body.Name)
	}

	return paths, nil
}

// generate all paths for /${org}
func projectPaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	orgIDs, _, orgMapID, err := filterOrgs(orgs, cpathObj)
	if err != nil {
		return nil, err
	}

	projects, err := listProjectsByOrgID(nil, nil, orgIDs)
	if err != nil {
		return nil, err
	}

	for _, project := range projects {
		pOrgName := orgMapID[*project.Body.OrgID]
		paths = append(paths, fmt.Sprintf("/%s/%s", pOrgName, project.Body.Name))
	}

	return paths, nil
}

// generate all paths for /${org}/${project}
func envPaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string
	c, client, err := NewAPIClient(nil, nil)

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	orgIDs, _, orgMapID, err := filterOrgs(orgs, cpathObj)
	if err != nil {
		return nil, err
	}

	projects, err := listProjectsByOrgID(&c, client, orgIDs)
	if err != nil {
		return nil, err
	}

	projectIDs, projMapID, err := filterProjects(projects, cpathObj)
	if err != nil {
		return nil, err
	}

	envs, err := listEnvsByProjectID(&c, client, projectIDs)
	if err != nil {
		return nil, err
	}

	for _, env := range envs {
		eOrgName := orgMapID[*env.Body.OrgID]
		eProjName := projMapID[*env.Body.ProjectID]
		paths = append(paths, fmt.Sprintf("/%s/%s/%s", eOrgName, eProjName, env.Body.Name))
	}

	return paths, nil
}

// generate all paths for /${org}/${project}/*
func servicePaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string
	c, client, err := NewAPIClient(nil, nil)

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	orgIDs, _, orgMapID, err := filterOrgs(orgs, cpathObj)
	if err != nil {
		return nil, err
	}

	projects, err := listProjectsByOrgID(&c, client, orgIDs)
	if err != nil {
		return nil, err
	}

	projectIDs, projMapID, err := filterProjects(projects, cpathObj)
	if err != nil {
		return nil, err
	}

	services, err := listServicesByProjectID(&c, client, projectIDs)
	if err != nil {
		return nil, err
	}

	for _, service := range services {
		sOrgName := orgMapID[*service.Body.OrgID]
		sProjName := projMapID[*service.Body.ProjectID]
		paths = append(paths, fmt.Sprintf("/%s/%s/*/%s", sOrgName, sProjName, service.Body.Name))
	}

	return paths, nil
}

func secretPaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string
	c, client, err := NewAPIClient(nil, nil)

	creds, err := client.Credentials.Search(c, cpathObj.String())
	if err != nil {
		return nil, err
	}

	for _, cred := range creds {
		body := *cred.Body
		paths = append(paths, fmt.Sprintf("%s/%s", body.GetPathExp(), body.GetName()))
	}

	return paths, nil
}

func filterProjects(projects []api.ProjectResult, pe *pathexp.PathExp) ([]*identity.ID, map[identity.ID]string, error) {
	projMapID := make(map[identity.ID]string, len(projects))
	var projectIDs []*identity.ID
	for _, project := range projects {
		projMapID[*project.ID] = project.Body.Name
		if pe.Project() == "*" {
			projectIDs = append(projectIDs, project.ID)
		} else if project.Body.Name == pe.Project() {
			projectIDs = append(projectIDs, project.ID)
		}
	}
	if len(projectIDs) < 1 {
		return nil, nil, errs.NewExitError("Project not found.")
	}
	return projectIDs, projMapID, nil
}

func filterOrgs(orgs []api.OrgResult, pe *pathexp.PathExp) ([]*identity.ID, map[string]identity.ID, map[identity.ID]string, error) {
	orgMapName := make(map[string]identity.ID, len(orgs))
	orgMapID := make(map[identity.ID]string, len(orgs))

	var orgIDs []*identity.ID
	for _, org := range orgs {
		orgMapName[org.Body.Name] = *org.ID
		orgMapID[*org.ID] = org.Body.Name
		if pe.Org() == "*" || org.Body.Name == pe.Org() {
			orgIDs = append(orgIDs, org.ID)
		}
	}
	if len(orgIDs) < 1 {
		return nil, nil, nil, errs.NewExitError("Org not found.")
	}

	return orgIDs, orgMapName, orgMapID, nil
}
<commit_msg>Use credentialSet for displaying paths in ls, sort output paths<commit_after>package cmd

import (
	"fmt"
	"sort"

	"github.com/urfave/cli"

	"github.com/arigatomachine/cli/api"
	"github.com/arigatomachine/cli/errs"
	"github.com/arigatomachine/cli/identity"
	"github.com/arigatomachine/cli/pathexp"
)

func init() {
	ls := cli.Command{
		Name:      "ls",
		ArgsUsage: "[cpath]",
		Usage:     "Explore all objects your account has access to",
		Category:  "SECRETS",
		Flags: []cli.Flag{
			orgFlag("Use this organization.", false),
			projectFlag("Use this project.", false),
			newSlicePlaceholder("environment, e", "ENV", "Use this environment.",
				"*", "TORUS_ENVIRONMENT", false),
			newSlicePlaceholder("service, s", "SERVICE", "Use this service.",
				"default", "TORUS_SERVICE", false),
			newSlicePlaceholder("user, u", "USER", "Use this user (identity).",
				"*", "TORUS_USER", false),
			newSlicePlaceholder("instance, i", "INSTANCE", "Use this instance.",
				"*", "TORUS_INSTANCE", false),
		},
		Action: chain(
			ensureDaemon, ensureSession, loadDirPrefs, loadPrefDefaults,
			checkRequiredFlags, listObjects,
		),
	}
	Cmds = append(Cmds, ls)
}

func listObjects(ctx *cli.Context) error {
	args := ctx.Args()

	var useFlags bool

	// Try to be helpful and detect when a wildcard isn't quoted
	if len(args) > 1 {
		return errs.NewUsageExitError("Invalid path supplied.\n"+
			"Note: arguments containing wildcards must be wrapped in qutoes.", ctx)
	}

	var cpathObj *pathexp.PathExp
	var count int
	var err error

	hasPath := len(args) > 0
	emptyOrg := ctx.String("org") == ""
	emptyProj := ctx.String("project") == ""
	emptyOrgOrProject := len(args) == 0 && (emptyOrg || emptyProj)

	if hasPath || emptyOrgOrProject {
		var path string
		if hasPath {
			// User has supplied a path
			path = args[0]
		} else if emptyProj {
			// Context enabled, no project supplied
			path = "/" + ctx.String("org")
		} else {
			// Context enabled, no org supplied
			path = "/"
		}

		// Construct the target from single path supplied
		obj, segmentCount, err := pathexp.NewPartialFromPath(path)
		cpathObj = obj
		count = *segmentCount
		if err != nil {
			return err
		}
	} else {
		// Construct the target path through flags
		obj, _, err := pathexp.NewPartial(ctx.String("org"), ctx.String("project"),
			ctx.StringSlice("environment"), ctx.StringSlice("service"),
			ctx.StringSlice("user"), ctx.StringSlice("instance"),
		)
		cpathObj = obj
		count = 6
		if err != nil {
			return err
		}
		useFlags = true
	}

	// When using flag composition, require org and project at minimum
	if useFlags && count < 1 {
		return errs.NewUsageExitError("Org must be supplied", ctx)
	}
	if useFlags && count < 2 {
		return errs.NewUsageExitError("Project must be supplied", ctx)
	}
	if count > 3 && cpathObj.Org() == "*" {
		return errs.NewUsageExitError("Org must be supplied to view secrets", ctx)
	}
	if count > 3 && cpathObj.Project() == "*" {
		return errs.NewUsageExitError("Project must be supplied to view secrets", ctx)
	}

	var paths []string
	var pathErr error

	showing := "Listing objects for path"
	switch count {
	case 0:
		showing = "Listing orgs:"
		paths, err = orgPaths()
		if err != nil {
			pathErr = errs.NewExitError("Failed to list orgs.")
		}
	case 1:
		partial := "/" + cpathObj.Org()
		showing = "Listing projects within path: " + partial
		paths, err = projectPaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list projects.")
		}
	case 2:
		partial := "/" + cpathObj.Org() + "/" + cpathObj.Project()
		showing = "Listing environments within path: " + partial
		paths, err = envPaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list environments.")
		}
	case 3:
		partial := "/" + cpathObj.Org() + "/" + cpathObj.Project() + "/*"
		showing = "Listing services within path: " + partial
		paths, err = servicePaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list services.")
		}
	default:
		showing = "Listing secrets within path: " + cpathObj.String()
		paths, err = secretPaths(cpathObj)
		if err != nil {
			pathErr = errs.NewExitError("Failed to list secrets.")
		}
	}

	// Print the path and object type of the output
	fmt.Println(showing)

	// Must replace Envs with * when only 3 segments supplied
	if count == 3 && cpathObj.Envs() != "*" {
		fmt.Println("Note: environment exchanged for *")
		fmt.Println("")
	} else {
		fmt.Println("")
	}

	if pathErr != nil {
		return pathErr
	}
	for _, path := range paths {
		fmt.Println(path)
	}

	return nil
}

// generate all paths for /
func orgPaths() ([]string, error) {
	var paths []string

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	for _, org := range orgs {
		paths = append(paths, "/"+org.Body.Name)
	}

	return paths, nil
}

// generate all paths for /${org}
func projectPaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	orgIDs, _, orgMapID, err := filterOrgs(orgs, cpathObj)
	if err != nil {
		return nil, err
	}

	projects, err := listProjectsByOrgID(nil, nil, orgIDs)
	if err != nil {
		return nil, err
	}

	for _, project := range projects {
		pOrgName := orgMapID[*project.Body.OrgID]
		paths = append(paths, fmt.Sprintf("/%s/%s", pOrgName, project.Body.Name))
	}

	return paths, nil
}

// generate all paths for /${org}/${project}
func envPaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string
	c, client, err := NewAPIClient(nil, nil)

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	orgIDs, _, orgMapID, err := filterOrgs(orgs, cpathObj)
	if err != nil {
		return nil, err
	}

	projects, err := listProjectsByOrgID(&c, client, orgIDs)
	if err != nil {
		return nil, err
	}

	projectIDs, projMapID, err := filterProjects(projects, cpathObj)
	if err != nil {
		return nil, err
	}

	envs, err := listEnvsByProjectID(&c, client, projectIDs)
	if err != nil {
		return nil, err
	}

	for _, env := range envs {
		eOrgName := orgMapID[*env.Body.OrgID]
		eProjName := projMapID[*env.Body.ProjectID]
		paths = append(paths, fmt.Sprintf("/%s/%s/%s", eOrgName, eProjName, env.Body.Name))
	}

	return paths, nil
}

// generate all paths for /${org}/${project}/*
func servicePaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string
	c, client, err := NewAPIClient(nil, nil)

	orgs, _, err := orgsList()
	if err != nil {
		return nil, err
	}

	orgIDs, _, orgMapID, err := filterOrgs(orgs, cpathObj)
	if err != nil {
		return nil, err
	}

	projects, err := listProjectsByOrgID(&c, client, orgIDs)
	if err != nil {
		return nil, err
	}

	projectIDs, projMapID, err := filterProjects(projects, cpathObj)
	if err != nil {
		return nil, err
	}

	services, err := listServicesByProjectID(&c, client, projectIDs)
	if err != nil {
		return nil, err
	}

	for _, service := range services {
		sOrgName := orgMapID[*service.Body.OrgID]
		sProjName := projMapID[*service.Body.ProjectID]
		paths = append(paths, fmt.Sprintf("/%s/%s/*/%s", sOrgName, sProjName, service.Body.Name))
	}

	return paths, nil
}

func secretPaths(cpathObj *pathexp.PathExp) ([]string, error) {
	var paths []string
	c, client, err := NewAPIClient(nil, nil)

	creds, err := client.Credentials.Search(c, cpathObj.String())
	if err != nil {
		return nil, err
	}

	cset := credentialSet{}
	for _, c := range creds {
		cset.Add(c)
	}

	for _, cred := range cset {
		body := *cred.Body
		paths = append(paths, fmt.Sprintf("%s/%s", body.GetPathExp(), body.GetName()))
	}
	sort.Strings(paths)

	return paths, nil
}

func filterProjects(projects []api.ProjectResult, pe *pathexp.PathExp) ([]*identity.ID, map[identity.ID]string, error) {
	projMapID := make(map[identity.ID]string, len(projects))
	var projectIDs []*identity.ID
	for _, project := range projects {
		projMapID[*project.ID] = project.Body.Name
		if pe.Project() == "*" {
			projectIDs = append(projectIDs, project.ID)
		} else if project.Body.Name == pe.Project() {
			projectIDs = append(projectIDs, project.ID)
		}
	}
	if len(projectIDs) < 1 {
		return nil, nil, errs.NewExitError("Project not found.")
	}
	return projectIDs, projMapID, nil
}

func filterOrgs(orgs []api.OrgResult, pe *pathexp.PathExp) ([]*identity.ID, map[string]identity.ID, map[identity.ID]string, error) {
	orgMapName := make(map[string]identity.ID, len(orgs))
	orgMapID := make(map[identity.ID]string, len(orgs))

	var orgIDs []*identity.ID
	for _, org := range orgs {
		orgMapName[org.Body.Name] = *org.ID
		orgMapID[*org.ID] = org.Body.Name
		if pe.Org() == "*" || org.Body.Name == pe.Org() {
			orgIDs = append(orgIDs, org.ID)
		}
	}
	if len(orgIDs) < 1 {
		return nil, nil, nil, errs.NewExitError("Org not found.")
	}

	return orgIDs, orgMapName, orgMapID, nil
}
<|endoftext|>


<commit_before>/*
Copyright 2017 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cmd

import (
	log "github.com/Sirupsen/logrus"

	"github.com/kubernetes/kompose/pkg/app"
	"github.com/kubernetes/kompose/pkg/kobject"
	"github.com/spf13/cobra"
)

// TODO: comment
var (
	UpReplicas     int
	UpEmptyVols    bool
	UpVolumes      string
	UpInsecureRepo bool
	UpNamespace    string
	UpOpt          kobject.ConvertOptions
	UpBuild        string
)

var upCmd = &cobra.Command{
	Use:   "up",
	Short: "Deploy your Dockerized application to a container orchestrator.",
	Long:  `Deploy your Dockerized application to a container orchestrator. (default "kubernetes")`,
	PreRun: func(cmd *cobra.Command, args []string) {

		// Check that build-config wasn't passed in with --provider=kubernetes
		if GlobalProvider == "kubernetes" && UpBuild == "build-config" {
			log.Fatalf("build-config is not a valid --build parameter with provider Kubernetes")
		}

		// Create the Convert options.
		UpOpt = kobject.ConvertOptions{
			Build:              UpBuild,
			Replicas:           UpReplicas,
			InputFiles:         GlobalFiles,
			Provider:           GlobalProvider,
			EmptyVols:          UpEmptyVols,
			Volumes:            UpVolumes,
			Namespace:          UpNamespace,
			InsecureRepository: UpInsecureRepo,
			IsNamespaceFlag:    cmd.Flags().Lookup("namespace").Changed,
		}

		// Validate before doing anything else.
		app.ValidateComposeFile(&UpOpt)
	},
	Run: func(cmd *cobra.Command, args []string) {
		app.Up(UpOpt)
	},
}

func init() {
	upCmd.Flags().IntVar(&UpReplicas, "replicas", 1, "Specify the number of replicas generated")
	upCmd.Flags().StringVar(&UpVolumes, "volumes", "persistentVolumeClaim", `Volumes to be generated ("persistentVolumeClaim"|"emptyDir")`)
	upCmd.Flags().BoolVar(&UpInsecureRepo, "insecure-repository", false, "Use an insecure Docker repository for OpenShift ImageStream")
	upCmd.Flags().StringVar(&UpNamespace, "namespace", "default", "Specify Namespace to deploy your application")
	upCmd.Flags().StringVar(&UpBuild, "build", "local", `Set the type of build ("local"|"build-config" (OpenShift only)|"none")`)

	// Deprecated
	upCmd.Flags().BoolVar(&UpEmptyVols, "emptyvols", false, "Use empty volumes. Do not generate PersistentVolumeClaim")
	upCmd.Flags().MarkDeprecated("emptyvols", "emptyvols has been marked as deprecated. Use --volumes empty")

	RootCmd.AddCommand(upCmd)
}
<commit_msg>Adding  --build-branch to `kompose up`<commit_after>/*
Copyright 2017 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cmd

import (
	log "github.com/Sirupsen/logrus"

	"github.com/kubernetes/kompose/pkg/app"
	"github.com/kubernetes/kompose/pkg/kobject"
	"github.com/spf13/cobra"
)

// TODO: comment
var (
	UpReplicas     int
	UpEmptyVols    bool
	UpVolumes      string
	UpInsecureRepo bool
	UpNamespace    string
	UpOpt          kobject.ConvertOptions
	UpBuild        string
	UpBuildBranch  string
)

var upCmd = &cobra.Command{
	Use:   "up",
	Short: "Deploy your Dockerized application to a container orchestrator.",
	Long:  `Deploy your Dockerized application to a container orchestrator. (default "kubernetes")`,
	PreRun: func(cmd *cobra.Command, args []string) {

		// Check that build-config wasn't passed in with --provider=kubernetes
		if GlobalProvider == "kubernetes" && UpBuild == "build-config" {
			log.Fatalf("build-config is not a valid --build parameter with provider Kubernetes")
		}

		// Create the Convert options.
		UpOpt = kobject.ConvertOptions{
			Build:              UpBuild,
			Replicas:           UpReplicas,
			InputFiles:         GlobalFiles,
			Provider:           GlobalProvider,
			EmptyVols:          UpEmptyVols,
			Volumes:            UpVolumes,
			Namespace:          UpNamespace,
			InsecureRepository: UpInsecureRepo,
			BuildBranch:        UpBuildBranch,
			IsNamespaceFlag:    cmd.Flags().Lookup("namespace").Changed,
		}

		// Validate before doing anything else.
		app.ValidateComposeFile(&UpOpt)
	},
	Run: func(cmd *cobra.Command, args []string) {
		app.Up(UpOpt)
	},
}

func init() {
	upCmd.Flags().IntVar(&UpReplicas, "replicas", 1, "Specify the number of replicas generated")
	upCmd.Flags().StringVar(&UpVolumes, "volumes", "persistentVolumeClaim", `Volumes to be generated ("persistentVolumeClaim"|"emptyDir")`)
	upCmd.Flags().BoolVar(&UpInsecureRepo, "insecure-repository", false, "Use an insecure Docker repository for OpenShift ImageStream")
	upCmd.Flags().StringVar(&UpNamespace, "namespace", "default", "Specify Namespace to deploy your application")
	upCmd.Flags().StringVar(&UpBuild, "build", "local", `Set the type of build ("local"|"build-config" (OpenShift only)|"none")`)

	upCmd.Flags().StringVar(&UpBuildBranch, "build-branch", "", "Specify repository branch to use for buildconfig (default master)")
	// Deprecated
	upCmd.Flags().BoolVar(&UpEmptyVols, "emptyvols", false, "Use empty volumes. Do not generate PersistentVolumeClaim")
	upCmd.Flags().MarkDeprecated("emptyvols", "emptyvols has been marked as deprecated. Use --volumes empty")

	RootCmd.AddCommand(upCmd)
}
<|endoftext|>


<commit_before>// SPDX-License-Identifier: MIT

package serialization

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"errors"
	"io"
	"io/fs"
	"path/filepath"

	"golang.org/x/text/feature/plural"
	"golang.org/x/text/language"
	"golang.org/x/text/message"
	"golang.org/x/text/message/catalog"
	"gopkg.in/yaml.v2"
)

type (
	// Locale 提供了从文件中加载本地化信息的方法
	Locale struct {
		b *catalog.Builder
		f *Files
	}

	// TagBuilder 简化 catalog.Builder
	//
	// 为 catalog.Builder.SetString 省略了 tag 参数
	TagBuilder struct {
		builder *catalog.Builder
		tag     language.Tag
	}

	localeMessages struct {
		XMLName  struct{}        `xml:"messages" json:"-" yaml:"-"`
		Language language.Tag    `xml:"language,attr" json:"language" yaml:"language"`
		Messages []localeMessage `xml:"message" json:"messages" yaml:"messages"`
	}

	// localeMessage 单条消息
	localeMessage struct {
		Key     string     `xml:"key" json:"key" yaml:"key"`
		Message localeText `xml:"message" json:"message" yaml:"message"`
	}

	localeText struct {
		Msg    string        `xml:"msg,omitempty" json:"msg,omitempty"  yaml:"msg,omitempty"`
		Select *localeSelect `xml:"select,omitempty" json:"select,omitempty" yaml:"select,omitempty"`
		Vars   []*localeVar  `xml:"var,omitempty" json:"vars,omitempty" yaml:"vars,omitempty"`
	}

	localeSelect struct {
		Arg    int         `xml:"arg,attr" json:"arg" yaml:"arg"`
		Format string      `xml:"format,attr,omitempty" json:"format,omitempty" yaml:"format,omitempty"`
		Cases  localeCases `xml:"case" json:"cases" yaml:"cases"`
	}

	localeVar struct {
		Name   string      `xml:"name,attr" json:"name" yaml:"name"`
		Arg    int         `xml:"arg,attr" json:"arg" yaml:"arg"`
		Format string      `xml:"format,attr,omitempty" json:"format,omitempty" yaml:"format,omitempty"`
		Cases  localeCases `xml:"case" json:"cases" yaml:"cases"`
	}

	localeCases []interface{}

	entry struct {
		XMLName struct{} `xml:"case"`
		Cond    string   `xml:"cond,attr"`
		Value   string   `xml:",chardata"`
	}
)

func buildSelectf(arg int, format string, cases []interface{}) catalog.Message {
	return plural.Selectf(arg, format, cases...)
}

func (v *localeVar) message() catalog.Message {
	msg := buildSelectf(v.Arg, v.Format, v.Cases)
	return catalog.Var(v.Name, msg)
}

func NewLocale(b *catalog.Builder, f *Files) *Locale {
	return &Locale{b: b, f: f}
}

func (b *TagBuilder) SetString(key, msg string) error {
	return b.builder.SetString(b.tag, key, msg)
}

func (b *TagBuilder) Set(key string, msg ...catalog.Message) error {
	return b.builder.Set(b.tag, key, msg...)
}

func (b *TagBuilder) SetMacro(key string, msg ...catalog.Message) error {
	return b.builder.SetMacro(b.tag, key, msg...)
}

// Builder 返回本地化操作的相关接口
func (l *Locale) Builder() *catalog.Builder { return l.b }

func (l *Locale) TagBuilder(tag language.Tag) *TagBuilder {
	return &TagBuilder{
		builder: l.Builder(),
		tag:     tag,
	}
}

func (l *Locale) Printer(tag language.Tag) *message.Printer {
	return message.NewPrinter(tag, message.Catalog(l.Builder()))
}

// LoadFile 从文件中加载本地化内容
func (l *Locale) LoadFile(glob string) error {
	matchs, err := filepath.Glob(glob)
	if err != nil {
		return err
	}

	for _, f := range matchs {
		m := &localeMessages{}
		if err := l.f.Load(f, m); err != nil {
			return err
		}

		if err := l.set(m); err != nil {
			return err
		}
	}

	return nil
}

// LoadFileFS 从文件中加载本地化内容
func (l *Locale) LoadFileFS(fsys fs.FS, glob string) error {
	matchs, err := fs.Glob(fsys, glob)
	if err != nil {
		return err
	}

	for _, f := range matchs {
		m := &localeMessages{}
		if err := l.f.LoadFS(fsys, f, m); err != nil {
			return err
		}

		if err := l.set(m); err != nil {
			return err
		}
	}

	return nil
}

func (l *Locale) set(m *localeMessages) (err error) {
	tag := l.TagBuilder(m.Language)

	for _, msg := range m.Messages {
		switch {
		case msg.Message.Vars != nil:
			vars := msg.Message.Vars
			msgs := make([]catalog.Message, 0, len(vars))
			for _, v := range vars {
				msgs = append(msgs, v.message())
			}
			msgs = append(msgs, catalog.String(msg.Message.Msg))
			err = tag.Set(msg.Key, msgs...)
		case msg.Message.Select != nil:
			s := msg.Message.Select
			err = tag.Set(msg.Key, buildSelectf(s.Arg, s.Format, s.Cases))
		case msg.Message.Msg != "":
			err = tag.SetString(msg.Key, msg.Message.Msg)
		}

		if err != nil {
			return err
		}
	}

	return nil
}

// UnmarshalXML implement xml.Unmarshaler
func (c *localeCases) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	for {
		e := &entry{}
		if err := d.DecodeElement(e, &start); errors.Is(err, io.EOF) {
			return nil
		} else if err != nil {
			return err
		}

		*c = append(*c, e.Cond, e.Value)
	}
}

func (c *localeCases) UnmarshalYAML(unmarshal func(interface{}) error) error {
	kv := yaml.MapSlice{}
	if err := unmarshal(&kv); err != nil {
		return err
	}

	*c = make(localeCases, 0, len(kv))
	for _, item := range kv {
		*c = append(*c, item.Key, item.Value)
	}

	return nil
}

func (c *localeCases) UnmarshalJSON(data []byte) error {
	d := json.NewDecoder(bytes.NewBuffer(data))
	for {
		t, err := d.Token()
		if errors.Is(err, io.EOF) {
			return nil
		} else if err != nil {
			return err
		}

		if t == json.Delim('{') || t == json.Delim('}') {
			continue
		}

		*c = append(*c, t)
	}
}
<commit_msg>refactor(serialization): 简化代码<commit_after>// SPDX-License-Identifier: MIT

package serialization

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"errors"
	"io"
	"io/fs"
	"path/filepath"

	"golang.org/x/text/feature/plural"
	"golang.org/x/text/language"
	"golang.org/x/text/message"
	"golang.org/x/text/message/catalog"
	"gopkg.in/yaml.v2"
)

type (
	// Locale 提供了从文件中加载本地化信息的方法
	Locale struct {
		b *catalog.Builder
		f *Files
	}

	// TagBuilder 简化 catalog.Builder
	//
	// 为 catalog.Builder.SetString 省略了 tag 参数
	TagBuilder struct {
		builder *catalog.Builder
		tag     language.Tag
	}

	localeMessages struct {
		XMLName  struct{}        `xml:"messages" json:"-" yaml:"-"`
		Language language.Tag    `xml:"language,attr" json:"language" yaml:"language"`
		Messages []localeMessage `xml:"message" json:"messages" yaml:"messages"`
	}

	// localeMessage 单条消息
	localeMessage struct {
		Key     string     `xml:"key" json:"key" yaml:"key"`
		Message localeText `xml:"message" json:"message" yaml:"message"`
	}

	localeText struct {
		Msg    string        `xml:"msg,omitempty" json:"msg,omitempty"  yaml:"msg,omitempty"`
		Select *localeSelect `xml:"select,omitempty" json:"select,omitempty" yaml:"select,omitempty"`
		Vars   []*localeVar  `xml:"var,omitempty" json:"vars,omitempty" yaml:"vars,omitempty"`
	}

	localeSelect struct {
		Arg    int         `xml:"arg,attr" json:"arg" yaml:"arg"`
		Format string      `xml:"format,attr,omitempty" json:"format,omitempty" yaml:"format,omitempty"`
		Cases  localeCases `xml:"case" json:"cases" yaml:"cases"`
	}

	localeVar struct {
		Name   string      `xml:"name,attr" json:"name" yaml:"name"`
		Arg    int         `xml:"arg,attr" json:"arg" yaml:"arg"`
		Format string      `xml:"format,attr,omitempty" json:"format,omitempty" yaml:"format,omitempty"`
		Cases  localeCases `xml:"case" json:"cases" yaml:"cases"`
	}

	localeCases []interface{}

	entry struct {
		XMLName struct{} `xml:"case"`
		Cond    string   `xml:"cond,attr"`
		Value   string   `xml:",chardata"`
	}
)

// NewLocale 返回 Locale 实例
//
// f 表示用于加载本地化文件的序列化方法，根据文件扩展名在 f 中查找相应的序列化方法；
// 加载后的内容被应用在 b 之上。
func NewLocale(b *catalog.Builder, f *Files) *Locale { return &Locale{b: b, f: f} }

func (b *TagBuilder) SetString(key, msg string) error {
	return b.builder.SetString(b.tag, key, msg)
}

func (b *TagBuilder) Set(key string, msg ...catalog.Message) error {
	return b.builder.Set(b.tag, key, msg...)
}

func (b *TagBuilder) SetMacro(key string, msg ...catalog.Message) error {
	return b.builder.SetMacro(b.tag, key, msg...)
}

// Files 返回用于序列化文件的实例
func (l *Locale) Files() *Files { return l.f }

// Builder 返回本地化操作的相关接口
func (l *Locale) Builder() *catalog.Builder { return l.b }

func (l *Locale) TagBuilder(tag language.Tag) *TagBuilder {
	return &TagBuilder{
		builder: l.Builder(),
		tag:     tag,
	}
}

func (l *Locale) Printer(tag language.Tag) *message.Printer {
	return message.NewPrinter(tag, message.Catalog(l.Builder()))
}

// LoadFile 从文件中加载本地化内容
func (l *Locale) LoadFile(glob string) error {
	matchs, err := filepath.Glob(glob)
	if err != nil {
		return err
	}

	for _, f := range matchs {
		m := &localeMessages{}
		if err := l.f.Load(f, m); err != nil {
			return err
		}

		if err := l.set(m); err != nil {
			return err
		}
	}

	return nil
}

// LoadFileFS 从文件中加载本地化内容
func (l *Locale) LoadFileFS(fsys fs.FS, glob string) error {
	matchs, err := fs.Glob(fsys, glob)
	if err != nil {
		return err
	}

	for _, f := range matchs {
		m := &localeMessages{}
		if err := l.f.LoadFS(fsys, f, m); err != nil {
			return err
		}

		if err := l.set(m); err != nil {
			return err
		}
	}

	return nil
}

func (l *Locale) set(m *localeMessages) (err error) {
	tag := l.TagBuilder(m.Language)

	for _, msg := range m.Messages {
		switch {
		case msg.Message.Vars != nil:
			vars := msg.Message.Vars
			msgs := make([]catalog.Message, 0, len(vars))
			for _, v := range vars {
				mm := catalog.Var(v.Name, plural.Selectf(v.Arg, v.Format, v.Cases...))
				msgs = append(msgs, mm)
			}
			msgs = append(msgs, catalog.String(msg.Message.Msg))
			err = tag.Set(msg.Key, msgs...)
		case msg.Message.Select != nil:
			s := msg.Message.Select
			err = tag.Set(msg.Key, plural.Selectf(s.Arg, s.Format, s.Cases...))
		case msg.Message.Msg != "":
			err = tag.SetString(msg.Key, msg.Message.Msg)
		}

		if err != nil {
			return err
		}
	}

	return nil
}

// UnmarshalXML implement xml.Unmarshaler
func (c *localeCases) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	for {
		e := &entry{}
		if err := d.DecodeElement(e, &start); errors.Is(err, io.EOF) {
			return nil
		} else if err != nil {
			return err
		}

		*c = append(*c, e.Cond, e.Value)
	}
}

func (c *localeCases) UnmarshalYAML(unmarshal func(interface{}) error) error {
	kv := yaml.MapSlice{}
	if err := unmarshal(&kv); err != nil {
		return err
	}

	*c = make(localeCases, 0, len(kv))
	for _, item := range kv {
		*c = append(*c, item.Key, item.Value)
	}

	return nil
}

func (c *localeCases) UnmarshalJSON(data []byte) error {
	d := json.NewDecoder(bytes.NewBuffer(data))
	for {
		t, err := d.Token()
		if errors.Is(err, io.EOF) {
			return nil
		} else if err != nil {
			return err
		}

		if t == json.Delim('{') || t == json.Delim('}') {
			continue
		}

		*c = append(*c, t)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"time"
)

// Two-way channel
func worker(input chan string) {
	go func() {
		for i := 65; i < 75; i++ {
			input <- string(i)
			time.Sleep(100 * time.Millisecond)
		}
		// Close channel
		close(input)
	}()
}

func workerPrinter(input <-chan string) {
	go func() {
		// Range keyword
		for n := range input {
			fmt.Println("n:", n)
		}
	}()
}

// Write-only channel
func supply(input chan<- string) {
	go func() {
		for {
			input <- "Hello"
			time.Sleep(100 * time.Millisecond)
		}
	}()
}

// Read-only channel
func print(input <-chan string) {
	go func() {
		for i := 0; i < 3; i++ {
			fmt.Println("<-input:", <-input)
		}
	}()
}

func main() {
	// Two-way channel
	c := make(chan string)
	c1 := make(chan string)

	worker(c)
	workerPrinter(c)

	supply(c1)
	print(c1)

	// Buffered channel
	bc := make(chan string, 2)

	go func() {
		bc <- "A"
		bc <- "B"
		bc <- "C"
		bc <- "D"
		bc <- "E"
	}()

	go func() {
		for {
			if len(bc) > 1 {
				fmt.Println("bc:", <-bc)
				time.Sleep(1 * time.Second)
			}
		}
	}()

	var input string
	fmt.Scanln(&input)
}
<commit_msg>Add more examples<commit_after>package main

import (
	"fmt"
	"time"
)

// Two-way channel
func worker(input chan string) {
	go func() {
		for i := 65; i < 75; i++ {
			input <- string(i)
			time.Sleep(100 * time.Millisecond)
		}
		// Close channel
		close(input)
	}()
}

func workerPrinter(input <-chan string) {
	go func() {
		// Range keyword
		for n := range input {
			fmt.Println("n:", n)
		}
	}()
}

// Write-only channel
func supply(input chan<- string) {
	go func() {
		for {
			input <- "Hello"
			time.Sleep(100 * time.Millisecond)
		}
	}()
}

// Read-only channel
func print(input <-chan string) {
	go func() {
		for i := 0; i < 3; i++ {
			fmt.Println("<-input:", <-input)
		}
	}()
}

func main() {
	// Two-way channel
	c := make(chan string)
	c1 := make(chan string)

	worker(c)
	workerPrinter(c)

	supply(c1)
	print(c1)

	// Buffered channel
	bc := make(chan string, 2)

	go func() {
		bc <- "A"
		bc <- "B"
		bc <- "C"
		bc <- "D"
		bc <- "E"
	}()

	go func() {
		for {
			if len(bc) > 1 {
				fmt.Println("bc:", <-bc)
				time.Sleep(1 * time.Second)
			}
		}
	}()

	// Nested channel
	nc := make(chan chan string)

	go func() {
		c := make(chan string)
		nc <- c
		fmt.Println("<-c:", <-c)
	}()

	go func() {
		select {
		case c := <-nc:
			c <- "Done"
		}
	}()

	var input string
	fmt.Scanln(&input)
}
<|endoftext|>


<commit_before>package core

import "encoding/binary"

const (
	SEQEND       = 0
	LITERAL_EXPR = 1
	VECTOR_EXPR  = 2
	MAP_EXPR     = 3
	SET_EXPR     = 4
	IF_EXPR      = 5
	DEF_EXPR     = 6
	INT          = 100
)

type (
	PackEnv struct {
		Strings         map[*string]uint16
		nextStringIndex uint16
	}

	PackHeader struct {
		Strings []*string
	}
)

func (env *PackEnv) stringIndex(s *string) uint16 {
	index, ok := env.Strings[s]
	if ok {
		return index
	}
	env.Strings[s] = env.nextStringIndex
	env.nextStringIndex++
	return env.nextStringIndex - 1
}

func appendBool(p []byte, b bool) []byte {
	var bb byte
	if b {
		bb = 1
	}
	return append(p, bb)
}

func extractBool(p []byte) (bool, []byte) {
	var b bool
	if p[0] == 1 {
		b = true
	}
	return b, p[1:]
}

func appendUint16(p []byte, i uint16) []byte {
	pp := make([]byte, 2)
	binary.BigEndian.PutUint16(pp, i)
	p = append(p, pp...)
	return p
}

func extractUInt16(p []byte) (uint16, []byte) {
	return binary.BigEndian.Uint16(p[0:2]), p[2:]
}

func appendUint32(p []byte, i uint32) []byte {
	pp := make([]byte, 4)
	binary.BigEndian.PutUint32(pp, i)
	p = append(p, pp...)
	return p
}

func extractUInt32(p []byte) (uint32, []byte) {
	return binary.BigEndian.Uint32(p[0:4]), p[4:]
}

func appendInt(p []byte, i int) []byte {
	pp := make([]byte, 8)
	binary.BigEndian.PutUint64(pp, uint64(i))
	p = append(p, pp...)
	return p
}

func extractInt(p []byte) (int, []byte) {
	return int(binary.BigEndian.Uint64(p[0:8])), p[8:]
}

func (pos Position) Pack(p []byte, env *PackEnv) []byte {
	p = appendInt(p, pos.startLine)
	p = appendInt(p, pos.endLine)
	p = appendInt(p, pos.startColumn)
	p = appendInt(p, pos.endColumn)
	p = appendUint16(p, env.stringIndex(pos.filename))
	return p
}

func unpackPosition(p []byte, header *PackHeader) (pos Position, pp []byte) {
	pos.startLine, p = extractInt(p)
	pos.endLine, p = extractInt(p)
	pos.startColumn, p = extractInt(p)
	pos.endColumn, p = extractInt(p)
	i, p := extractUInt16(p)
	pos.filename = header.Strings[i]
	return pos, p
}

func (i Int) Pack(p []byte, env *PackEnv) []byte {
	p = i.info.Pack(p, env)
	p = appendInt(p, i.I)
	return p
}

func unpackInt(p []byte) (Int, []byte) {
	i, p := extractInt(p)
	return MakeInt(i), p
}

func (info *ObjectInfo) Pack(p []byte, env *PackEnv) []byte {
	return info.Pos().Pack(p, env)
}

func unpackObjectInfo(p []byte, header *PackHeader) (*ObjectInfo, []byte) {
	pos, p := unpackPosition(p, header)
	return &ObjectInfo{Position: pos}, p
}

func (s Symbol) Pack(p []byte, env *PackEnv) []byte {
	p = s.info.Pack(p, env)
	p = appendUint16(p, env.stringIndex(s.name))
	p = appendUint16(p, env.stringIndex(s.ns))
	p = appendUint32(p, s.hash)
	return p
}

func unpackSymbol(p []byte, header *PackHeader) (Symbol, []byte) {
	info, p := unpackObjectInfo(p, header)
	iname, p := extractUInt16(p)
	ins, p := extractUInt16(p)
	hash, p := extractUInt32(p)
	res := Symbol{
		InfoHolder: InfoHolder{info: info},
		name:       header.Strings[iname],
		ns:         header.Strings[ins],
		hash:       hash,
	}
	return res, p
}

func unpackObject(p []byte, header *PackHeader) (Object, []byte) {
	switch p[0] {
	case INT:
		return unpackInt(p[1:])
	default:
		panic(RT.NewError("Unknown pack tag"))
	}
}

func (expr *LiteralExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, LITERAL_EXPR)
	p = expr.Pos().Pack(p, env)
	p = appendBool(p, expr.isSurrogate)
	p = expr.obj.Pack(p, env)
	return p
}

func unpackLiteralExpr(p []byte, header *PackHeader) (*LiteralExpr, []byte) {
	pos, p := unpackPosition(p, header)
	isSurrogate, p := extractBool(p)
	obj, p := unpackObject(p, header)
	res := &LiteralExpr{
		obj:         obj,
		Position:    pos,
		isSurrogate: isSurrogate,
	}
	return res, p
}

func packSeq(p []byte, s []Expr, env *PackEnv) []byte {
	for _, e := range s {
		p = e.Pack(p, env)
	}
	p = append(p, SEQEND)
	return p
}

func unpackSeq(p []byte, header *PackHeader) ([]Expr, []byte) {
	var res []Expr
	for p[0] != SEQEND {
		var e Expr
		e, p = UnpackExpr(p, header)
		res = append(res, e)
	}
	return res, p[1:]
}

func (expr *VectorExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, VECTOR_EXPR)
	p = expr.Pos().Pack(p, env)
	return packSeq(p, expr.v, env)
}

func unpackSetExpr(p []byte, header *PackHeader) (*SetExpr, []byte) {
	pos, p := unpackPosition(p, header)
	v, p := unpackSeq(p, header)
	res := &SetExpr{
		Position: pos,
		elements: v,
	}
	return res, p
}

func (expr *SetExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, SET_EXPR)
	p = expr.Pos().Pack(p, env)
	return packSeq(p, expr.elements, env)
}

func unpackVectorExpr(p []byte, header *PackHeader) (*VectorExpr, []byte) {
	pos, p := unpackPosition(p, header)
	v, p := unpackSeq(p, header)
	res := &VectorExpr{
		Position: pos,
		v:        v,
	}
	return res, p
}

func (expr *MapExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, MAP_EXPR)
	p = expr.Pos().Pack(p, env)
	p = packSeq(p, expr.keys, env)
	p = packSeq(p, expr.values, env)
	return p
}

func unpackMapExpr(p []byte, header *PackHeader) (*MapExpr, []byte) {
	pos, p := unpackPosition(p, header)
	ks, p := unpackSeq(p, header)
	vs, p := unpackSeq(p, header)
	res := &MapExpr{
		Position: pos,
		keys:     ks,
		values:   vs,
	}
	return res, p
}

func (expr *IfExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, IF_EXPR)
	p = expr.Pos().Pack(p, env)
	p = expr.cond.Pack(p, env)
	p = expr.positive.Pack(p, env)
	p = expr.negative.Pack(p, env)
	return p
}

func unpackIfExpr(p []byte, header *PackHeader) (*IfExpr, []byte) {
	pos, p := unpackPosition(p, header)
	cond, p := UnpackExpr(p, header)
	positive, p := UnpackExpr(p, header)
	negative, p := UnpackExpr(p, header)
	res := &IfExpr{
		Position: pos,
		positive: positive,
		negative: negative,
		cond:     cond,
	}
	return res, p
}

func (expr *DefExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, DEF_EXPR)
	p = expr.Pos().Pack(p, env)
	p = expr.name.Pack(p, env)
	p = expr.value.Pack(p, env)
	p = expr.meta.Pack(p, env)
	return p
}

func unpackDefExpr(p []byte, header *PackHeader) (*DefExpr, []byte) {
	pos, p := unpackPosition(p, header)
	name, p := unpackSymbol(p, header)
	value, p := UnpackExpr(p, header)
	meta, p := UnpackExpr(p, header)
	res := &DefExpr{
		Position: pos,
		name:     name,
		value:    value,
		meta:     meta,
	}
	return res, p
}

func UnpackExpr(p []byte, header *PackHeader) (Expr, []byte) {
	switch p[0] {
	case LITERAL_EXPR:
		return unpackLiteralExpr(p[1:], header)
	case VECTOR_EXPR:
		return unpackVectorExpr(p[1:], header)
	case MAP_EXPR:
		return unpackMapExpr(p[1:], header)
	case SET_EXPR:
		return unpackSetExpr(p[1:], header)
	case IF_EXPR:
		return unpackIfExpr(p[1:], header)
	case DEF_EXPR:
		return unpackDefExpr(p[1:], header)
	default:
		panic(RT.NewError("Unknown pack tag"))
	}
}
<commit_msg>Pack CallExpr<commit_after>package core

import "encoding/binary"

const (
	SEQEND       = 0
	LITERAL_EXPR = 1
	VECTOR_EXPR  = 2
	MAP_EXPR     = 3
	SET_EXPR     = 4
	IF_EXPR      = 5
	DEF_EXPR     = 6
	CALL_EXPR    = 7
	INT          = 100
)

type (
	PackEnv struct {
		Strings         map[*string]uint16
		nextStringIndex uint16
	}

	PackHeader struct {
		Strings []*string
	}
)

func (env *PackEnv) stringIndex(s *string) uint16 {
	index, ok := env.Strings[s]
	if ok {
		return index
	}
	env.Strings[s] = env.nextStringIndex
	env.nextStringIndex++
	return env.nextStringIndex - 1
}

func appendBool(p []byte, b bool) []byte {
	var bb byte
	if b {
		bb = 1
	}
	return append(p, bb)
}

func extractBool(p []byte) (bool, []byte) {
	var b bool
	if p[0] == 1 {
		b = true
	}
	return b, p[1:]
}

func appendUint16(p []byte, i uint16) []byte {
	pp := make([]byte, 2)
	binary.BigEndian.PutUint16(pp, i)
	p = append(p, pp...)
	return p
}

func extractUInt16(p []byte) (uint16, []byte) {
	return binary.BigEndian.Uint16(p[0:2]), p[2:]
}

func appendUint32(p []byte, i uint32) []byte {
	pp := make([]byte, 4)
	binary.BigEndian.PutUint32(pp, i)
	p = append(p, pp...)
	return p
}

func extractUInt32(p []byte) (uint32, []byte) {
	return binary.BigEndian.Uint32(p[0:4]), p[4:]
}

func appendInt(p []byte, i int) []byte {
	pp := make([]byte, 8)
	binary.BigEndian.PutUint64(pp, uint64(i))
	p = append(p, pp...)
	return p
}

func extractInt(p []byte) (int, []byte) {
	return int(binary.BigEndian.Uint64(p[0:8])), p[8:]
}

func (pos Position) Pack(p []byte, env *PackEnv) []byte {
	p = appendInt(p, pos.startLine)
	p = appendInt(p, pos.endLine)
	p = appendInt(p, pos.startColumn)
	p = appendInt(p, pos.endColumn)
	p = appendUint16(p, env.stringIndex(pos.filename))
	return p
}

func unpackPosition(p []byte, header *PackHeader) (pos Position, pp []byte) {
	pos.startLine, p = extractInt(p)
	pos.endLine, p = extractInt(p)
	pos.startColumn, p = extractInt(p)
	pos.endColumn, p = extractInt(p)
	i, p := extractUInt16(p)
	pos.filename = header.Strings[i]
	return pos, p
}

func (i Int) Pack(p []byte, env *PackEnv) []byte {
	p = i.info.Pack(p, env)
	p = appendInt(p, i.I)
	return p
}

func unpackInt(p []byte) (Int, []byte) {
	i, p := extractInt(p)
	return MakeInt(i), p
}

func (info *ObjectInfo) Pack(p []byte, env *PackEnv) []byte {
	return info.Pos().Pack(p, env)
}

func unpackObjectInfo(p []byte, header *PackHeader) (*ObjectInfo, []byte) {
	pos, p := unpackPosition(p, header)
	return &ObjectInfo{Position: pos}, p
}

func (s Symbol) Pack(p []byte, env *PackEnv) []byte {
	p = s.info.Pack(p, env)
	p = appendUint16(p, env.stringIndex(s.name))
	p = appendUint16(p, env.stringIndex(s.ns))
	p = appendUint32(p, s.hash)
	return p
}

func unpackSymbol(p []byte, header *PackHeader) (Symbol, []byte) {
	info, p := unpackObjectInfo(p, header)
	iname, p := extractUInt16(p)
	ins, p := extractUInt16(p)
	hash, p := extractUInt32(p)
	res := Symbol{
		InfoHolder: InfoHolder{info: info},
		name:       header.Strings[iname],
		ns:         header.Strings[ins],
		hash:       hash,
	}
	return res, p
}

func unpackObject(p []byte, header *PackHeader) (Object, []byte) {
	switch p[0] {
	case INT:
		return unpackInt(p[1:])
	default:
		panic(RT.NewError("Unknown pack tag"))
	}
}

func (expr *LiteralExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, LITERAL_EXPR)
	p = expr.Pos().Pack(p, env)
	p = appendBool(p, expr.isSurrogate)
	p = expr.obj.Pack(p, env)
	return p
}

func unpackLiteralExpr(p []byte, header *PackHeader) (*LiteralExpr, []byte) {
	pos, p := unpackPosition(p, header)
	isSurrogate, p := extractBool(p)
	obj, p := unpackObject(p, header)
	res := &LiteralExpr{
		obj:         obj,
		Position:    pos,
		isSurrogate: isSurrogate,
	}
	return res, p
}

func packSeq(p []byte, s []Expr, env *PackEnv) []byte {
	for _, e := range s {
		p = e.Pack(p, env)
	}
	p = append(p, SEQEND)
	return p
}

func unpackSeq(p []byte, header *PackHeader) ([]Expr, []byte) {
	var res []Expr
	for p[0] != SEQEND {
		var e Expr
		e, p = UnpackExpr(p, header)
		res = append(res, e)
	}
	return res, p[1:]
}

func (expr *VectorExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, VECTOR_EXPR)
	p = expr.Pos().Pack(p, env)
	return packSeq(p, expr.v, env)
}

func unpackSetExpr(p []byte, header *PackHeader) (*SetExpr, []byte) {
	pos, p := unpackPosition(p, header)
	v, p := unpackSeq(p, header)
	res := &SetExpr{
		Position: pos,
		elements: v,
	}
	return res, p
}

func (expr *SetExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, SET_EXPR)
	p = expr.Pos().Pack(p, env)
	return packSeq(p, expr.elements, env)
}

func unpackVectorExpr(p []byte, header *PackHeader) (*VectorExpr, []byte) {
	pos, p := unpackPosition(p, header)
	v, p := unpackSeq(p, header)
	res := &VectorExpr{
		Position: pos,
		v:        v,
	}
	return res, p
}

func (expr *MapExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, MAP_EXPR)
	p = expr.Pos().Pack(p, env)
	p = packSeq(p, expr.keys, env)
	p = packSeq(p, expr.values, env)
	return p
}

func unpackMapExpr(p []byte, header *PackHeader) (*MapExpr, []byte) {
	pos, p := unpackPosition(p, header)
	ks, p := unpackSeq(p, header)
	vs, p := unpackSeq(p, header)
	res := &MapExpr{
		Position: pos,
		keys:     ks,
		values:   vs,
	}
	return res, p
}

func (expr *IfExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, IF_EXPR)
	p = expr.Pos().Pack(p, env)
	p = expr.cond.Pack(p, env)
	p = expr.positive.Pack(p, env)
	p = expr.negative.Pack(p, env)
	return p
}

func unpackIfExpr(p []byte, header *PackHeader) (*IfExpr, []byte) {
	pos, p := unpackPosition(p, header)
	cond, p := UnpackExpr(p, header)
	positive, p := UnpackExpr(p, header)
	negative, p := UnpackExpr(p, header)
	res := &IfExpr{
		Position: pos,
		positive: positive,
		negative: negative,
		cond:     cond,
	}
	return res, p
}

func (expr *DefExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, DEF_EXPR)
	p = expr.Pos().Pack(p, env)
	p = expr.name.Pack(p, env)
	p = expr.value.Pack(p, env)
	p = expr.meta.Pack(p, env)
	return p
}

func unpackDefExpr(p []byte, header *PackHeader) (*DefExpr, []byte) {
	pos, p := unpackPosition(p, header)
	name, p := unpackSymbol(p, header)
	value, p := UnpackExpr(p, header)
	meta, p := UnpackExpr(p, header)
	res := &DefExpr{
		Position: pos,
		name:     name,
		value:    value,
		meta:     meta,
	}
	return res, p
}

func (expr *CallExpr) Pack(p []byte, env *PackEnv) []byte {
	p = append(p, CALL_EXPR)
	p = expr.Pos().Pack(p, env)
	p = expr.callable.Pack(p, env)
	p = packSeq(p, expr.args, env)
	return p
}

func unpackCallExpr(p []byte, header *PackHeader) (*CallExpr, []byte) {
	pos, p := unpackPosition(p, header)
	callable, p := UnpackExpr(p, header)
	args, p := unpackSeq(p, header)
	res := &CallExpr{
		Position: pos,
		callable: callable,
		args:     args,
	}
	return res, p
}

func UnpackExpr(p []byte, header *PackHeader) (Expr, []byte) {
	switch p[0] {
	case LITERAL_EXPR:
		return unpackLiteralExpr(p[1:], header)
	case VECTOR_EXPR:
		return unpackVectorExpr(p[1:], header)
	case MAP_EXPR:
		return unpackMapExpr(p[1:], header)
	case SET_EXPR:
		return unpackSetExpr(p[1:], header)
	case IF_EXPR:
		return unpackIfExpr(p[1:], header)
	case DEF_EXPR:
		return unpackDefExpr(p[1:], header)
	case CALL_EXPR:
		return unpackCallExpr(p[1:], header)
	default:
		panic(RT.NewError("Unknown pack tag"))
	}
}
<|endoftext|>


<commit_before>package common

import (
	"log"
	"time"
)

type GitHubAPIKeyChain struct {
	GitHubAPIKeys []GitHubAPIKeyModel
}

func NewGitHubAPIKeyChain() *GitHubAPIKeyChain {
	log.Println("CREATING NEW KEYCHAIN")
	newGitHubAPIKeyChain := GitHubAPIKeyChain{}
	newGitHubAPIKeyChain.GitHubAPIKeys = make([]GitHubAPIKeyModel, 0)

	keys := []string{"79aed53b9efda8b1b62512d53b0308dbc3e0511f"}

	// For each api key create a new key model and push to the the list of GitHubAPIKeys
	for _, key := range keys {
		log.Println("KEY =", key)
		gitHubAPIKeyModel := GitHubAPIKeyModel{
			string(key),
			5000,
			5000,
			time.Time{},
		}

		newGitHubAPIKeyChain.GitHubAPIKeys = append(newGitHubAPIKeyChain.GitHubAPIKeys, gitHubAPIKeyModel)
	}

	return &newGitHubAPIKeyChain
}

func (gitHubAPIKeyChain *GitHubAPIKeyChain) getAPIKeyModel() *GitHubAPIKeyModel {
	return &gitHubAPIKeyChain.GitHubAPIKeys[0]
}
<commit_msg>updates<commit_after>package common

import (
	"log"
	"time"
)

type GitHubAPIKeyChain struct {
	GitHubAPIKeys []GitHubAPIKeyModel
	CurrentKey    GitHubAPIKeyModel
}

func NewGitHubAPIKeyChain() *GitHubAPIKeyChain {
	log.Println("CREATING NEW KEYCHAIN")
	newGitHubAPIKeyChain := GitHubAPIKeyChain{}
	newGitHubAPIKeyChain.GitHubAPIKeys = make([]GitHubAPIKeyModel, 0)

	keys := []string{}

	// For each api key create a new key model and push to the the list of GitHubAPIKeys
	for _, key := range keys {
		log.Println("KEY =", key)
		gitHubAPIKeyModel := GitHubAPIKeyModel{
			string(key),
			5000,
			5000,
			time.Time{},
		}
		log.Println("Priming API KEY")
		gitHubAPIKeyModel.prime()
		gitHubAPIKeyModel.print()

		newGitHubAPIKeyChain.GitHubAPIKeys = append(newGitHubAPIKeyChain.GitHubAPIKeys, gitHubAPIKeyModel)
	}

	//TODO sort
	newGitHubAPIKeyChain.setCurrentKey()
	return &newGitHubAPIKeyChain
}

func (gitHubAPIKeyChain *GitHubAPIKeyChain) getAPIKeyModel() *GitHubAPIKeyModel {
	if gitHubAPIKeyChain.CurrentKey.RemainingUses > 0 {
		return &gitHubAPIKeyChain.CurrentKey
	}
	log.Println("KEY NEEDS TO BE SWAPED")
	newGitHubAPIKeys := make([]GitHubAPIKeyModel, 0)
	var swapModel GitHubAPIKeyModel
	for index, APIKeyModel := range gitHubAPIKeyChain.GitHubAPIKeys {
		if index == 0 {
			swapModel = APIKeyModel
		} else {
			newGitHubAPIKeys = append(newGitHubAPIKeys, APIKeyModel)
		}
	}
	newGitHubAPIKeys = append(newGitHubAPIKeys, swapModel)
	gitHubAPIKeyChain.GitHubAPIKeys = newGitHubAPIKeys
	gitHubAPIKeyChain.setCurrentKey()

	if gitHubAPIKeyChain.CurrentKey.RemainingUses == 0 {
		coolDown(gitHubAPIKeyChain.CurrentKey)
	}

	return &gitHubAPIKeyChain.CurrentKey
}

func (gitHubAPIKeyChain *GitHubAPIKeyChain) setCurrentKey() {
	if len(gitHubAPIKeyChain.GitHubAPIKeys) == 0 {
		gitHubAPIKeyChain.CurrentKey = GitHubAPIKeyModel{}
	}

	gitHubAPIKeyChain.CurrentKey = gitHubAPIKeyChain.GitHubAPIKeys[0]

}

func coolDown(apiKeyModel GitHubAPIKeyModel) {
	timeNow := time.Now()
	log.Println("Time now = ", timeNow)
	resetTime := apiKeyModel.RateLimitResetTime
	log.Println("Reset time = ", resetTime)

	sleepTime := resetTime.Sub(timeNow)
	log.Println("Sleep time is = ", sleepTime)
	time.Sleep(sleepTime)
}
<|endoftext|>


<commit_before>package compiler

import (
  "testing"
  "bitbucket.org/yyuu/bs/ast"
  "bitbucket.org/yyuu/bs/core"
  "bitbucket.org/yyuu/bs/entity"
  "bitbucket.org/yyuu/bs/typesys"
//"bitbucket.org/yyuu/bs/xt"
)

func setupTypeResolver(a *ast.AST, table *typesys.TypeTable) *TypeResolver {
  resolver := NewTypeResolver(table)
  resolver.defineTypes(a.ListTypes())
  return resolver
}

func TestTypeResolverVisitNodeEmpty(t *testing.T) {
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(
        // TODO
      ),
      ast.NewUnionNodes(
        // TODO
      ),
      ast.NewTypedefNodes(
        // TODO
      ),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  types := a.ListTypes()
  for i := range types {
    ast.VisitNode(resolver, types[i])
  }
  // TODO: write tests
}

func TestTypeResolverWithStruct(t *testing.T) {
/*
  struct foo {
    int n
    int m
  };
 */
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(
        ast.NewStructNode(
          loc,
          typesys.NewStructTypeRef(loc, "foo"),
          "foo",
          []core.ISlot {
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "n"),
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "m"),
          },
        ),
      ),
      ast.NewUnionNodes(),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  types := a.ListTypes()
  for i := range types {
    ast.VisitNode(resolver, types[i])
  }
  // TODO: add asserts
  t.SkipNow()
}

func TestTypeResolverWithUnion(t *testing.T) {
/*
  union foo {
    short n
    int m
  };
 */
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(),
      ast.NewUnionNodes(
        ast.NewUnionNode(
          loc,
          typesys.NewUnionTypeRef(loc, "foo"),
          "foo",
          []core.ISlot {
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "n"),
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "m"),
          },
        ),
      ),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  types := a.ListTypes()
  for i := range types {
    ast.VisitNode(resolver, types[i])
  }
  // FIXME: add asserts
  t.SkipNow()
}

func TestTypeResolverVisitEntity(t *testing.T) {
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(),
      ast.NewUnionNodes(),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  entities := a.ListEntities()
  for i := range entities {
    entity.VisitEntity(resolver, entities[i])
  }
  // TODO: add asserts
  t.SkipNow()
}
<commit_msg>Add tests for TypeResolver, but it is broken for now<commit_after>package compiler

import (
  "testing"
  "bitbucket.org/yyuu/bs/ast"
  "bitbucket.org/yyuu/bs/core"
  "bitbucket.org/yyuu/bs/entity"
  "bitbucket.org/yyuu/bs/typesys"
//"bitbucket.org/yyuu/bs/xt"
)

func setupTypeResolver(a *ast.AST, table *typesys.TypeTable) *TypeResolver {
  resolver := NewTypeResolver(table)
  resolver.defineTypes(a.ListTypes())
  return resolver
}

func TestTypeResolverVisitNodeEmpty(t *testing.T) {
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(
        // TODO
      ),
      ast.NewUnionNodes(
        // TODO
      ),
      ast.NewTypedefNodes(
        // TODO
      ),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  types := a.ListTypes()
  for i := range types {
    ast.VisitNode(resolver, types[i])
  }
  // TODO: write tests
}

func TestTypeResolverWithStruct(t *testing.T) {
/*
  struct foo {
    int n
    int m
  };
 */
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(
        ast.NewStructNode(
          loc,
          typesys.NewStructTypeRef(loc, "foo"),
          "foo",
          []core.ISlot {
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "n"),
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "m"),
          },
        ),
      ),
      ast.NewUnionNodes(),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  types := a.ListTypes()
  for i := range types {
    ast.VisitNode(resolver, types[i])
  }
  // TODO: add asserts
  t.SkipNow()
}

func TestTypeResolverWithUnion(t *testing.T) {
/*
  union foo {
    short n
    int m
  };
 */
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(),
      ast.NewUnionNodes(
        ast.NewUnionNode(
          loc,
          typesys.NewUnionTypeRef(loc, "foo"),
          "foo",
          []core.ISlot {
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "n"),
            ast.NewSlot(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "m"),
          },
        ),
      ),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  types := a.ListTypes()
  for i := range types {
    ast.VisitNode(resolver, types[i])
  }
  // FIXME: add asserts
  t.SkipNow()
}

func TestTypeResolverVisitEntity(t *testing.T) {
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(),
      ast.NewUnionNodes(),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  entities := a.ListEntities()
  for i := range entities {
    entity.VisitEntity(resolver, entities[i])
  }
  // TODO: add asserts
  t.SkipNow()
}

func TestTypeResolverWithFunctionWithoutArguments(t *testing.T) {
/*
  void hello() {
    println("hello, world");
  }
 */
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(
        entity.NewDefinedFunction(
          false,
          ast.NewTypeNode(loc, typesys.NewVoidTypeRef(loc)),
          "hello",
          entity.NewParams(loc,
            entity.NewParameters(),
          ),
          ast.NewBlockNode(loc,
            entity.NewDefinedVariables(),
            []core.IStmtNode {
              ast.NewExprStmtNode(loc,
                ast.NewFuncallNode(loc,
                  ast.NewVariableNode(loc, "println"),
                  []core.IExprNode {
                    ast.NewStringLiteralNode(loc, "\"hello, world\""),
                  },
                ),
              ),
            },
          ),
        ),
      ),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(),
      ast.NewUnionNodes(),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  entities := a.ListEntities()
  for i := range entities {
    entity.VisitEntity(resolver, entities[i])
  }
  // TODO: add asserts
}

func TestTypeResolverWithFunctionWithArguments(t *testing.T) {
/*
  int main(int argc, char*[] argv) {
    println("hello, world");
  }
 */
  loc := core.NewLocation("", 0, 0)
  a := ast.NewAST(loc,
    ast.NewDeclarations(
      entity.NewDefinedVariables(),
      entity.NewUndefinedVariables(),
      entity.NewDefinedFunctions(
        entity.NewDefinedFunction(
          false,
          ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)),
          "main",
          entity.NewParams(loc,
            entity.NewParameters(
              entity.NewParameter(ast.NewTypeNode(loc, typesys.NewIntTypeRef(loc)), "argc"),
              entity.NewParameter(ast.NewTypeNode(loc, typesys.NewArrayTypeRef(typesys.NewPointerTypeRef(typesys.NewCharTypeRef(loc)), 0)), "argv"),
            ),
          ),
          ast.NewBlockNode(loc,
            entity.NewDefinedVariables(),
            []core.IStmtNode {
              ast.NewExprStmtNode(loc,
                ast.NewFuncallNode(loc,
                  ast.NewVariableNode(loc, "println"),
                  []core.IExprNode {
                    ast.NewStringLiteralNode(loc, "\"hello, world\""),
                  },
                ),
              ),
            },
          ),
        ),
      ),
      entity.NewUndefinedFunctions(),
      entity.NewConstants(),
      ast.NewStructNodes(),
      ast.NewUnionNodes(),
      ast.NewTypedefNodes(),
    ),
  )
  table := typesys.NewTypeTableFor("x86-linux")
  resolver := setupTypeResolver(a, table)

  entities := a.ListEntities()
  for i := range entities {
    entity.VisitEntity(resolver, entities[i])
  }
  // TODO: add asserts
}
<|endoftext|>