<commit_before>package commands

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"github.com/Shopify/themekit/kit"
	"github.com/Shopify/themekit/theme"
)

// DownloadCommand downloads file(s) from theme
func DownloadCommand(args Args, done chan bool) {
	if len(args.Filenames) <= 0 {
		for _, asset := range args.ThemeClient.AssetList() {
			if err := writeToDisk(asset); err == nil {
				client.Message(kit.GreenText(fmt.Sprintf("Successfully wrote %s to disk", filename)))
			} else {
				kit.Fatal(err)
			}
		}
	} else {
		for _, filename := range args.Filenames {
			if asset, err := args.ThemeClient.Asset(filename); err != nil {
				if nonFatal, ok := err.(kit.NonFatalNetworkError); ok {
					args.ThemeClient.Message("[%s] Could not complete %s for %s", kit.RedText(fmt.Sprintf("%d", nonFatal.Code)), kit.YellowText(nonFatal.Verb), kit.BlueText(filename))
				} else {
					kit.Fatal(err)
				}
			} else {
				if err := writeToDisk(asset); err == nil {
					client.Message(kit.GreenText(fmt.Sprintf("Successfully wrote %s to disk", filename)))
				} else {
					kit.Fatal(err)
				}
			}
		}
	}
	done <- true
}

func writeToDisk(asset theme.Asset) error {
	dir, err := os.Getwd()
	if err != nil {
		return err
	}

	perms, err := os.Stat(dir)
	if err != nil {
		return err
	}

	filename := fmt.Sprintf("%s/%s", dir, asset.Key)
	err = os.MkdirAll(filepath.Dir(filename), perms.Mode())
	if err != nil {
		return err
	}

	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Sync()
	defer file.Close()

	var data []byte
	switch {
	case len(asset.Value) > 0:
		data = []byte(asset.Value)
	case len(asset.Attachment) > 0:
		data, err = base64.StdEncoding.DecodeString(asset.Attachment)
		if err != nil {
			return fmt.Errorf("Could not decode %s. error: %s", asset.Key, err)
		}
	}

	if len(data) > 0 {
		_, err = prettyWrite(file, data)
	}

	return err
}

func prettyWrite(file *os.File, data []byte) (n int, err error) {
	switch filepath.Ext(file.Name()) {
	case ".json":
		var out bytes.Buffer
		json.Indent(&out, data, "", "\t")
		return file.Write(out.Bytes())
	default:
		return file.Write(data)
	}
}
<commit_msg>fixed the bad stashed applied code<commit_after>package commands

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"github.com/Shopify/themekit/kit"
	"github.com/Shopify/themekit/theme"
)

// DownloadCommand downloads file(s) from theme
func DownloadCommand(args Args, done chan bool) {
	if len(args.Filenames) <= 0 {
		for _, asset := range args.ThemeClient.AssetList() {
			if err := writeToDisk(args.ThemeClient, asset); err != nil {
				kit.Fatal(err)
			}
		}
	} else {
		for _, filename := range args.Filenames {
			if asset, err := args.ThemeClient.Asset(filename); err != nil {
				if nonFatal, ok := err.(kit.NonFatalNetworkError); ok {
					args.ThemeClient.Message("[%s] Could not complete %s for %s", kit.RedText(fmt.Sprintf("%d", nonFatal.Code)), kit.YellowText(nonFatal.Verb), kit.BlueText(filename))
				} else {
					kit.Fatal(err)
				}
			} else {
				if err := writeToDisk(args.ThemeClient, asset); err != nil {
					kit.Fatal(err)
				}
			}
		}
	}
	done <- true
}

func writeToDisk(client kit.ThemeClient, asset theme.Asset) error {
	dir, err := os.Getwd()
	if err != nil {
		return err
	}

	perms, err := os.Stat(dir)
	if err != nil {
		return err
	}

	filename := fmt.Sprintf("%s/%s", dir, asset.Key)
	err = os.MkdirAll(filepath.Dir(filename), perms.Mode())
	if err != nil {
		return err
	}

	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Sync()
	defer file.Close()

	var data []byte
	switch {
	case len(asset.Value) > 0:
		data = []byte(asset.Value)
	case len(asset.Attachment) > 0:
		data, err = base64.StdEncoding.DecodeString(asset.Attachment)
		if err != nil {
			return fmt.Errorf("Could not decode %s. error: %s", asset.Key, err)
		}
	}

	if len(data) > 0 {
		_, err = prettyWrite(file, data)
	}

	if err != nil {
		return err
	}

	client.Message(kit.GreenText(fmt.Sprintf("Successfully wrote %s to disk", filename)))

	return nil
}

func prettyWrite(file *os.File, data []byte) (n int, err error) {
	switch filepath.Ext(file.Name()) {
	case ".json":
		var out bytes.Buffer
		json.Indent(&out, data, "", "\t")
		return file.Write(out.Bytes())
	default:
		return file.Write(data)
	}
}
<|endoftext|>


<commit_before>package sqlgen

import (
	"fmt"
	"strings"

	"github.com/rbastic/dyndao/schema"
)

func (s *SQLBuilder) From(tblName string, tblPrefix string) string {
	return tblName + " " + tblPrefix
}

func (s *SQLBuilder) Where(str string) string {
	return str
}

// For PK-based queries
func (s *SQLBuilder) Eq(colName string, value int64) string {
	return colName + " = " + fmt.Sprint(value)
}
func (s *SQLBuilder) Lt(colName string, value int64) string {
	return colName + " < " + fmt.Sprint(value)
}
func (s *SQLBuilder) LtEq(colName string, value int64) string {
	return colName + " <=" + fmt.Sprint(value)
}

func (s *SQLBuilder) Gt(colName string, value int64) string {
	return colName + " > " + fmt.Sprint(value)
}
func (s *SQLBuilder) GtEq(colName string, value int64) string {
	return colName + " >= " + fmt.Sprint(value)
}

func (s *SQLBuilder) Limit(numRows int64) string {
	return "LIMIT " + fmt.Sprint(numRows)
}

func (s *SQLBuilder) Top(numRows int64) string {
	return "TOP " + fmt.Sprint(numRows)
}

func (s *SQLBuilder) RowNum(numRows int64) string {
	return "ROWNUM <" + fmt.Sprint(numRows)

}

// Paging select function
func (s *SQLBuilder) PagedSelect(cols, from, where, pkCol string, pkValue int64, numRows int64) string {
	if pkValue > 0 {
		where = s.GtEq(pkCol, pkValue)
	}

	// this should be in the adapter but for now it's here.
	if s.IsSQLITE || s.IsPOSTGRES || s.IsMYSQL {
		limit := s.Limit(numRows)
		where = where + " " + limit
	} else if s.IsORACLE {
		rownum := s.RowNum(numRows)
		if where != "" {
			where = where + " AND " + rownum
		} else {
			where = rownum
		}
	} else if s.IsMSSQL {
		top := s.Top(numRows)
		cols = top + " " + cols
	} else {
		panic("Unrecognized driver type")
	}

	// NOTE: will not handle column alias
	where = where + " ORDER BY " + pkCol
	return s.SelectWhere(cols, from, where)

}

func (s *SQLBuilder) SelectWhere(cols string, from string, where string) string {
	if where != "" {
		return "SELECT " + cols + " FROM " + from + " WHERE " + where
	}
	return "SELECT " + cols + " FROM " + from
}

func (s *SQLBuilder) Select(cols string, from string) string {
	return "SELECT " + cols + " FROM " + from
}

func (s *SQLBuilder) Columns(cols []string) string {
	return strings.Join(cols, ", ")
}

func (s *SQLBuilder) ColumnsAliased(cols []string, prefix string) []string {
	newCols := make([]string, len(cols))
	for i, v := range cols {
		newCols[i] = prefix + "." + v
	}
	return newCols
}

func (s *SQLBuilder) JSONColumns(schTbl *schema.Table, tblPrefix string, jsonPathAliases map[string]string) ([]string, []string, error) {
	jsonPaths, mappedCols, err := s.MapJSONPaths(s, schTbl, tblPrefix, jsonPathAliases)
	return jsonPaths, mappedCols, err
}
<commit_msg>minor comments, cleanups. testing pending<commit_after>package sqlgen

import (
	"fmt"
	"strings"

	"github.com/rbastic/dyndao/schema"
)

func (s *SQLBuilder) From(tblName string, tblPrefix string) string {
	return tblName + " " + tblPrefix
}

func (s *SQLBuilder) Where(str string) string {
	return str
}

// For PK-based queries
func (s *SQLBuilder) Eq(colName string, value int64) string {
	return colName + " = " + fmt.Sprint(value)
}
func (s *SQLBuilder) Lt(colName string, value int64) string {
	return colName + " < " + fmt.Sprint(value)
}
func (s *SQLBuilder) LtEq(colName string, value int64) string {
	return colName + " <=" + fmt.Sprint(value)
}

func (s *SQLBuilder) Gt(colName string, value int64) string {
	return colName + " > " + fmt.Sprint(value)
}
func (s *SQLBuilder) GtEq(colName string, value int64) string {
	return colName + " >= " + fmt.Sprint(value)
}

func (s *SQLBuilder) Limit(numRows int64) string {
	return "LIMIT " + fmt.Sprint(numRows)
}

func (s *SQLBuilder) Top(numRows int64) string {
	return "TOP " + fmt.Sprint(numRows)
}

func (s *SQLBuilder) RowNum(numRows int64) string {
	return "ROWNUM <" + fmt.Sprint(numRows)

}

// Paging select function
func (s *SQLBuilder) PagedSelect(cols, from, where, pkCol string, pkValue int64, numRows int64) string {
	if pkValue > 0 {
		where = s.GtEq(pkCol, pkValue)
	}

	// this should be in the adapter but for now it's here.
	if s.IsSQLITE || s.IsPOSTGRES || s.IsMYSQL {
		// Append limit to where clause
		limit := s.Limit(numRows)
		where = where + " " + limit
	} else if s.IsORACLE {
		// Oracle requires this strange row num thing
		rownum := s.RowNum(numRows)
		if where != "" {
			where = where + " AND " + rownum
		} else {
			where = rownum
		}
	} else if s.IsMSSQL {
		// Prepend top clause to columns portion
		top := s.Top(numRows)
		cols = top + " " + cols
	} else {
		panic("Unrecognized driver type")
	}

	// NOTE: will not handle column alias? is that a problem..? probably with some
	// SQL flavors. we'll know soon.
	where = where + " ORDER BY " + pkCol
	return s.SelectWhere(cols, from, where)

}

func (s *SQLBuilder) SelectWhere(cols string, from string, where string) string {
	if where != "" {
		return "SELECT " + cols + " FROM " + from + " WHERE " + where
	}
	return "SELECT " + cols + " FROM " + from
}

func (s *SQLBuilder) Select(cols string, from string) string {
	return "SELECT " + cols + " FROM " + from
}

func (s *SQLBuilder) Columns(cols []string) string {
	return strings.Join(cols, ", ")
}

func (s *SQLBuilder) ColumnsAliased(cols []string, prefix string) []string {
	newCols := make([]string, len(cols))
	for i, v := range cols {
		newCols[i] = prefix + "." + v
	}
	return newCols
}

func (s *SQLBuilder) JSONColumns(schTbl *schema.Table, tblPrefix string, jsonPathAliases map[string]string) ([]string, []string, error) {
	return s.MapJSONPaths(s, schTbl, tblPrefix, jsonPathAliases)
}
<|endoftext|>


<commit_before>
package sqlutil

import (
    "fmt"
    "strings"
    "regexp"
    "errors"
    "reflect"
    "database/sql"
)

var (
    ErrSelectOneGetMore = errors.New("SelectOne: got multiple rows")
    errfSelectIntoNonStructType = errFormatFactory("SELECT into non-struct type: %v")
    errfSelectIntoPointerSlices = errFormatFactory("SELECT into non-pointer slices: %v")
    errfSelectIntoNonStructMoreCols = errFormatFactory("SELECT into non-struct, only 1 column requires: %d")
    errfTableMetaNoField = errFormatFactory("SELECT into struct, column %q not in meta of table %q")
)

func (this *dbMap) columnsToFieldIndexList(meta reflect.Type, cols []string) ([][]int, error) {
    fieldIndexList := make([][]int, len(cols))

    table, ok := this.getTableByMeta(meta)
    if !ok {
        table = this.getOrAddPseudoTable(meta)
    }
    for i, colName := range cols {
        if col, ok := table.colDict[colName]; ok {
            if f, ok := meta.FieldByName(col.fieldName); ok {
                fieldIndexList[i] = f.Index
            }
        }
        if fieldIndexList[i] == nil {
            return nil, errfTableMetaNoField(colName, table.tableName)
        }
    }
    return fieldIndexList, nil
}
func checkSlices(holder interface{}, appendToSlice bool) (reflect.Type, error) {
    t := reflect.TypeOf(holder)
    raw := t
    // if not append to holder slices, holder MUST be valid meta for new slices
    if !appendToSlice {
        for t.Kind() == reflect.Ptr {
            t = t.Elem()
        }
        if t.Kind() != reflect.Struct {
            return nil, errfSelectIntoNonStructType(raw)
        }
        return t, nil
    }
    // else; check holder as slices
    if true {
        if t.Kind() != reflect.Ptr {
            return nil, errfSelectIntoPointerSlices(raw)
        }
        if t = t.Elem(); t.Kind() != reflect.Slice {
            return nil, errfSelectIntoPointerSlices(raw)
        }
        return t.Elem(), nil
    }
    return nil, nil
}
func (this *dbMap) selectIntoOrNew(exec SQLExecutor, holder interface{}, appendToSlice bool, query string, args ...interface{}) (list []interface{}, err error) {
    var (
        meta reflect.Type
        elemIsPointer = true
        elemIsStruct = true
        rows    *sql.Rows
        cols    []string
        colN    int
        colToFieldIndex     [][]int
        holderSlice = reflect.Indirect(reflect.ValueOf(holder))
        newSlice []interface{}
    )
    if meta, err = checkSlices(holder, appendToSlice); err != nil {
        return
    }
    if appendToSlice {
        if elemIsPointer = meta.Kind() == reflect.Ptr; elemIsPointer {
            meta = meta.Elem()
        }
        elemIsStruct = meta.Kind() == reflect.Struct
    }

    if len(args) == 1 {
        query, args = this.maybeExpandNamedQuery(query, args)
    }

    if rows, err = exec.Query(query, args...); err != nil {
        return
    }
    defer rows.Close()

    if cols, err = rows.Columns(); err != nil {
        return
    }
    colN = len(cols)
    if !elemIsStruct && colN > 1 {
        return nil, errfSelectIntoNonStructMoreCols(colN)
    }
    if elemIsStruct {
        if colToFieldIndex, err = this.columnsToFieldIndexList(meta, cols); err != nil {
            return
        }
    }

    dest := make([]interface{}, colN)
    for {
        if !rows.Next() {
            if err = rows.Err(); err != nil {
                return
            }
            break
        }

        pvElem := reflect.New(meta)
        vElem := pvElem.Elem()
        for i := range cols {
            target := vElem
            if elemIsStruct {
                target = target.FieldByIndex(colToFieldIndex[i])
            }
            dest[i] = target.Addr().Interface()
        }

        if err = rows.Scan(dest...); err != nil {
            return
        }

        if appendToSlice {
            if elemIsPointer {
                vElem = pvElem
            }
            holderSlice.Set(reflect.Append(holderSlice, vElem))
        } else {
            newSlice = append(newSlice, pvElem.Interface())
        }
    }

    if appendToSlice {
        //
    } else {
        list = newSlice
    }
    return
}
func (this *dbMap) selectAll(exec SQLExecutor, slices interface{}, query string, args ...interface{}) (rows int64, err error) {
    if _, err = this.selectIntoOrNew(exec, slices, true, query, args...); err != nil {
        return
    }
    triggerArgs := triggerArg(exec)
    vslices := reflect.Indirect(reflect.ValueOf(slices))
    rows = int64(vslices.Len())
    for i := 0; i < int(rows); i++ {
        if err = triggerRun("PostGet", vslices.Index(i), triggerArgs); err != nil {
            return
        }
    }
    return
}
func (this *dbMap   ) SelectAll(slices interface{}, query string, args ...interface{}) (int64, error) { return this      .selectAll(this, slices, query, args...) }
func (this *txMap   ) SelectAll(slices interface{}, query string, args ...interface{}) (int64, error) { return this.dbmap.selectAll(this, slices, query, args...) }
func (this *tableMap) SelectAll(slices interface{}, query string, args ...interface{}) (int64, error) { return this.dbmap.selectAll(this, slices, query, args...) }

func (this *dbMap) selectOne(exec SQLExecutor, holder interface{}, query string, args ...interface{}) (err error) {
    v := reflect.Indirect(reflect.ValueOf(holder))
    if v.Kind() != reflect.Struct {
        return this.selectVal(exec, holder, query, args...)
    }

    list, err := this.selectIntoOrNew(exec, holder, false, query, args...)
    if err != nil {
        return err
    }
    if list == nil || len(list) <= 0 {
        return sql.ErrNoRows
    }
    if len(list) > 1 {
        err = ErrSelectOneGetMore
    }
    w := reflect.Indirect(reflect.ValueOf(list[0]))
    v.Set(w)
    return
}
func (this *dbMap   ) SelectOne(holder interface{}, query string, args ...interface{}) (error) { return this      .selectOne(this, holder, query, args...) }
func (this *txMap   ) SelectOne(holder interface{}, query string, args ...interface{}) (error) { return this.dbmap.selectOne(this, holder, query, args...) }
func (this *tableMap) SelectOne(holder interface{}, query string, args ...interface{}) (error) { return this.dbmap.selectOne(this, holder, query, args...) }

//

var (
    reField = regexp.MustCompile("^\\s*(\\w+)(?:\\s+(\\w+)\\s+(.+)\\s*)?\\s*$")
)

func (this *tableMap) makeSelectSQL(fields, where, suffix string) (string) {
    sql := this.dbmap.dialect.SelectSQL(this.schemaName, this.tableName)

    fs := strings.TrimSpace(fields)
    /*
    fs := ""
    for _, field := range strings.Split(fields, ",") {
        if fs != "" {
            fs += ", "
        }
        subs := reField.FindStringSubmatch(field)
        if subs == nil {
            fs += field
        } else {
            fs += this.dbmap.dialect.QuoteField(subs[1])
            if subs[2] != "" {
                fs += fmt.Sprintf(" %s %s", strings.ToUpper(subs[2]), subs[3])
            }
        }
    }
    //*/
    if fs == "" {
        fs = "*"
    }

    if where == "" {
        where = "1"
    }
    return fmt.Sprintf(sql, "", fs, "", where, suffix)
}

func (this *tableMap) SelectOne2 (holder interface{},         where         string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(""    , where, ""    ), args...)
}
func (this *tableMap) SelectOne2x(holder interface{},         where, suffix string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(""    , where, suffix), args...)
}
func (this *tableMap) SelectOne3 (holder interface{}, fields, where         string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(fields, where, ""    ), args...)
}
func (this *tableMap) SelectOne3x(holder interface{}, fields, where, suffix string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(fields, where, suffix), args...)
}

func (this *tableMap) SelectAll2 (slices interface{},         where         string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(""    , where, ""    ), args...)
}
func (this *tableMap) SelectAll2x(slices interface{},         where, suffix string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(""    , where, suffix), args...)
}
func (this *tableMap) SelectAll3 (slices interface{}, fields, where         string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(fields, where, ""    ), args...)
}
func (this *tableMap) SelectAll3x(slices interface{}, fields, where, suffix string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(fields, where, suffix), args...)
}
<commit_msg>* sqlutil: fields or where can be "", "*", "all", "ALL"<commit_after>
package sqlutil

import (
    "fmt"
    "strings"
    "regexp"
    "errors"
    "reflect"
    "database/sql"
)

var (
    ErrSelectOneGetMore = errors.New("SelectOne: got multiple rows")
    errfSelectIntoNonStructType = errFormatFactory("SELECT into non-struct type: %v")
    errfSelectIntoPointerSlices = errFormatFactory("SELECT into non-pointer slices: %v")
    errfSelectIntoNonStructMoreCols = errFormatFactory("SELECT into non-struct, only 1 column requires: %d")
    errfTableMetaNoField = errFormatFactory("SELECT into struct, column %q not in meta of table %q")
)

func (this *dbMap) columnsToFieldIndexList(meta reflect.Type, cols []string) ([][]int, error) {
    fieldIndexList := make([][]int, len(cols))

    table, ok := this.getTableByMeta(meta)
    if !ok {
        table = this.getOrAddPseudoTable(meta)
    }
    for i, colName := range cols {
        if col, ok := table.colDict[colName]; ok {
            if f, ok := meta.FieldByName(col.fieldName); ok {
                fieldIndexList[i] = f.Index
            }
        }
        if fieldIndexList[i] == nil {
            return nil, errfTableMetaNoField(colName, table.tableName)
        }
    }
    return fieldIndexList, nil
}
func checkSlices(holder interface{}, appendToSlice bool) (reflect.Type, error) {
    t := reflect.TypeOf(holder)
    raw := t
    // if not append to holder slices, holder MUST be valid meta for new slices
    if !appendToSlice {
        for t.Kind() == reflect.Ptr {
            t = t.Elem()
        }
        if t.Kind() != reflect.Struct {
            return nil, errfSelectIntoNonStructType(raw)
        }
        return t, nil
    }
    // else; check holder as slices
    if true {
        if t.Kind() != reflect.Ptr {
            return nil, errfSelectIntoPointerSlices(raw)
        }
        if t = t.Elem(); t.Kind() != reflect.Slice {
            return nil, errfSelectIntoPointerSlices(raw)
        }
        return t.Elem(), nil
    }
    return nil, nil
}
func (this *dbMap) selectIntoOrNew(exec SQLExecutor, holder interface{}, appendToSlice bool, query string, args ...interface{}) (list []interface{}, err error) {
    var (
        meta reflect.Type
        elemIsPointer = true
        elemIsStruct = true
        rows    *sql.Rows
        cols    []string
        colN    int
        colToFieldIndex     [][]int
        holderSlice = reflect.Indirect(reflect.ValueOf(holder))
        newSlice []interface{}
    )
    if meta, err = checkSlices(holder, appendToSlice); err != nil {
        return
    }
    if appendToSlice {
        if elemIsPointer = meta.Kind() == reflect.Ptr; elemIsPointer {
            meta = meta.Elem()
        }
        elemIsStruct = meta.Kind() == reflect.Struct
    }

    if len(args) == 1 {
        query, args = this.maybeExpandNamedQuery(query, args)
    }

    if rows, err = exec.Query(query, args...); err != nil {
        return
    }
    defer rows.Close()

    if cols, err = rows.Columns(); err != nil {
        return
    }
    colN = len(cols)
    if !elemIsStruct && colN > 1 {
        return nil, errfSelectIntoNonStructMoreCols(colN)
    }
    if elemIsStruct {
        if colToFieldIndex, err = this.columnsToFieldIndexList(meta, cols); err != nil {
            return
        }
    }

    dest := make([]interface{}, colN)
    for {
        if !rows.Next() {
            if err = rows.Err(); err != nil {
                return
            }
            break
        }

        pvElem := reflect.New(meta)
        vElem := pvElem.Elem()
        for i := range cols {
            target := vElem
            if elemIsStruct {
                target = target.FieldByIndex(colToFieldIndex[i])
            }
            dest[i] = target.Addr().Interface()
        }

        if err = rows.Scan(dest...); err != nil {
            return
        }

        if appendToSlice {
            if elemIsPointer {
                vElem = pvElem
            }
            holderSlice.Set(reflect.Append(holderSlice, vElem))
        } else {
            newSlice = append(newSlice, pvElem.Interface())
        }
    }

    if appendToSlice {
        //
    } else {
        list = newSlice
    }
    return
}
func (this *dbMap) selectAll(exec SQLExecutor, slices interface{}, query string, args ...interface{}) (rows int64, err error) {
    if _, err = this.selectIntoOrNew(exec, slices, true, query, args...); err != nil {
        return
    }
    triggerArgs := triggerArg(exec)
    vslices := reflect.Indirect(reflect.ValueOf(slices))
    rows = int64(vslices.Len())
    for i := 0; i < int(rows); i++ {
        if err = triggerRun("PostGet", vslices.Index(i), triggerArgs); err != nil {
            return
        }
    }
    return
}
func (this *dbMap   ) SelectAll(slices interface{}, query string, args ...interface{}) (int64, error) { return this      .selectAll(this, slices, query, args...) }
func (this *txMap   ) SelectAll(slices interface{}, query string, args ...interface{}) (int64, error) { return this.dbmap.selectAll(this, slices, query, args...) }
func (this *tableMap) SelectAll(slices interface{}, query string, args ...interface{}) (int64, error) { return this.dbmap.selectAll(this, slices, query, args...) }

func (this *dbMap) selectOne(exec SQLExecutor, holder interface{}, query string, args ...interface{}) (err error) {
    v := reflect.Indirect(reflect.ValueOf(holder))
    if v.Kind() != reflect.Struct {
        return this.selectVal(exec, holder, query, args...)
    }

    list, err := this.selectIntoOrNew(exec, holder, false, query, args...)
    if err != nil {
        return err
    }
    if list == nil || len(list) <= 0 {
        return sql.ErrNoRows
    }
    if len(list) > 1 {
        err = ErrSelectOneGetMore
    }
    w := reflect.Indirect(reflect.ValueOf(list[0]))
    v.Set(w)
    return
}
func (this *dbMap   ) SelectOne(holder interface{}, query string, args ...interface{}) (error) { return this      .selectOne(this, holder, query, args...) }
func (this *txMap   ) SelectOne(holder interface{}, query string, args ...interface{}) (error) { return this.dbmap.selectOne(this, holder, query, args...) }
func (this *tableMap) SelectOne(holder interface{}, query string, args ...interface{}) (error) { return this.dbmap.selectOne(this, holder, query, args...) }

//

var (
    reField = regexp.MustCompile("^\\s*(\\w+)(?:\\s+(\\w+)\\s+(.+)\\s*)?\\s*$")
)

func (this *tableMap) makeSelectSQL(fields, where, suffix string) (string) {
    sql := this.dbmap.dialect.SelectSQL(this.schemaName, this.tableName)

    fs := strings.TrimSpace(fields)
    /*
    fs := ""
    for _, field := range strings.Split(fields, ",") {
        if fs != "" {
            fs += ", "
        }
        subs := reField.FindStringSubmatch(field)
        if subs == nil {
            fs += field
        } else {
            fs += this.dbmap.dialect.QuoteField(subs[1])
            if subs[2] != "" {
                fs += fmt.Sprintf(" %s %s", strings.ToUpper(subs[2]), subs[3])
            }
        }
    }
    //*/
    if fs = strings.TrimSpace(fs); isAll(fs) {
        fs = "*"
    }

    if where = strings.TrimSpace(where); isAll(where) {
        where = "1"
    }
    return fmt.Sprintf(sql, "", fs, "", where, suffix)
}

func (this *tableMap) SelectOne2 (holder interface{},         where         string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(""    , where, ""    ), args...)
}
func (this *tableMap) SelectOne2x(holder interface{},         where, suffix string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(""    , where, suffix), args...)
}
func (this *tableMap) SelectOne3 (holder interface{}, fields, where         string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(fields, where, ""    ), args...)
}
func (this *tableMap) SelectOne3x(holder interface{}, fields, where, suffix string, args ...interface{}) (error) {
    return this.SelectOne(holder, this.makeSelectSQL(fields, where, suffix), args...)
}

func (this *tableMap) SelectAll2 (slices interface{},         where         string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(""    , where, ""    ), args...)
}
func (this *tableMap) SelectAll2x(slices interface{},         where, suffix string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(""    , where, suffix), args...)
}
func (this *tableMap) SelectAll3 (slices interface{}, fields, where         string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(fields, where, ""    ), args...)
}
func (this *tableMap) SelectAll3x(slices interface{}, fields, where, suffix string, args ...interface{}) (int64, error) {
    return this.SelectAll(slices, this.makeSelectSQL(fields, where, suffix), args...)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
)

func main() {
	teams := []string{"Dev", "QA", "Ops"}
	manager := "Keerthi"

	team := struct {
		teams   []string
		manager string
	}{
		teams,
		manager,
	}
	fmt.Printf("%+v", team)
}
<commit_msg>Minor modifications on struct examples<commit_after>package main

import (
	"fmt"
)

func main() {

	team := struct {
		teams   []string
		manager string
	}{
		[]string{"Dev", "QA", "Ops"},
		"Keerthi",
	}
	fmt.Printf("%+v\n", team)

}
<|endoftext|>


<commit_before>package Common

// 每日滚动的LOG实现

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"sync"
	"time"
)

var (
	logDir  = os.TempDir()
	logDay  = 0
	logLock = sync.Mutex{}
	logFile *os.File
)

// parse env ENABLE_DEBUG_LOG and DISABLE_INFO_LOG
func init() {
	if proc, err := filepath.Abs(os.Args[0]); err == nil {
		SetLogDir(filepath.Dir(proc))
	}
}

func SetLogDir(dir string) {
	logDir = dir
}

func check() {
	logLock.Lock()
	defer logLock.Unlock()

	if logDay == time.Now().Day() {
		return
	}

	logDay = time.Now().Day()
	logFile.Sync()
	logFile.Close()
	logProc := filepath.Base(os.Args[0])
	filename := filepath.Join(logDir,
		fmt.Sprintf("%s.%s.log", logProc, time.Now().Format("2006-01-02")))
	var err error
	logFile, err = os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		logFile = os.Stderr
		fmt.Fprintln(os.Stderr, "check log file", err, "use STDOUT")
	}
}

func DropLog(v ...interface{}) {}

func DebugLog(v ...interface{}) {
	check()
	logLock.Lock()
	defer logLock.Unlock()
	_, file, line, _ := runtime.Caller(2)
	fmt.Fprintln(logFile, NumberNow(), file, line, "debug", v)
}

func InfoLog(v ...interface{}) {
	check()
	logLock.Lock()
	defer logLock.Unlock()
	_, file, line, _ := runtime.Caller(2)
	fmt.Fprintln(logFile, NumberNow(), file, line, "info", v)
}

func ErrorLog(v ...interface{}) {
	check()
	logLock.Lock()
	defer logLock.Unlock()
	_, file, line, _ := runtime.Caller(2)
	fmt.Fprintln(logFile, NumberNow(), file, line, "error", v)
}
<commit_msg>log use short file name<commit_after>package Common

// 每日滚动的LOG实现

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"sync"
	"time"
)

var (
	logDir  = os.TempDir()
	logDay  = 0
	logLock = sync.Mutex{}
	logFile *os.File
)

// parse env ENABLE_DEBUG_LOG and DISABLE_INFO_LOG
func init() {
	if proc, err := filepath.Abs(os.Args[0]); err == nil {
		SetLogDir(filepath.Dir(proc))
	}
}

func SetLogDir(dir string) {
	logDir = dir
}

func check() {
	logLock.Lock()
	defer logLock.Unlock()

	if logDay == time.Now().Day() {
		return
	}

	logDay = time.Now().Day()
	logFile.Sync()
	logFile.Close()
	logProc := filepath.Base(os.Args[0])
	filename := filepath.Join(logDir,
		fmt.Sprintf("%s.%s.log", logProc, time.Now().Format("2006-01-02")))
	var err error
	logFile, err = os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		logFile = os.Stderr
		fmt.Fprintln(os.Stderr, NumberNow(), "check log file", err, "use STDOUT")
	}
}

func DropLog(v ...interface{}) {}

func DebugLog(v ...interface{}) {
	check()
	logLock.Lock()
	defer logLock.Unlock()
	_, file, line, _ := runtime.Caller(1)
	fmt.Fprintln(logFile, NumberNow(), filepath.Base(file), line, "debug", v)
}

func InfoLog(v ...interface{}) {
	check()
	logLock.Lock()
	defer logLock.Unlock()
	_, file, line, _ := runtime.Caller(1)
	fmt.Fprintln(logFile, NumberNow(), filepath.Base(file), line, "info", v)
}

func ErrorLog(v ...interface{}) {
	check()
	logLock.Lock()
	defer logLock.Unlock()
	_, file, line, _ := runtime.Caller(1)
	fmt.Fprintln(logFile, NumberNow(), filepath.Base(file), line, "error", v)
}
<|endoftext|>


<commit_before>package hamming

const testVersion = 5

func Distance(a, b string) (int, error) {
	// your code here!
}
<commit_msg>hamming: remove unnecessary stub comment<commit_after>package hamming

const testVersion = 5

func Distance(a, b string) (int, error) {
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"net"
	"time"
	"flag"
	"strings"
	"os"
	"os/signal"
	"syscall"

	"github.com/miekg/dns"
)

var nameservers []string
var verbose *bool
var gateway *string

func getErrMsg(w dns.ResponseWriter, req *dns.Msg, err int) *dns.Msg {
	m := new(dns.Msg)
	m.SetReply(req)
	m.SetRcode(req, err)
	m.Authoritative = false
	m.RecursionAvailable = true
	return m
}

func getNsReply(w dns.ResponseWriter, req *dns.Msg) *dns.Msg {
	if *verbose {
		log.Print("Forwarding ", req.Question[0].Name, "/", dns.Type(req.Question[0].Qtype).String())
	}

	client := &dns.Client{Net: "udp", ReadTimeout: 4 * time.Second, WriteTimeout: 4 * time.Second, SingleInflight: true}

	if _, tcp := w.RemoteAddr().(*net.TCPAddr); tcp {
		client.Net = "tcp"
	}

	var r *dns.Msg
	var err error

	for i := 0; i < len(nameservers); i++ {
		r, _, err = client.Exchange(req, nameservers[(int(req.Id) + i) % len(nameservers)])
		if err == nil {
			r.Compress = true
			return r
		}
	}

	log.Print("Failed to forward request.", err)
	return getErrMsg(w, req, dns.RcodeServerFailure)
}

func handleRequest(w dns.ResponseWriter, req *dns.Msg) {
	var m *dns.Msg

	if len(req.Question) > 0 && strings.HasSuffix(req.Question[0].Name, ".netflix.com.") {
		if req.Question[0].Qtype == dns.TypeA {
			m = getNsReply(w, req)
			for _, ans := range m.Answer {
				if ans.Header().Rrtype == dns.TypeA {
					ip := ans.(*dns.A).A.String()
					log.Print("Re-routing ", ip, " for ", ans.Header().Name, "/", dns.Type(ans.Header().Rrtype).String())
					// TODO reroute
					//"route add " + ip + "/32 " + *gateway
				} else if ans.Header().Rrtype == dns.TypeAAAA {
					// sanity check for now, shouldn't happen afaik
					log.Print("WARNING: AAAA response in ", ans.Header().Name, "/A")
				}
			}
		} else if req.Question[0].Qtype == dns.TypeAAAA {
			if *verbose {
				log.Print("Hijacking ", req.Question[0].Name, "/", dns.Type(req.Question[0].Qtype).String())
			}
			m = getErrMsg(w, req, dns.RcodeNameError)
		} else {
			m = getNsReply(w, req)
		}
	} else {
		m = getNsReply(w, req)
	}

	w.WriteMsg(m)
}

func main() {
	gateway = flag.String("gw", "192.168.1.1", "gateway IP to re-route to")
	verbose = flag.Bool("v", false, "verbose logging")

	flag.Usage = func() {
		flag.PrintDefaults()
	}
	flag.Parse()

	log.Print("Starting DNS resolver...")

	nameservers = []string{"8.8.8.8:53", "8.8.4.4:53"}

	log.Print("Forwarding to ", nameservers)

	dns.HandleFunc(".", handleRequest)

	go func() {
		srv := &dns.Server{Addr: ":53", Net: "udp"}
		err := srv.ListenAndServe()
		if err != nil {
			log.Fatal("Failed to start UDP server.", err.Error())
		}
	}()

	go func() {
		srv := &dns.Server{Addr: ":53", Net: "tcp"}
		err := srv.ListenAndServe()
		if err != nil {
			log.Fatal("Failed to start TCP server.", err.Error())
		}
	}()

	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	for {
		select {
		case s := <-sig:
			log.Fatalf("Received signal %d, exiting...", s)
		}
	}
}<commit_msg>Implemented routing.<commit_after>package main

import (
	"log"
	"net"
	"time"
	"flag"
	"strings"
	"os"
	"os/exec"
	"os/signal"
	"syscall"

	"github.com/miekg/dns"
)

var nameservers []string
var verbose *bool
var gateway *string
var router string
var routed []string

func getErrMsg(w dns.ResponseWriter, req *dns.Msg, err int) *dns.Msg {
	m := new(dns.Msg)
	m.SetReply(req)
	m.SetRcode(req, err)
	m.Authoritative = false
	m.RecursionAvailable = true
	return m
}

func getNsReply(w dns.ResponseWriter, req *dns.Msg) *dns.Msg {
	if *verbose {
		log.Print("Forwarding ", req.Question[0].Name, "/", dns.Type(req.Question[0].Qtype).String())
	}

	client := &dns.Client{Net: "udp", ReadTimeout: 4 * time.Second, WriteTimeout: 4 * time.Second, SingleInflight: true}

	if _, tcp := w.RemoteAddr().(*net.TCPAddr); tcp {
		client.Net = "tcp"
	}

	var r *dns.Msg
	var err error

	for i := 0; i < len(nameservers); i++ {
		r, _, err = client.Exchange(req, nameservers[(int(req.Id) + i) % len(nameservers)])
		if err == nil {
			r.Compress = true
			return r
		}
	}

	log.Print("Failed to forward request.", err)
	return getErrMsg(w, req, dns.RcodeServerFailure)
}

func handleRequest(w dns.ResponseWriter, req *dns.Msg) {
	var m *dns.Msg

	if len(req.Question) > 0 && (req.Question[0].Name == "netflix.com." || strings.HasSuffix(req.Question[0].Name, ".netflix.com.")) {
		if req.Question[0].Qtype == dns.TypeA {
			m = getNsReply(w, req)
			for _, ans := range m.Answer {
				if ans.Header().Rrtype == dns.TypeA {
					ip := ans.(*dns.A).A.String()
					routed = append(routed, ip)

					log.Print("Re-routing ", ip, " for ", ans.Header().Name, "/", dns.Type(ans.Header().Rrtype).String())

					out, err := exec.Command(router, "add", ip + "/32", *gateway).CombinedOutput()
					if err != nil {
						log.Print(err)
					} else if *verbose {
						log.Printf("route: %s", out)
					}
				} else if ans.Header().Rrtype == dns.TypeAAAA {
					// sanity check for now, shouldn't happen afaik
					log.Print("WARNING: AAAA response in ", ans.Header().Name, "/A")
				}
			}
		} else if req.Question[0].Qtype == dns.TypeAAAA {
			if *verbose {
				log.Print("Hijacking ", req.Question[0].Name, "/", dns.Type(req.Question[0].Qtype).String())
			}
			m = getErrMsg(w, req, dns.RcodeNameError)
		} else {
			m = getNsReply(w, req)
		}
	} else {
		m = getNsReply(w, req)
	}

	w.WriteMsg(m)
}

func main() {
	gateway = flag.String("r", "", "gateway IP for routing destination")
	verbose = flag.Bool("v", false, "verbose logging")

	flag.Usage = func() {
		flag.PrintDefaults()
	}
	flag.Parse()

	router, _ = exec.LookPath("route")
	if len(router) < 1 {
		log.Fatal("Unable to find the `route` command in your %PATH%.")
	}

	if len(*gateway) < 7 {
		log.Fatal("Gateway IP must be specified via argument `r`.")
	}

	log.Print("Starting DNS resolver...")

	nameservers = []string{"8.8.8.8:53", "8.8.4.4:53"}

	log.Print("Forwarding to ", nameservers)

	dns.HandleFunc(".", handleRequest)

	go func() {
		srv := &dns.Server{Addr: ":53", Net: "udp"}
		err := srv.ListenAndServe()
		if err != nil {
			log.Fatal("Failed to start UDP server.", err.Error())
		}
	}()

	go func() {
		srv := &dns.Server{Addr: ":53", Net: "tcp"}
		err := srv.ListenAndServe()
		if err != nil {
			log.Fatal("Failed to start TCP server.", err.Error())
		}
	}()

	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	for {
		select {
		case s := <-sig:
			if len(routed) > 0 {
				log.Print("Removing routes...")

				for _, ip := range routed {
					out, err := exec.Command(router, "delete", ip + "/32").CombinedOutput()
					if err != nil {
						log.Print(err)
					} else if *verbose {
						log.Printf("route: %s", out)
					}
				}
			}

			log.Fatalf("Received signal %d, exiting...", s)
		}
	}
}<|endoftext|>


<commit_before>package herd

import (
	"fmt"
	"github.com/Symantec/Dominator/lib/filesystem"
	"github.com/Symantec/Dominator/lib/filter"
	subproto "github.com/Symantec/Dominator/proto/sub"
	"os"
	"path"
)

type state struct {
	subInodeToRequiredInode map[uint64]uint64
}

func (sub *Sub) buildUpdateRequest(request *subproto.UpdateRequest) {
	fmt.Println("buildUpdateRequest()") // TODO(rgooch): Delete debugging.
	subFS := sub.fileSystem
	requiredImage := sub.herd.getImage(sub.requiredImage)
	requiredFS := requiredImage.FileSystem
	filter := requiredImage.Filter
	request.Triggers = requiredImage.Triggers
	var state state
	state.subInodeToRequiredInode = make(map[uint64]uint64)
	compareDirectories(request, &state,
		&subFS.DirectoryInode, &requiredFS.DirectoryInode,
		"/", filter)
	// TODO(rgooch): Implement this.
}

func compareDirectories(request *subproto.UpdateRequest, state *state,
	subDirectory, requiredDirectory *filesystem.DirectoryInode,
	myPathName string, filter *filter.Filter) {
	// First look for entries that should be deleted.
	if subDirectory != nil {
		for name := range subDirectory.EntriesByName {
			pathname := path.Join(myPathName, name)
			if filter.Match(pathname) {
				continue
			}
			if _, ok := requiredDirectory.EntriesByName[name]; !ok {
				request.PathsToDelete = append(request.PathsToDelete, pathname)
				fmt.Printf("Delete: %s\n", pathname) // HACK
			}
		}
	}
	for name, requiredEntry := range requiredDirectory.EntriesByName {
		pathname := path.Join(myPathName, name)
		if filter.Match(pathname) {
			continue
		}
		var subEntry *filesystem.DirectoryEntry
		if subDirectory != nil {
			if se, ok := subDirectory.EntriesByName[name]; ok {
				subEntry = se
			}
		}
		if subEntry == nil {
			addEntry(request, state, requiredEntry, pathname)
		} else {
			compareEntries(request, state, subEntry, requiredEntry, pathname,
				filter)
		}
		// If a directory: descend (possibly with the directory for the sub).
		requiredInode := requiredEntry.Inode()
		if requiredInode, ok := requiredInode.(*filesystem.DirectoryInode); ok {
			var subInode *filesystem.DirectoryInode
			if si, ok := subEntry.Inode().(*filesystem.DirectoryInode); ok {
				subInode = si
			}
			compareDirectories(request, state, requiredInode, subInode,
				pathname, filter)
		}
	}
}

func addEntry(request *subproto.UpdateRequest, state *state,
	requiredEntry *filesystem.DirectoryEntry, myPathName string) {
	requiredInode := requiredEntry.Inode()
	if requiredInode, ok := requiredInode.(*filesystem.DirectoryInode); ok {
		makeDirectory(request, requiredInode, myPathName, true)
		fmt.Printf("Add directory: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Add entry: %s...\n", myPathName) // HACK
		// TODO(rgooch): Add entry.
	}
}

func makeDirectory(request *subproto.UpdateRequest,
	requiredInode *filesystem.DirectoryInode, pathName string, create bool) {
	var newdir subproto.Directory
	newdir.Name = pathName
	newdir.Mode = requiredInode.Mode
	newdir.Uid = requiredInode.Uid
	newdir.Gid = requiredInode.Gid
	if create {
		request.DirectoriesToMake = append(request.DirectoriesToMake, newdir)
	} else {
		request.DirectoriesToChange = append(request.DirectoriesToMake, newdir)
	}
}

func compareEntries(request *subproto.UpdateRequest, state *state,
	subEntry, requiredEntry *filesystem.DirectoryEntry,
	myPathName string, filter *filter.Filter) {
	switch requiredInode := requiredEntry.Inode().(type) {
	case *filesystem.RegularInode:
		compareRegularFile(request, state, subEntry,
			requiredInode, requiredEntry.InodeNumber, myPathName)
		return
	case *filesystem.SymlinkInode:
		compareSymlink(request, state, subEntry,
			requiredInode, requiredEntry.InodeNumber, myPathName)
		return
	case *filesystem.Inode:
		compareFile(request, state, subEntry,
			requiredInode, requiredEntry.InodeNumber, myPathName)
		return
	case *filesystem.DirectoryInode:
		compareDirectory(request, state, subEntry, requiredInode, myPathName,
			filter)
		return
	}
	panic("Unsupported entry type")
}

func compareRegularFile(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.RegularInode, requiredInodeNumber uint64,
	myPathName string) {
	if subInode, ok := subEntry.Inode().(*filesystem.RegularInode); ok {
		if requiredInum, ok :=
			state.subInodeToRequiredInode[subEntry.InodeNumber]; ok {
			if requiredInum != requiredInodeNumber {
				//
				fmt.Printf("Different links: %s...\n", myPathName) // HACK
			}
		} else {
			state.subInodeToRequiredInode[subEntry.InodeNumber] =
				requiredInodeNumber
		}
		sameMetadata := filesystem.CompareRegularInodesMetadata(
			subInode, requiredInode, os.Stdout)
		sameData := filesystem.CompareRegularInodesData(subInode,
			requiredInode, os.Stdout)
		if sameMetadata && sameData {
			return
		}
		fmt.Printf("Different rfile: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Delete+add rfile: %s...\n", myPathName) // HACK
	}
	// TODO(rgooch): Delete entry and replace.
}

func compareSymlink(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.SymlinkInode, requiredInodeNumber uint64,
	myPathName string) {
	if subInode, ok := subEntry.Inode().(*filesystem.SymlinkInode); ok {
		if requiredInum, ok :=
			state.subInodeToRequiredInode[subEntry.InodeNumber]; ok {
			if requiredInum != requiredInodeNumber {
				fmt.Printf("Different links: %s...\n", myPathName) // HACK
			}
		} else {
			state.subInodeToRequiredInode[subEntry.InodeNumber] =
				requiredInodeNumber
		}
		if filesystem.CompareSymlinkInodes(subInode, requiredInode, os.Stdout) {
			return
		}
		fmt.Printf("Different symlink: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Add symlink: %s...\n", myPathName) // HACK
	}
	// TODO(rgooch): Delete entry and replace.
}

func compareFile(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.Inode, requiredInodeNumber uint64,
	myPathName string) {
	if subInode, ok := subEntry.Inode().(*filesystem.Inode); ok {
		if requiredInum, ok :=
			state.subInodeToRequiredInode[subEntry.InodeNumber]; ok {
			if requiredInum != requiredInodeNumber {
				fmt.Printf("Different links: %s...\n", myPathName) // HACK
			}
		} else {
			state.subInodeToRequiredInode[subEntry.InodeNumber] =
				requiredInodeNumber
		}
		if filesystem.CompareInodes(subInode, requiredInode, os.Stdout) {
			return
		}
		fmt.Printf("Different file: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Add file: %s...\n", myPathName) // HACK
	}
	// TODO(rgooch): Delete entry and replace.
}

func compareDirectory(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.DirectoryInode,
	myPathName string, filter *filter.Filter) {
	if subInode, ok := subEntry.Inode().(*filesystem.DirectoryInode); ok {
		if filesystem.CompareDirectoriesMetadata(subInode, requiredInode,
			os.Stdout) {
			return
		}
		makeDirectory(request, requiredInode, myPathName, false)
		fmt.Printf("Different directory: %s...\n", myPathName) // HACK
	} else {
		request.PathsToDelete = append(request.PathsToDelete, myPathName)
		makeDirectory(request, requiredInode, myPathName, true)
		fmt.Printf("Replace non-directory: %s...\n", myPathName) // HACK
	}
}
<commit_msg>Move panic() in compareEntries() into default case.<commit_after>package herd

import (
	"fmt"
	"github.com/Symantec/Dominator/lib/filesystem"
	"github.com/Symantec/Dominator/lib/filter"
	subproto "github.com/Symantec/Dominator/proto/sub"
	"os"
	"path"
)

type state struct {
	subInodeToRequiredInode map[uint64]uint64
}

func (sub *Sub) buildUpdateRequest(request *subproto.UpdateRequest) {
	fmt.Println("buildUpdateRequest()") // TODO(rgooch): Delete debugging.
	subFS := sub.fileSystem
	requiredImage := sub.herd.getImage(sub.requiredImage)
	requiredFS := requiredImage.FileSystem
	filter := requiredImage.Filter
	request.Triggers = requiredImage.Triggers
	var state state
	state.subInodeToRequiredInode = make(map[uint64]uint64)
	compareDirectories(request, &state,
		&subFS.DirectoryInode, &requiredFS.DirectoryInode,
		"/", filter)
	// TODO(rgooch): Implement this.
}

func compareDirectories(request *subproto.UpdateRequest, state *state,
	subDirectory, requiredDirectory *filesystem.DirectoryInode,
	myPathName string, filter *filter.Filter) {
	// First look for entries that should be deleted.
	if subDirectory != nil {
		for name := range subDirectory.EntriesByName {
			pathname := path.Join(myPathName, name)
			if filter.Match(pathname) {
				continue
			}
			if _, ok := requiredDirectory.EntriesByName[name]; !ok {
				request.PathsToDelete = append(request.PathsToDelete, pathname)
				fmt.Printf("Delete: %s\n", pathname) // HACK
			}
		}
	}
	for name, requiredEntry := range requiredDirectory.EntriesByName {
		pathname := path.Join(myPathName, name)
		if filter.Match(pathname) {
			continue
		}
		var subEntry *filesystem.DirectoryEntry
		if subDirectory != nil {
			if se, ok := subDirectory.EntriesByName[name]; ok {
				subEntry = se
			}
		}
		if subEntry == nil {
			addEntry(request, state, requiredEntry, pathname)
		} else {
			compareEntries(request, state, subEntry, requiredEntry, pathname,
				filter)
		}
		// If a directory: descend (possibly with the directory for the sub).
		requiredInode := requiredEntry.Inode()
		if requiredInode, ok := requiredInode.(*filesystem.DirectoryInode); ok {
			var subInode *filesystem.DirectoryInode
			if si, ok := subEntry.Inode().(*filesystem.DirectoryInode); ok {
				subInode = si
			}
			compareDirectories(request, state, requiredInode, subInode,
				pathname, filter)
		}
	}
}

func addEntry(request *subproto.UpdateRequest, state *state,
	requiredEntry *filesystem.DirectoryEntry, myPathName string) {
	requiredInode := requiredEntry.Inode()
	if requiredInode, ok := requiredInode.(*filesystem.DirectoryInode); ok {
		makeDirectory(request, requiredInode, myPathName, true)
		fmt.Printf("Add directory: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Add entry: %s...\n", myPathName) // HACK
		// TODO(rgooch): Add entry.
	}
}

func makeDirectory(request *subproto.UpdateRequest,
	requiredInode *filesystem.DirectoryInode, pathName string, create bool) {
	var newdir subproto.Directory
	newdir.Name = pathName
	newdir.Mode = requiredInode.Mode
	newdir.Uid = requiredInode.Uid
	newdir.Gid = requiredInode.Gid
	if create {
		request.DirectoriesToMake = append(request.DirectoriesToMake, newdir)
	} else {
		request.DirectoriesToChange = append(request.DirectoriesToMake, newdir)
	}
}

func compareEntries(request *subproto.UpdateRequest, state *state,
	subEntry, requiredEntry *filesystem.DirectoryEntry,
	myPathName string, filter *filter.Filter) {
	switch requiredInode := requiredEntry.Inode().(type) {
	case *filesystem.RegularInode:
		compareRegularFile(request, state, subEntry,
			requiredInode, requiredEntry.InodeNumber, myPathName)
		return
	case *filesystem.SymlinkInode:
		compareSymlink(request, state, subEntry,
			requiredInode, requiredEntry.InodeNumber, myPathName)
		return
	case *filesystem.Inode:
		compareFile(request, state, subEntry,
			requiredInode, requiredEntry.InodeNumber, myPathName)
		return
	case *filesystem.DirectoryInode:
		compareDirectory(request, state, subEntry, requiredInode, myPathName,
			filter)
		return
	default:
		panic("Unsupported entry type")
	}
}

func compareRegularFile(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.RegularInode, requiredInodeNumber uint64,
	myPathName string) {
	if subInode, ok := subEntry.Inode().(*filesystem.RegularInode); ok {
		if requiredInum, ok :=
			state.subInodeToRequiredInode[subEntry.InodeNumber]; ok {
			if requiredInum != requiredInodeNumber {
				//
				fmt.Printf("Different links: %s...\n", myPathName) // HACK
			}
		} else {
			state.subInodeToRequiredInode[subEntry.InodeNumber] =
				requiredInodeNumber
		}
		sameMetadata := filesystem.CompareRegularInodesMetadata(
			subInode, requiredInode, os.Stdout)
		sameData := filesystem.CompareRegularInodesData(subInode,
			requiredInode, os.Stdout)
		if sameMetadata && sameData {
			return
		}
		fmt.Printf("Different rfile: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Delete+add rfile: %s...\n", myPathName) // HACK
	}
	// TODO(rgooch): Delete entry and replace.
}

func compareSymlink(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.SymlinkInode, requiredInodeNumber uint64,
	myPathName string) {
	if subInode, ok := subEntry.Inode().(*filesystem.SymlinkInode); ok {
		if requiredInum, ok :=
			state.subInodeToRequiredInode[subEntry.InodeNumber]; ok {
			if requiredInum != requiredInodeNumber {
				fmt.Printf("Different links: %s...\n", myPathName) // HACK
			}
		} else {
			state.subInodeToRequiredInode[subEntry.InodeNumber] =
				requiredInodeNumber
		}
		if filesystem.CompareSymlinkInodes(subInode, requiredInode, os.Stdout) {
			return
		}
		fmt.Printf("Different symlink: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Add symlink: %s...\n", myPathName) // HACK
	}
	// TODO(rgooch): Delete entry and replace.
}

func compareFile(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.Inode, requiredInodeNumber uint64,
	myPathName string) {
	if subInode, ok := subEntry.Inode().(*filesystem.Inode); ok {
		if requiredInum, ok :=
			state.subInodeToRequiredInode[subEntry.InodeNumber]; ok {
			if requiredInum != requiredInodeNumber {
				fmt.Printf("Different links: %s...\n", myPathName) // HACK
			}
		} else {
			state.subInodeToRequiredInode[subEntry.InodeNumber] =
				requiredInodeNumber
		}
		if filesystem.CompareInodes(subInode, requiredInode, os.Stdout) {
			return
		}
		fmt.Printf("Different file: %s...\n", myPathName) // HACK
	} else {
		fmt.Printf("Add file: %s...\n", myPathName) // HACK
	}
	// TODO(rgooch): Delete entry and replace.
}

func compareDirectory(request *subproto.UpdateRequest, state *state,
	subEntry *filesystem.DirectoryEntry,
	requiredInode *filesystem.DirectoryInode,
	myPathName string, filter *filter.Filter) {
	if subInode, ok := subEntry.Inode().(*filesystem.DirectoryInode); ok {
		if filesystem.CompareDirectoriesMetadata(subInode, requiredInode,
			os.Stdout) {
			return
		}
		makeDirectory(request, requiredInode, myPathName, false)
		fmt.Printf("Different directory: %s...\n", myPathName) // HACK
	} else {
		request.PathsToDelete = append(request.PathsToDelete, myPathName)
		makeDirectory(request, requiredInode, myPathName, true)
		fmt.Printf("Replace non-directory: %s...\n", myPathName) // HACK
	}
}
<|endoftext|>


<commit_before>// Copyright 2022 The Ebitengine Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build microsoftgdk
// +build microsoftgdk

package microsoftgdk

// Unfortunately, some functions like XSystemGetDeviceType is not implemented in a DLL,
// so LoadLibrary is not available.

// #include <stdint.h>
//
// uint32_t XSystemGetDeviceType(void);
import "C"

const (
	_XSystemDeviceType_Unknown              = 0x00
	_XSystemDeviceType_Pc                   = 0x01
	_XSystemDeviceType_XboxOne              = 0x02
	_XSystemDeviceType_XboxOneS             = 0x03
	_XSystemDeviceType_XboxOneX             = 0x04
	_XSystemDeviceType_XboxOneXDevkit       = 0x05
	_XSystemDeviceType_XboxScarlettLockhart = 0x06
	_XSystemDeviceType_XboxScarlettAnaconda = 0x07
	_XSystemDeviceType_XboxScarlettDevkit   = 0x08
)

func IsXbox() bool {
	t := C.XSystemGetDeviceType()
	return t != _XSystemDeviceType_Unknown && t != _XSystemDeviceType_Pc
}

func MonitorResolution() (int, int) {
	switch C.XSystemGetDeviceType() {
	case _XSystemDeviceType_XboxOne, _XSystemDeviceType_XboxOneS:
		return 1920, 1080
	case _XSystemDeviceType_XboxScarlettLockhart:
		// Series S
		return 2560, 1440
	case _XSystemDeviceType_XboxOneX, _XSystemDeviceType_XboxOneXDevkit, _XSystemDeviceType_XboxScarlettAnaconda, _XSystemDeviceType_XboxScarlettDevkit:
		// Series X
		return 3840, 2160
	default:
		return 1920, 1080
	}
}

func D3D12DLLName() string {
	switch C.XSystemGetDeviceType() {
	case _XSystemDeviceType_XboxOne, _XSystemDeviceType_XboxOneS, _XSystemDeviceType_XboxOneX, _XSystemDeviceType_XboxOneXDevkit:
		return "d3d12_x.dll"
	case _XSystemDeviceType_XboxScarlettLockhart, _XSystemDeviceType_XboxScarlettAnaconda, _XSystemDeviceType_XboxScarlettDevkit:
		return "d3d12_xs.dll"
	default:
		return ""
	}
}
<commit_msg>internal/microsoftgdk: initialize GDK on the Ebitengine side<commit_after>// Copyright 2022 The Ebitengine Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build microsoftgdk
// +build microsoftgdk

package microsoftgdk

// Unfortunately, some functions like XSystemGetDeviceType is not implemented in a DLL,
// so LoadLibrary is not available.

// #include <stdint.h>
//
// uint32_t XGameRuntimeInitialize(void);
// uint32_t XSystemGetDeviceType(void);
import "C"

import (
	"fmt"

	"golang.org/x/sys/windows"
)

var (
	kernel32 = windows.NewLazyDLL("kernel32")

	procGetACP = kernel32.NewProc("GetACP")
)

const (
	_CP_UTF8 = 65001

	_XSystemDeviceType_Unknown              = 0x00
	_XSystemDeviceType_Pc                   = 0x01
	_XSystemDeviceType_XboxOne              = 0x02
	_XSystemDeviceType_XboxOneS             = 0x03
	_XSystemDeviceType_XboxOneX             = 0x04
	_XSystemDeviceType_XboxOneXDevkit       = 0x05
	_XSystemDeviceType_XboxScarlettLockhart = 0x06
	_XSystemDeviceType_XboxScarlettAnaconda = 0x07
	_XSystemDeviceType_XboxScarlettDevkit   = 0x08
)

func _GetACP() uint32 {
	r, _, _ := procGetACP.Call()
	return uint32(r)
}

func IsXbox() bool {
	t := C.XSystemGetDeviceType()
	return t != _XSystemDeviceType_Unknown && t != _XSystemDeviceType_Pc
}

func MonitorResolution() (int, int) {
	switch C.XSystemGetDeviceType() {
	case _XSystemDeviceType_XboxOne, _XSystemDeviceType_XboxOneS:
		return 1920, 1080
	case _XSystemDeviceType_XboxScarlettLockhart:
		// Series S
		return 2560, 1440
	case _XSystemDeviceType_XboxOneX, _XSystemDeviceType_XboxOneXDevkit, _XSystemDeviceType_XboxScarlettAnaconda, _XSystemDeviceType_XboxScarlettDevkit:
		// Series X
		return 3840, 2160
	default:
		return 1920, 1080
	}
}

func D3D12DLLName() string {
	switch C.XSystemGetDeviceType() {
	case _XSystemDeviceType_XboxOne, _XSystemDeviceType_XboxOneS, _XSystemDeviceType_XboxOneX, _XSystemDeviceType_XboxOneXDevkit:
		return "d3d12_x.dll"
	case _XSystemDeviceType_XboxScarlettLockhart, _XSystemDeviceType_XboxScarlettAnaconda, _XSystemDeviceType_XboxScarlettDevkit:
		return "d3d12_xs.dll"
	default:
		return ""
	}
}

func init() {
	if r := C.XGameRuntimeInitialize(); uint32(r) != uint32(windows.S_OK) {
		panic(fmt.Sprintf("microsoftgdk: XSystemGetDeviceType failed: HRESULT(%d)", r))
	}
	if got, want := _GetACP(), uint32(_CP_UTF8); got != want {
		panic(fmt.Sprintf("microsoftgdk: GetACP(): got %d, want %d", got, want))
	}
}
<|endoftext|>


<commit_before>package middleware

import (
	"log"
	"net/http"
	"net/url"
	"strings"

	"github.com/intervention-engine/fhir/server"
	"github.com/intervention-engine/ie/notifications"
	"github.com/labstack/echo"
)

type NotificationHandler struct {
	Registry *notifications.NotificationDefinitionRegistry
}

func (h *NotificationHandler) Handle() echo.MiddlewareFunc {
	return func(hf echo.HandlerFunc) echo.HandlerFunc {
		return func(c *echo.Context) error {
			hf(c)
			resourceType := c.Get("Resource")
			if resourceType != nil {
				rs := resourceType.(string)
				resource := c.Get(rs)
				actionType := c.Get("Action")

				var reg *notifications.NotificationDefinitionRegistry
				if h.Registry != nil {
					reg = h.Registry
				} else {
					reg = notifications.DefaultNotificationDefinitionRegistry
				}
				for _, def := range reg.GetAll() {
					if def.Triggers(resource, actionType.(string)) {
						notification := def.GetNotification(resource, actionType.(string), h.getBaseURL(c.Request()))
						err := server.Database.C("communicationrequests").Insert(notification)
						if err != nil {
							log.Printf("Error creating notification.\n\tNotification: %#v\n\tResource: %#v\n\tError: %#v", notification, resource, err)
							return err
						}
					}
				}
			}
			return nil
		}
	}
}

func (h *NotificationHandler) getBaseURL(r *http.Request) string {
	newURL := url.URL(*r.URL)
	if newURL.Host == "" {
		newURL.Host = r.Host
	}
	if newURL.Scheme == "" {
		if strings.HasSuffix(newURL.Host, ":443") {
			newURL.Scheme = "https"
		} else {
			newURL.Scheme = "http"
		}
	}
	newURL.Path = ""

	return newURL.String()
}
<commit_msg>Encounter notifications should only happen on POST<commit_after>package middleware

import (
	"log"
	"net/http"
	"net/url"
	"strings"

	"github.com/intervention-engine/fhir/server"
	"github.com/intervention-engine/ie/notifications"
	"github.com/labstack/echo"
)

type NotificationHandler struct {
	Registry *notifications.NotificationDefinitionRegistry
}

func (h *NotificationHandler) Handle() echo.MiddlewareFunc {
	return func(hf echo.HandlerFunc) echo.HandlerFunc {
		return func(c *echo.Context) error {
			hf(c)
			if c.Request().Method != "POST" {
				return nil
			}

			resourceType := c.Get("Resource")
			if resourceType != nil {
				rs := resourceType.(string)
				resource := c.Get(rs)
				actionType := c.Get("Action")

				var reg *notifications.NotificationDefinitionRegistry
				if h.Registry != nil {
					reg = h.Registry
				} else {
					reg = notifications.DefaultNotificationDefinitionRegistry
				}
				for _, def := range reg.GetAll() {
					if def.Triggers(resource, actionType.(string)) {
						notification := def.GetNotification(resource, actionType.(string), h.getBaseURL(c.Request()))
						err := server.Database.C("communicationrequests").Insert(notification)
						if err != nil {
							log.Printf("Error creating notification.\n\tNotification: %#v\n\tResource: %#v\n\tError: %#v", notification, resource, err)
							return err
						}
					}
				}
			}
			return nil
		}
	}
}

func (h *NotificationHandler) getBaseURL(r *http.Request) string {
	newURL := url.URL(*r.URL)
	if newURL.Host == "" {
		newURL.Host = r.Host
	}
	if newURL.Scheme == "" {
		if strings.HasSuffix(newURL.Host, ":443") {
			newURL.Scheme = "https"
		} else {
			newURL.Scheme = "http"
		}
	}
	newURL.Path = ""

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


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

package main

import (
	"fmt"
	"io"
	"os"
	"testing"
	"time"

	"v.io/v23"
	"v.io/v23/context"
	"v.io/v23/options"
	"v.io/x/ref/services/mounttable/mounttablelib"
	"v.io/x/ref/test"
	"v.io/x/ref/test/modules"
)

//go:generate v23 test generate

func rootMT(stdin io.Reader, stdout, stderr io.Writer, env map[string]string, args ...string) error {
	ctx, shutdown := v23.Init()
	defer shutdown()

	lspec := v23.GetListenSpec(ctx)
	server, err := v23.NewServer(ctx, options.ServesMountTable(true))
	if err != nil {
		return fmt.Errorf("root failed: %v", err)
	}
	mt, err := mounttablelib.NewMountTableDispatcher("", "mounttable")
	if err != nil {
		return fmt.Errorf("mounttable.NewMountTableDispatcher failed: %s", err)
	}
	eps, err := server.Listen(lspec)
	if err != nil {
		return fmt.Errorf("server.Listen failed: %s", err)
	}
	if err := server.ServeDispatcher("", mt); err != nil {
		return fmt.Errorf("root failed: %s", err)
	}
	fmt.Fprintf(stdout, "PID=%d\n", os.Getpid())
	for _, ep := range eps {
		fmt.Fprintf(stdout, "MT_NAME=%s\n", ep.Name())
	}
	modules.WaitForEOF(stdin)
	return nil
}

// Starts a mounttable.  Returns the name and a stop function.
func startMountTable(t *testing.T, ctx *context.T) (string, func()) {
	sh, err := modules.NewShell(ctx, nil, testing.Verbose(), t)
	if err != nil {
		t.Fatalf("unexpected error: %s", err)
	}

	rootMT, err := sh.Start("rootMT", nil, "--v23.tcp.address=127.0.0.1:0")
	if err != nil {
		t.Fatalf("failed to start root mount table: %s", err)
	}
	rootMT.ExpectVar("PID")
	rootName := rootMT.ExpectVar("MT_NAME")

	return rootName, func() {
		if err := sh.Cleanup(nil, nil); err != nil {
			t.Fatalf("failed to cleanup shell: %s", rootMT.Error())
		}
	}
}

// Asserts that the channel contains members with expected names and no others.
func AssertMembersWithNames(channel *channel, expectedNames []string) error {
	members, err := channel.getMembers()
	if err != nil {
		return fmt.Errorf("channel.getMembers() failed: %v", err)
	}
	if actualLen, expectedLen := len(members), len(expectedNames); actualLen != expectedLen {
		return fmt.Errorf("Wrong number of members.  Expected %v, actual %v.", expectedLen, actualLen)
	}
	for _, expectedName := range expectedNames {
		found := false
		for _, member := range members {
			if member.Name == expectedName {
				found = true
				break
			}
		}
		if !found {
			return fmt.Errorf("Expected member with name %v, but did not find one.", expectedName)
		}
	}
	return nil
}

func TestMembers(t *testing.T) {
	ctx, shutdown := test.InitForTest()
	defer shutdown()

	mounttable, stopMountTable := startMountTable(t, ctx)
	defer stopMountTable()

	proxy := ""

	path := "path/to/channel"

	// Create a new channel.
	channel, err := newChannel(ctx, mounttable, proxy, path)
	if err != nil {
		t.Fatal("newChannel(%v, %v, %v) failed: %v", ctx, mounttable, proxy, path)
	}

	// New channel should be empty.
	if err := AssertMembersWithNames(channel, []string{}); err != nil {
		t.Error(err)
	}

	// Join the channel.
	if err := channel.join(); err != nil {
		t.Fatalf("channel.join() failed: %v", err)
	}

	// Channel should contain only current user.
	if err := AssertMembersWithNames(channel, []string{channel.UserName()}); err != nil {
		t.Error(err)
	}

	// Create and join the channel a second time.
	channel2, err := newChannel(ctx, mounttable, proxy, path)
	if err != nil {
		t.Fatal("newChannel(%v, %v, %v) failed: %v", ctx, mounttable, proxy, path)
	}
	if err := channel2.join(); err != nil {
		t.Fatalf("channel2.join() failed: %v", err)
	}

	// Channel should contain both users.
	if err := AssertMembersWithNames(channel, []string{channel.UserName(), channel2.UserName()}); err != nil {
		t.Error(err)
	}

	// Leave first instance of channel.
	if err := channel.leave(); err != nil {
		t.Fatalf("channel.leave() failed: %v", err)
	}

	// Channel should contain only second user.
	if err := AssertMembersWithNames(channel, []string{channel2.UserName()}); err != nil {
		t.Error(err)
	}

	// Leave second instance of channel.
	if err := channel2.leave(); err != nil {
		t.Fatalf("channel2.leave() failed: %v", err)
	}

	// Channel should be empty.
	if err := AssertMembersWithNames(channel, []string{}); err != nil {
		t.Error(err)
	}
}

func TestBroadcastMessage(t *testing.T) {
	ctx, shutdown := test.InitForTest()
	defer shutdown()

	mounttable, stopMountTable := startMountTable(t, ctx)
	defer stopMountTable()

	proxy := ""

	path := "path/to/channel"

	channel, err := newChannel(ctx, mounttable, proxy, path)
	if err != nil {
		t.Fatalf("newChannel(%v, %v, %v) failed: %v", ctx, mounttable, proxy, path, err)
	}

	defer channel.leave()

	if err := channel.join(); err != nil {
		t.Fatalf("channel.join() failed: %v", err)
	}

	message := "Hello Vanadium world!"

	go func() {
		// Call getMembers(), which will set channel.members, used by
		// channel.broadcastMessage().
		if _, err := channel.getMembers(); err != nil {
			t.Fatalf("channel.getMembers() failed: %v", err)
		}
		if err := channel.broadcastMessage(message); err != nil {
			t.Fatalf("channel.broadcastMessage(%v) failed: %v", message, err)
		}
	}()

	select {
	case <-time.After(10 * time.Second):
		t.Errorf("Timeout waiting for message to be received.")
	case m := <-channel.messages:
		if m.Text != message {
			t.Errorf("Expected message text to be %v but got %v", message, m.Text)
		}
		if got, want := m.SenderName, channel.UserName(); got != want {
			t.Errorf("Got m.SenderName = %v, want %v", got, want)
		}
	}
}
<commit_msg>mounttablelib: Persist permissions to the underlying file system.<commit_after>// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"io"
	"os"
	"testing"
	"time"

	"v.io/v23"
	"v.io/v23/context"
	"v.io/v23/options"
	"v.io/x/ref/services/mounttable/mounttablelib"
	"v.io/x/ref/test"
	"v.io/x/ref/test/modules"
)

//go:generate v23 test generate

func rootMT(stdin io.Reader, stdout, stderr io.Writer, env map[string]string, args ...string) error {
	ctx, shutdown := v23.Init()
	defer shutdown()

	lspec := v23.GetListenSpec(ctx)
	server, err := v23.NewServer(ctx, options.ServesMountTable(true))
	if err != nil {
		return fmt.Errorf("root failed: %v", err)
	}
	mt, err := mounttablelib.NewMountTableDispatcher("", "", "mounttable")
	if err != nil {
		return fmt.Errorf("mounttable.NewMountTableDispatcher failed: %s", err)
	}
	eps, err := server.Listen(lspec)
	if err != nil {
		return fmt.Errorf("server.Listen failed: %s", err)
	}
	if err := server.ServeDispatcher("", mt); err != nil {
		return fmt.Errorf("root failed: %s", err)
	}
	fmt.Fprintf(stdout, "PID=%d\n", os.Getpid())
	for _, ep := range eps {
		fmt.Fprintf(stdout, "MT_NAME=%s\n", ep.Name())
	}
	modules.WaitForEOF(stdin)
	return nil
}

// Starts a mounttable.  Returns the name and a stop function.
func startMountTable(t *testing.T, ctx *context.T) (string, func()) {
	sh, err := modules.NewShell(ctx, nil, testing.Verbose(), t)
	if err != nil {
		t.Fatalf("unexpected error: %s", err)
	}

	rootMT, err := sh.Start("rootMT", nil, "--v23.tcp.address=127.0.0.1:0")
	if err != nil {
		t.Fatalf("failed to start root mount table: %s", err)
	}
	rootMT.ExpectVar("PID")
	rootName := rootMT.ExpectVar("MT_NAME")

	return rootName, func() {
		if err := sh.Cleanup(nil, nil); err != nil {
			t.Fatalf("failed to cleanup shell: %s", rootMT.Error())
		}
	}
}

// Asserts that the channel contains members with expected names and no others.
func AssertMembersWithNames(channel *channel, expectedNames []string) error {
	members, err := channel.getMembers()
	if err != nil {
		return fmt.Errorf("channel.getMembers() failed: %v", err)
	}
	if actualLen, expectedLen := len(members), len(expectedNames); actualLen != expectedLen {
		return fmt.Errorf("Wrong number of members.  Expected %v, actual %v.", expectedLen, actualLen)
	}
	for _, expectedName := range expectedNames {
		found := false
		for _, member := range members {
			if member.Name == expectedName {
				found = true
				break
			}
		}
		if !found {
			return fmt.Errorf("Expected member with name %v, but did not find one.", expectedName)
		}
	}
	return nil
}

func TestMembers(t *testing.T) {
	ctx, shutdown := test.InitForTest()
	defer shutdown()

	mounttable, stopMountTable := startMountTable(t, ctx)
	defer stopMountTable()

	proxy := ""

	path := "path/to/channel"

	// Create a new channel.
	channel, err := newChannel(ctx, mounttable, proxy, path)
	if err != nil {
		t.Fatal("newChannel(%v, %v, %v) failed: %v", ctx, mounttable, proxy, path)
	}

	// New channel should be empty.
	if err := AssertMembersWithNames(channel, []string{}); err != nil {
		t.Error(err)
	}

	// Join the channel.
	if err := channel.join(); err != nil {
		t.Fatalf("channel.join() failed: %v", err)
	}

	// Channel should contain only current user.
	if err := AssertMembersWithNames(channel, []string{channel.UserName()}); err != nil {
		t.Error(err)
	}

	// Create and join the channel a second time.
	channel2, err := newChannel(ctx, mounttable, proxy, path)
	if err != nil {
		t.Fatal("newChannel(%v, %v, %v) failed: %v", ctx, mounttable, proxy, path)
	}
	if err := channel2.join(); err != nil {
		t.Fatalf("channel2.join() failed: %v", err)
	}

	// Channel should contain both users.
	if err := AssertMembersWithNames(channel, []string{channel.UserName(), channel2.UserName()}); err != nil {
		t.Error(err)
	}

	// Leave first instance of channel.
	if err := channel.leave(); err != nil {
		t.Fatalf("channel.leave() failed: %v", err)
	}

	// Channel should contain only second user.
	if err := AssertMembersWithNames(channel, []string{channel2.UserName()}); err != nil {
		t.Error(err)
	}

	// Leave second instance of channel.
	if err := channel2.leave(); err != nil {
		t.Fatalf("channel2.leave() failed: %v", err)
	}

	// Channel should be empty.
	if err := AssertMembersWithNames(channel, []string{}); err != nil {
		t.Error(err)
	}
}

func TestBroadcastMessage(t *testing.T) {
	ctx, shutdown := test.InitForTest()
	defer shutdown()

	mounttable, stopMountTable := startMountTable(t, ctx)
	defer stopMountTable()

	proxy := ""

	path := "path/to/channel"

	channel, err := newChannel(ctx, mounttable, proxy, path)
	if err != nil {
		t.Fatalf("newChannel(%v, %v, %v) failed: %v", ctx, mounttable, proxy, path, err)
	}

	defer channel.leave()

	if err := channel.join(); err != nil {
		t.Fatalf("channel.join() failed: %v", err)
	}

	message := "Hello Vanadium world!"

	go func() {
		// Call getMembers(), which will set channel.members, used by
		// channel.broadcastMessage().
		if _, err := channel.getMembers(); err != nil {
			t.Fatalf("channel.getMembers() failed: %v", err)
		}
		if err := channel.broadcastMessage(message); err != nil {
			t.Fatalf("channel.broadcastMessage(%v) failed: %v", message, err)
		}
	}()

	select {
	case <-time.After(10 * time.Second):
		t.Errorf("Timeout waiting for message to be received.")
	case m := <-channel.messages:
		if m.Text != message {
			t.Errorf("Expected message text to be %v but got %v", message, m.Text)
		}
		if got, want := m.SenderName, channel.UserName(); got != want {
			t.Errorf("Got m.SenderName = %v, want %v", got, want)
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2016 The Kubernetes Authors.

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

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

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

package apiserver

import (
	"net/http"

	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
	v1listers "k8s.io/client-go/listers/core/v1"

	apiregistrationapi "k8s.io/kube-aggregator/pkg/apis/apiregistration"
	apiregistrationv1alpha1api "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1alpha1"
	listers "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/internalversion"
)

// apisHandler serves the `/apis` endpoint.
// This is registered as a filter so that it never collides with any explictly registered endpoints
type apisHandler struct {
	codecs serializer.CodecFactory
	lister listers.APIServiceLister

	serviceLister   v1listers.ServiceLister
	endpointsLister v1listers.EndpointsLister

	delegate http.Handler
}

var discoveryGroup = metav1.APIGroup{
	Name: apiregistrationapi.GroupName,
	Versions: []metav1.GroupVersionForDiscovery{
		{
			GroupVersion: apiregistrationv1alpha1api.SchemeGroupVersion.String(),
			Version:      apiregistrationv1alpha1api.SchemeGroupVersion.Version,
		},
	},
	PreferredVersion: metav1.GroupVersionForDiscovery{
		GroupVersion: apiregistrationv1alpha1api.SchemeGroupVersion.String(),
		Version:      apiregistrationv1alpha1api.SchemeGroupVersion.Version,
	},
}

func (r *apisHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// don't handle URLs that aren't /apis
	if req.URL.Path != "/apis" && req.URL.Path != "/apis/" {
		r.delegate.ServeHTTP(w, req)
		return
	}

	discoveryGroupList := &metav1.APIGroupList{
		// always add OUR api group to the list first.  Since we'll never have a registered APIService for it
		// and since this is the crux of the API, having this first will give our names priority.  It's good to be king.
		Groups: []metav1.APIGroup{discoveryGroup},
	}

	apiServices, err := r.lister.List(labels.Everything())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	apiServicesByGroup := apiregistrationapi.SortedByGroup(apiServices)
	for _, apiGroupServers := range apiServicesByGroup {
		// skip the legacy group
		if len(apiGroupServers[0].Spec.Group) == 0 {
			continue
		}
		discoveryGroup := convertToDiscoveryAPIGroup(apiGroupServers, r.serviceLister, r.endpointsLister)
		if discoveryGroup != nil {
			discoveryGroupList.Groups = append(discoveryGroupList.Groups, *discoveryGroup)
		}
	}

	json, err := runtime.Encode(r.codecs.LegacyCodec(), discoveryGroupList)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if _, err := w.Write(json); err != nil {
		panic(err)
	}
}

// convertToDiscoveryAPIGroup takes apiservices in a single group and returns a discovery compatible object.
// if none of the services are available, it will return nil.
func convertToDiscoveryAPIGroup(apiServices []*apiregistrationapi.APIService, serviceLister v1listers.ServiceLister, endpointsLister v1listers.EndpointsLister) *metav1.APIGroup {
	apiServicesByGroup := apiregistrationapi.SortedByGroup(apiServices)[0]

	var discoveryGroup *metav1.APIGroup

	for _, apiService := range apiServicesByGroup {
		if apiService.Spec.Service != nil {
			// skip any API services without actual services
			if _, err := serviceLister.Services(apiService.Spec.Service.Namespace).Get(apiService.Spec.Service.Name); err != nil {
				continue
			}

			hasActiveEndpoints := false
			endpoints, err := endpointsLister.Endpoints(apiService.Spec.Service.Namespace).Get(apiService.Spec.Service.Name)
			// skip any API services without endpoints
			if err != nil {
				continue
			}
			for _, subset := range endpoints.Subsets {
				if len(subset.Addresses) > 0 {
					hasActiveEndpoints = true
					break
				}
			}
			if !hasActiveEndpoints {
				continue
			}
		}

		// the first APIService which is valid becomes the default
		if discoveryGroup == nil {
			discoveryGroup = &metav1.APIGroup{
				Name: apiService.Spec.Group,
				PreferredVersion: metav1.GroupVersionForDiscovery{
					GroupVersion: apiService.Spec.Group + "/" + apiService.Spec.Version,
					Version:      apiService.Spec.Version,
				},
			}
		}

		discoveryGroup.Versions = append(discoveryGroup.Versions,
			metav1.GroupVersionForDiscovery{
				GroupVersion: apiService.Spec.Group + "/" + apiService.Spec.Version,
				Version:      apiService.Spec.Version,
			},
		)
	}

	return discoveryGroup
}

// apiGroupHandler serves the `/apis/<group>` endpoint.
type apiGroupHandler struct {
	codecs    serializer.CodecFactory
	groupName string

	lister listers.APIServiceLister

	serviceLister   v1listers.ServiceLister
	endpointsLister v1listers.EndpointsLister

	delegate http.Handler
}

func (r *apiGroupHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// don't handle URLs that aren't /apis/<groupName>
	if req.URL.Path != "/apis/"+r.groupName && req.URL.Path != "/apis/"+r.groupName+"/" {
		r.delegate.ServeHTTP(w, req)
		return
	}

	apiServices, err := r.lister.List(labels.Everything())
	if statusErr, ok := err.(*apierrors.StatusError); ok && err != nil {
		responsewriters.WriteRawJSON(int(statusErr.Status().Code), statusErr.Status(), w)
		return
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	apiServicesForGroup := []*apiregistrationapi.APIService{}
	for _, apiService := range apiServices {
		if apiService.Spec.Group == r.groupName {
			apiServicesForGroup = append(apiServicesForGroup, apiService)
		}
	}

	if len(apiServicesForGroup) == 0 {
		r.delegate.ServeHTTP(w, req)
		return
	}

	discoveryGroup := convertToDiscoveryAPIGroup(apiServicesForGroup, r.serviceLister, r.endpointsLister)
	if discoveryGroup == nil {
		http.Error(w, "", http.StatusNotFound)
		return
	}
	json, err := runtime.Encode(r.codecs.LegacyCodec(), discoveryGroup)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if _, err := w.Write(json); err != nil {
		panic(err)
	}
}
<commit_msg>Fix Content-Type error of apis<commit_after>/*
Copyright 2016 The Kubernetes Authors.

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

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

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

package apiserver

import (
	"net/http"

	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
	v1listers "k8s.io/client-go/listers/core/v1"

	apiregistrationapi "k8s.io/kube-aggregator/pkg/apis/apiregistration"
	apiregistrationv1alpha1api "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1alpha1"
	listers "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/internalversion"
)

// apisHandler serves the `/apis` endpoint.
// This is registered as a filter so that it never collides with any explictly registered endpoints
type apisHandler struct {
	codecs serializer.CodecFactory
	lister listers.APIServiceLister

	serviceLister   v1listers.ServiceLister
	endpointsLister v1listers.EndpointsLister

	delegate http.Handler
}

var discoveryGroup = metav1.APIGroup{
	Name: apiregistrationapi.GroupName,
	Versions: []metav1.GroupVersionForDiscovery{
		{
			GroupVersion: apiregistrationv1alpha1api.SchemeGroupVersion.String(),
			Version:      apiregistrationv1alpha1api.SchemeGroupVersion.Version,
		},
	},
	PreferredVersion: metav1.GroupVersionForDiscovery{
		GroupVersion: apiregistrationv1alpha1api.SchemeGroupVersion.String(),
		Version:      apiregistrationv1alpha1api.SchemeGroupVersion.Version,
	},
}

func (r *apisHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// don't handle URLs that aren't /apis
	if req.URL.Path != "/apis" && req.URL.Path != "/apis/" {
		r.delegate.ServeHTTP(w, req)
		return
	}

	discoveryGroupList := &metav1.APIGroupList{
		// always add OUR api group to the list first.  Since we'll never have a registered APIService for it
		// and since this is the crux of the API, having this first will give our names priority.  It's good to be king.
		Groups: []metav1.APIGroup{discoveryGroup},
	}

	apiServices, err := r.lister.List(labels.Everything())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	apiServicesByGroup := apiregistrationapi.SortedByGroup(apiServices)
	for _, apiGroupServers := range apiServicesByGroup {
		// skip the legacy group
		if len(apiGroupServers[0].Spec.Group) == 0 {
			continue
		}
		discoveryGroup := convertToDiscoveryAPIGroup(apiGroupServers, r.serviceLister, r.endpointsLister)
		if discoveryGroup != nil {
			discoveryGroupList.Groups = append(discoveryGroupList.Groups, *discoveryGroup)
		}
	}

	responsewriters.WriteObjectNegotiated(r.codecs, schema.GroupVersion{}, w, req, http.StatusOK, discoveryGroupList)
}

// convertToDiscoveryAPIGroup takes apiservices in a single group and returns a discovery compatible object.
// if none of the services are available, it will return nil.
func convertToDiscoveryAPIGroup(apiServices []*apiregistrationapi.APIService, serviceLister v1listers.ServiceLister, endpointsLister v1listers.EndpointsLister) *metav1.APIGroup {
	apiServicesByGroup := apiregistrationapi.SortedByGroup(apiServices)[0]

	var discoveryGroup *metav1.APIGroup

	for _, apiService := range apiServicesByGroup {
		if apiService.Spec.Service != nil {
			// skip any API services without actual services
			if _, err := serviceLister.Services(apiService.Spec.Service.Namespace).Get(apiService.Spec.Service.Name); err != nil {
				continue
			}

			hasActiveEndpoints := false
			endpoints, err := endpointsLister.Endpoints(apiService.Spec.Service.Namespace).Get(apiService.Spec.Service.Name)
			// skip any API services without endpoints
			if err != nil {
				continue
			}
			for _, subset := range endpoints.Subsets {
				if len(subset.Addresses) > 0 {
					hasActiveEndpoints = true
					break
				}
			}
			if !hasActiveEndpoints {
				continue
			}
		}

		// the first APIService which is valid becomes the default
		if discoveryGroup == nil {
			discoveryGroup = &metav1.APIGroup{
				Name: apiService.Spec.Group,
				PreferredVersion: metav1.GroupVersionForDiscovery{
					GroupVersion: apiService.Spec.Group + "/" + apiService.Spec.Version,
					Version:      apiService.Spec.Version,
				},
			}
		}

		discoveryGroup.Versions = append(discoveryGroup.Versions,
			metav1.GroupVersionForDiscovery{
				GroupVersion: apiService.Spec.Group + "/" + apiService.Spec.Version,
				Version:      apiService.Spec.Version,
			},
		)
	}

	return discoveryGroup
}

// apiGroupHandler serves the `/apis/<group>` endpoint.
type apiGroupHandler struct {
	codecs    serializer.CodecFactory
	groupName string

	lister listers.APIServiceLister

	serviceLister   v1listers.ServiceLister
	endpointsLister v1listers.EndpointsLister

	delegate http.Handler
}

func (r *apiGroupHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// don't handle URLs that aren't /apis/<groupName>
	if req.URL.Path != "/apis/"+r.groupName && req.URL.Path != "/apis/"+r.groupName+"/" {
		r.delegate.ServeHTTP(w, req)
		return
	}

	apiServices, err := r.lister.List(labels.Everything())
	if statusErr, ok := err.(*apierrors.StatusError); ok && err != nil {
		responsewriters.WriteRawJSON(int(statusErr.Status().Code), statusErr.Status(), w)
		return
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	apiServicesForGroup := []*apiregistrationapi.APIService{}
	for _, apiService := range apiServices {
		if apiService.Spec.Group == r.groupName {
			apiServicesForGroup = append(apiServicesForGroup, apiService)
		}
	}

	if len(apiServicesForGroup) == 0 {
		r.delegate.ServeHTTP(w, req)
		return
	}

	discoveryGroup := convertToDiscoveryAPIGroup(apiServicesForGroup, r.serviceLister, r.endpointsLister)
	if discoveryGroup == nil {
		http.Error(w, "", http.StatusNotFound)
		return
	}
	responsewriters.WriteObjectNegotiated(r.codecs, schema.GroupVersion{}, w, req, http.StatusOK, discoveryGroup)
}
<|endoftext|>


<commit_before>package driver

import (
	"testing"
)

func TestNew(t *testing.T) {
	if _, err := New("unknown://host/database"); err == nil {
		t.Error("no error although driver unknown")
	}
}
<commit_msg>update test<commit_after>package driver

import (
	"testing"
)

func TestNew(t *testing.T) {
	if _, err := New("unknown://url"); err == nil {
		t.Error("no error although driver unknown")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/klauspost/doproxy/server"
	"github.com/klauspost/shutdown"
	"os"
	"syscall"
	"time"
	"log"
)

func main() {
	shutdown.Logger = log.New(os.Stdout, "", log.LstdFlags)
	shutdown.OnSignal(0, os.Interrupt, syscall.SIGTERM)
	shutdown.SetTimeout(time.Second)
	s, err := server.NewServer("doproxy.toml")
	if err != nil {
		log.Fatal("Error loading server configuration:", err)
	}
	s.Run()
}
<commit_msg>Add commandline parameter for config file.<commit_after>package main

import (
	"flag"
	"github.com/klauspost/doproxy/server"
	"github.com/klauspost/shutdown"
	"log"
	"os"
	"syscall"
	"time"
)

var configfile = flag.String("config", "doproxy.toml", "Use this config file")

func main() {
	flag.Parse()
	shutdown.Logger = log.New(os.Stdout, "", log.LstdFlags)
	shutdown.OnSignal(0, os.Interrupt, syscall.SIGTERM)
	shutdown.SetTimeout(time.Second)
	s, err := server.NewServer(*configfile)
	if err != nil {
		log.Fatal("Error loading server configuration:", err)
	}
	s.Run()
}
<|endoftext|>


<commit_before>// Copyright 2016 yryz Author. All Rights Reserved.

package ds18b20

import (
	"errors"
	"io/ioutil"
	"strconv"
	"strings"
)

// Sensors get all connected sensor IDs as array
func Sensors() ([]string, error) {
	data, err := ioutil.ReadFile("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves")
	if err != nil {
		return nil, err
	}

	return strings.Split(string(data), "\n"), nil
}

// Temperature get the temperature of a given sensor
func Temperature(sensor string) (float64, error) {
	data, err := ioutil.ReadFile("/sys/bus/w1/devices/" + sensor + "/w1_slave")
	if err != nil {
		return 0.0, nil
	}

	if strings.Contains(string(data), "YES") {
		arr := strings.SplitN(string(data), " ", 3)

		switch arr[1][0] {
		case 'f': //-0.5 ~ -55°C
			x, err := strconv.ParseInt(arr[1]+arr[0], 16, 32)
			if err != nil {
				return 0.0, err
			}
			return float64(^x+1) * 0.0625, nil

		case '0': //0~125°C
			x, err := strconv.ParseInt(arr[1]+arr[0], 16, 32)
			if err != nil {
				return 0.0, err
			}
			return float64(x) * 0.0625, nil
		}
	}

	return 0.0, errors.New("can not read temperature for sensor " + sensor)
}
<commit_msg>fix ds18b20.Sensors()<commit_after>// Copyright 2016 yryz Author. All Rights Reserved.

package ds18b20

import (
	"errors"
	"io/ioutil"
	"strconv"
	"strings"
)

// Sensors get all connected sensor IDs as array
func Sensors() ([]string, error) {
	data, err := ioutil.ReadFile("/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves")
	if err != nil {
		return nil, err
	}

	sensors := strings.Split(string(data), "\n")
	if len(sensors) > 0 {
		sensors = sensors[:len(sensors)-1]
	}

	return sensors, nil
}

// Temperature get the temperature of a given sensor
func Temperature(sensor string) (float64, error) {
	data, err := ioutil.ReadFile("/sys/bus/w1/devices/" + sensor + "/w1_slave")
	if err != nil {
		return 0.0, nil
	}

	if strings.Contains(string(data), "YES") {
		arr := strings.SplitN(string(data), " ", 3)

		switch arr[1][0] {
		case 'f': //-0.5 ~ -55°C
			x, err := strconv.ParseInt(arr[1]+arr[0], 16, 32)
			if err != nil {
				return 0.0, err
			}
			return float64(^x+1) * 0.0625, nil

		case '0': //0~125°C
			x, err := strconv.ParseInt(arr[1]+arr[0], 16, 32)
			if err != nil {
				return 0.0, err
			}
			return float64(x) * 0.0625, nil
		}
	}

	return 0.0, errors.New("can not read temperature for sensor " + sensor)
}
<|endoftext|>


<commit_before>package parser

import (
	"fmt"
	"strconv"
	"strings"
	"unicode"
)

// Dump dumps the AST defined by `node` as a list of sexps.
// Returns a string suitable for printing.
func (node *Node) Dump() string {
	str := ""
	str += node.Value

	if len(node.Flags) > 0 {
		str += fmt.Sprintf(" %q", node.Flags)
	}

	for _, n := range node.Children {
		str += "(" + n.Dump() + ")\n"
	}

	for n := node.Next; n != nil; n = n.Next {
		if len(n.Children) > 0 {
			str += " " + n.Dump()
		} else {
			str += " " + strconv.Quote(n.Value)
		}
	}

	return strings.TrimSpace(str)
}

// performs the dispatch based on the two primal strings, cmd and args. Please
// look at the dispatch table in parser.go to see how these dispatchers work.
func fullDispatch(cmd, args string, d *Directive) (*Node, map[string]bool, error) {
	fn := dispatch[cmd]

	// Ignore invalid Dockerfile instructions
	if fn == nil {
		fn = parseIgnore
	}

	sexp, attrs, err := fn(args, d)
	if err != nil {
		return nil, nil, err
	}

	return sexp, attrs, nil
}

// splitCommand takes a single line of text and parses out the cmd and args,
// which are used for dispatching to more exact parsing functions.
func splitCommand(line string) (string, []string, string, error) {
	var args string
	var flags []string

	// Make sure we get the same results irrespective of leading/trailing spaces
	cmdline := tokenWhitespace.Split(strings.TrimSpace(line), 2)
	cmd := strings.ToLower(cmdline[0])

	if len(cmdline) == 2 {
		var err error
		args, flags, err = extractBuilderFlags(cmdline[1])
		if err != nil {
			return "", nil, "", err
		}
	}

	return cmd, flags, strings.TrimSpace(args), nil
}

// covers comments and empty lines. Lines should be trimmed before passing to
// this function.
func stripComments(line string) string {
	// string is already trimmed at this point
	if tokenComment.MatchString(line) {
		return tokenComment.ReplaceAllString(line, "")
	}

	return line
}

func extractBuilderFlags(line string) (string, []string, error) {
	// Parses the BuilderFlags and returns the remaining part of the line

	const (
		inSpaces = iota // looking for start of a word
		inWord
		inQuote
	)

	words := []string{}
	phase := inSpaces
	word := ""
	quote := '\000'
	blankOK := false
	var ch rune

	for pos := 0; pos <= len(line); pos++ {
		if pos != len(line) {
			ch = rune(line[pos])
		}

		if phase == inSpaces { // Looking for start of word
			if pos == len(line) { // end of input
				break
			}
			if unicode.IsSpace(ch) { // skip spaces
				continue
			}

			// Only keep going if the next word starts with --
			if ch != '-' || pos+1 == len(line) || rune(line[pos+1]) != '-' {
				return line[pos:], words, nil
			}

			phase = inWord // found someting with "--", fall through
		}
		if (phase == inWord || phase == inQuote) && (pos == len(line)) {
			if word != "--" && (blankOK || len(word) > 0) {
				words = append(words, word)
			}
			break
		}
		if phase == inWord {
			if unicode.IsSpace(ch) {
				phase = inSpaces
				if word == "--" {
					return line[pos:], words, nil
				}
				if blankOK || len(word) > 0 {
					words = append(words, word)
				}
				word = ""
				blankOK = false
				continue
			}
			if ch == '\'' || ch == '"' {
				quote = ch
				blankOK = true
				phase = inQuote
				continue
			}
			if ch == '\\' {
				if pos+1 == len(line) {
					continue // just skip \ at end
				}
				pos++
				ch = rune(line[pos])
			}
			word += string(ch)
			continue
		}
		if phase == inQuote {
			if ch == quote {
				phase = inWord
				continue
			}
			if ch == '\\' {
				if pos+1 == len(line) {
					phase = inWord
					continue // just skip \ at end
				}
				pos++
				ch = rune(line[pos])
			}
			word += string(ch)
		}
	}

	return "", words, nil
}
<commit_msg>fix misspell in utils.go<commit_after>package parser

import (
	"fmt"
	"strconv"
	"strings"
	"unicode"
)

// Dump dumps the AST defined by `node` as a list of sexps.
// Returns a string suitable for printing.
func (node *Node) Dump() string {
	str := ""
	str += node.Value

	if len(node.Flags) > 0 {
		str += fmt.Sprintf(" %q", node.Flags)
	}

	for _, n := range node.Children {
		str += "(" + n.Dump() + ")\n"
	}

	for n := node.Next; n != nil; n = n.Next {
		if len(n.Children) > 0 {
			str += " " + n.Dump()
		} else {
			str += " " + strconv.Quote(n.Value)
		}
	}

	return strings.TrimSpace(str)
}

// performs the dispatch based on the two primal strings, cmd and args. Please
// look at the dispatch table in parser.go to see how these dispatchers work.
func fullDispatch(cmd, args string, d *Directive) (*Node, map[string]bool, error) {
	fn := dispatch[cmd]

	// Ignore invalid Dockerfile instructions
	if fn == nil {
		fn = parseIgnore
	}

	sexp, attrs, err := fn(args, d)
	if err != nil {
		return nil, nil, err
	}

	return sexp, attrs, nil
}

// splitCommand takes a single line of text and parses out the cmd and args,
// which are used for dispatching to more exact parsing functions.
func splitCommand(line string) (string, []string, string, error) {
	var args string
	var flags []string

	// Make sure we get the same results irrespective of leading/trailing spaces
	cmdline := tokenWhitespace.Split(strings.TrimSpace(line), 2)
	cmd := strings.ToLower(cmdline[0])

	if len(cmdline) == 2 {
		var err error
		args, flags, err = extractBuilderFlags(cmdline[1])
		if err != nil {
			return "", nil, "", err
		}
	}

	return cmd, flags, strings.TrimSpace(args), nil
}

// covers comments and empty lines. Lines should be trimmed before passing to
// this function.
func stripComments(line string) string {
	// string is already trimmed at this point
	if tokenComment.MatchString(line) {
		return tokenComment.ReplaceAllString(line, "")
	}

	return line
}

func extractBuilderFlags(line string) (string, []string, error) {
	// Parses the BuilderFlags and returns the remaining part of the line

	const (
		inSpaces = iota // looking for start of a word
		inWord
		inQuote
	)

	words := []string{}
	phase := inSpaces
	word := ""
	quote := '\000'
	blankOK := false
	var ch rune

	for pos := 0; pos <= len(line); pos++ {
		if pos != len(line) {
			ch = rune(line[pos])
		}

		if phase == inSpaces { // Looking for start of word
			if pos == len(line) { // end of input
				break
			}
			if unicode.IsSpace(ch) { // skip spaces
				continue
			}

			// Only keep going if the next word starts with --
			if ch != '-' || pos+1 == len(line) || rune(line[pos+1]) != '-' {
				return line[pos:], words, nil
			}

			phase = inWord // found something with "--", fall through
		}
		if (phase == inWord || phase == inQuote) && (pos == len(line)) {
			if word != "--" && (blankOK || len(word) > 0) {
				words = append(words, word)
			}
			break
		}
		if phase == inWord {
			if unicode.IsSpace(ch) {
				phase = inSpaces
				if word == "--" {
					return line[pos:], words, nil
				}
				if blankOK || len(word) > 0 {
					words = append(words, word)
				}
				word = ""
				blankOK = false
				continue
			}
			if ch == '\'' || ch == '"' {
				quote = ch
				blankOK = true
				phase = inQuote
				continue
			}
			if ch == '\\' {
				if pos+1 == len(line) {
					continue // just skip \ at end
				}
				pos++
				ch = rune(line[pos])
			}
			word += string(ch)
			continue
		}
		if phase == inQuote {
			if ch == quote {
				phase = inWord
				continue
			}
			if ch == '\\' {
				if pos+1 == len(line) {
					phase = inWord
					continue // just skip \ at end
				}
				pos++
				ch = rune(line[pos])
			}
			word += string(ch)
		}
	}

	return "", words, nil
}
<|endoftext|>