<commit_before>// Copyright 2015 Matthew Holt and The Caddy 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 fileserver

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"path"
	"strings"
	"text/template"

	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/caddy/v2/modules/caddyhttp"
	"github.com/caddyserver/caddy/v2/modules/caddyhttp/templates"
	"go.uber.org/zap"
)

// Browse configures directory browsing.
type Browse struct {
	// Use this template file instead of the default browse template.
	TemplateFile string `json:"template_file,omitempty"`

	template *template.Template
}

func (fsrv *FileServer) serveBrowse(root, dirPath string, w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	fsrv.logger.Debug("browse enabled; listing directory contents",
		zap.String("path", dirPath),
		zap.String("root", root))

	// navigation on the client-side gets messed up if the
	// URL doesn't end in a trailing slash because hrefs like
	// "/b/c" on a path like "/a" end up going to "/b/c" instead
	// of "/a/b/c" - so we have to redirect in this case
	oldReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
	if !strings.HasSuffix(oldReq.URL.Path, "/") {
		fsrv.logger.Debug("redirecting to trailing slash to preserve hrefs", zap.String("request_path", oldReq.URL.Path))
		http.Redirect(w, r, oldReq.URL.Path+"/", http.StatusMovedPermanently)
		return nil
	}

	dir, err := fsrv.openFile(dirPath, w)
	if err != nil {
		return err
	}
	defer dir.Close()

	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)

	// calling path.Clean here prevents weird breadcrumbs when URL paths are sketchy like /%2e%2e%2f
	listing, err := fsrv.loadDirectoryContents(dir, root, path.Clean(r.URL.Path), repl)
	switch {
	case os.IsPermission(err):
		return caddyhttp.Error(http.StatusForbidden, err)
	case os.IsNotExist(err):
		return fsrv.notFound(w, r, next)
	case err != nil:
		return caddyhttp.Error(http.StatusInternalServerError, err)
	}

	fsrv.browseApplyQueryParams(w, r, &listing)

	// write response as either JSON or HTML
	var buf *bytes.Buffer
	acceptHeader := strings.ToLower(strings.Join(r.Header["Accept"], ","))
	if strings.Contains(acceptHeader, "application/json") {
		if buf, err = fsrv.browseWriteJSON(listing); err != nil {
			return caddyhttp.Error(http.StatusInternalServerError, err)
		}
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	} else {
		var fs http.FileSystem
		if fsrv.Root != "" {
			fs = http.Dir(repl.ReplaceAll(fsrv.Root, "."))
		}

		var tplCtx = &templateContext{
			TemplateContext: templates.TemplateContext{
				Root:       fs,
				Req:        r,
				RespHeader: templates.WrappedHeader{Header: w.Header()},
			},
			browseTemplateContext: listing,
		}

		err = fsrv.makeBrowseTemplate(tplCtx)
		if err != nil {
			return fmt.Errorf("parsing browse template: %v", err)
		}

		if buf, err = fsrv.browseWriteHTML(tplCtx); err != nil {
			return caddyhttp.Error(http.StatusInternalServerError, err)
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
	}

	_, _ = buf.WriteTo(w)

	return nil
}

func (fsrv *FileServer) loadDirectoryContents(dir *os.File, root, urlPath string, repl *caddy.Replacer) (browseTemplateContext, error) {
	files, err := dir.Readdir(-1)
	if err != nil {
		return browseTemplateContext{}, err
	}

	// user can presumably browse "up" to parent folder if path is longer than "/"
	canGoUp := len(urlPath) > 1

	return fsrv.directoryListing(files, canGoUp, root, urlPath, repl), nil
}

// browseApplyQueryParams applies query parameters to the listing.
// It mutates the listing and may set cookies.
func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) {
	sortParam := r.URL.Query().Get("sort")
	orderParam := r.URL.Query().Get("order")
	limitParam := r.URL.Query().Get("limit")
	offsetParam := r.URL.Query().Get("offset")

	// first figure out what to sort by
	switch sortParam {
	case "":
		sortParam = sortByNameDirFirst
		if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil {
			sortParam = sortCookie.Value
		}
	case sortByName, sortByNameDirFirst, sortBySize, sortByTime:
		http.SetCookie(w, &http.Cookie{Name: "sort", Value: sortParam, Secure: r.TLS != nil})
	}

	// then figure out the order
	switch orderParam {
	case "":
		orderParam = "asc"
		if orderCookie, orderErr := r.Cookie("order"); orderErr == nil {
			orderParam = orderCookie.Value
		}
	case "asc", "desc":
		http.SetCookie(w, &http.Cookie{Name: "order", Value: orderParam, Secure: r.TLS != nil})
	}

	// finally, apply the sorting and limiting
	listing.applySortAndLimit(sortParam, orderParam, limitParam, offsetParam)
}

// makeBrowseTemplate creates the template to be used for directory listings.
func (fsrv *FileServer) makeBrowseTemplate(tplCtx *templateContext) error {
	var tpl *template.Template
	var err error

	if fsrv.Browse.TemplateFile != "" {
		tpl = tplCtx.NewTemplate(path.Base(fsrv.Browse.TemplateFile))
		tpl, err = tpl.ParseFiles(fsrv.Browse.TemplateFile)
		if err != nil {
			return fmt.Errorf("parsing browse template file: %v", err)
		}
	} else {
		tpl = tplCtx.NewTemplate("default_listing")
		tpl, err = tpl.Parse(defaultBrowseTemplate)
		if err != nil {
			return fmt.Errorf("parsing default browse template: %v", err)
		}
	}

	fsrv.Browse.template = tpl

	return nil
}

func (fsrv *FileServer) browseWriteJSON(listing browseTemplateContext) (*bytes.Buffer, error) {
	buf := bufPool.Get().(*bytes.Buffer)
	defer bufPool.Put(buf)
	err := json.NewEncoder(buf).Encode(listing.Items)
	return buf, err
}

func (fsrv *FileServer) browseWriteHTML(tplCtx *templateContext) (*bytes.Buffer, error) {
	buf := bufPool.Get().(*bytes.Buffer)
	defer bufPool.Put(buf)
	err := fsrv.Browse.template.Execute(buf, tplCtx)
	return buf, err
}

// isSymlink return true if f is a symbolic link
func isSymlink(f os.FileInfo) bool {
	return f.Mode()&os.ModeSymlink != 0
}

// isSymlinkTargetDir returns true if f's symbolic link target
// is a directory.
func isSymlinkTargetDir(f os.FileInfo, root, urlPath string) bool {
	if !isSymlink(f) {
		return false
	}
	target := sanitizedPathJoin(root, path.Join(urlPath, f.Name()))
	targetInfo, err := os.Stat(target)
	if err != nil {
		return false
	}
	return targetInfo.IsDir()
}

// templateContext powers the context used when evaluating the browse template.
// It combines browse-specific features with the standard templates handler
// features.
type templateContext struct {
	templates.TemplateContext
	browseTemplateContext
}
<commit_msg>fileserver: Fix browse not redirecting query parameters (#4196)<commit_after>// Copyright 2015 Matthew Holt and The Caddy 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 fileserver

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"path"
	"strings"
	"text/template"

	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/caddy/v2/modules/caddyhttp"
	"github.com/caddyserver/caddy/v2/modules/caddyhttp/templates"
	"go.uber.org/zap"
)

// Browse configures directory browsing.
type Browse struct {
	// Use this template file instead of the default browse template.
	TemplateFile string `json:"template_file,omitempty"`

	template *template.Template
}

func (fsrv *FileServer) serveBrowse(root, dirPath string, w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	fsrv.logger.Debug("browse enabled; listing directory contents",
		zap.String("path", dirPath),
		zap.String("root", root))

	// navigation on the client-side gets messed up if the
	// URL doesn't end in a trailing slash because hrefs like
	// "/b/c" on a path like "/a" end up going to "/b/c" instead
	// of "/a/b/c" - so we have to redirect in this case
	oldReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
	if !strings.HasSuffix(oldReq.URL.Path, "/") {
		fsrv.logger.Debug("redirecting to trailing slash to preserve hrefs", zap.String("request_path", oldReq.URL.Path))
		oldReq.URL.Path += "/"
		http.Redirect(w, r, oldReq.URL.String(), http.StatusMovedPermanently)
		return nil
	}

	dir, err := fsrv.openFile(dirPath, w)
	if err != nil {
		return err
	}
	defer dir.Close()

	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)

	// calling path.Clean here prevents weird breadcrumbs when URL paths are sketchy like /%2e%2e%2f
	listing, err := fsrv.loadDirectoryContents(dir, root, path.Clean(r.URL.Path), repl)
	switch {
	case os.IsPermission(err):
		return caddyhttp.Error(http.StatusForbidden, err)
	case os.IsNotExist(err):
		return fsrv.notFound(w, r, next)
	case err != nil:
		return caddyhttp.Error(http.StatusInternalServerError, err)
	}

	fsrv.browseApplyQueryParams(w, r, &listing)

	// write response as either JSON or HTML
	var buf *bytes.Buffer
	acceptHeader := strings.ToLower(strings.Join(r.Header["Accept"], ","))
	if strings.Contains(acceptHeader, "application/json") {
		if buf, err = fsrv.browseWriteJSON(listing); err != nil {
			return caddyhttp.Error(http.StatusInternalServerError, err)
		}
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	} else {
		var fs http.FileSystem
		if fsrv.Root != "" {
			fs = http.Dir(repl.ReplaceAll(fsrv.Root, "."))
		}

		var tplCtx = &templateContext{
			TemplateContext: templates.TemplateContext{
				Root:       fs,
				Req:        r,
				RespHeader: templates.WrappedHeader{Header: w.Header()},
			},
			browseTemplateContext: listing,
		}

		err = fsrv.makeBrowseTemplate(tplCtx)
		if err != nil {
			return fmt.Errorf("parsing browse template: %v", err)
		}

		if buf, err = fsrv.browseWriteHTML(tplCtx); err != nil {
			return caddyhttp.Error(http.StatusInternalServerError, err)
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
	}

	_, _ = buf.WriteTo(w)

	return nil
}

func (fsrv *FileServer) loadDirectoryContents(dir *os.File, root, urlPath string, repl *caddy.Replacer) (browseTemplateContext, error) {
	files, err := dir.Readdir(-1)
	if err != nil {
		return browseTemplateContext{}, err
	}

	// user can presumably browse "up" to parent folder if path is longer than "/"
	canGoUp := len(urlPath) > 1

	return fsrv.directoryListing(files, canGoUp, root, urlPath, repl), nil
}

// browseApplyQueryParams applies query parameters to the listing.
// It mutates the listing and may set cookies.
func (fsrv *FileServer) browseApplyQueryParams(w http.ResponseWriter, r *http.Request, listing *browseTemplateContext) {
	sortParam := r.URL.Query().Get("sort")
	orderParam := r.URL.Query().Get("order")
	limitParam := r.URL.Query().Get("limit")
	offsetParam := r.URL.Query().Get("offset")

	// first figure out what to sort by
	switch sortParam {
	case "":
		sortParam = sortByNameDirFirst
		if sortCookie, sortErr := r.Cookie("sort"); sortErr == nil {
			sortParam = sortCookie.Value
		}
	case sortByName, sortByNameDirFirst, sortBySize, sortByTime:
		http.SetCookie(w, &http.Cookie{Name: "sort", Value: sortParam, Secure: r.TLS != nil})
	}

	// then figure out the order
	switch orderParam {
	case "":
		orderParam = "asc"
		if orderCookie, orderErr := r.Cookie("order"); orderErr == nil {
			orderParam = orderCookie.Value
		}
	case "asc", "desc":
		http.SetCookie(w, &http.Cookie{Name: "order", Value: orderParam, Secure: r.TLS != nil})
	}

	// finally, apply the sorting and limiting
	listing.applySortAndLimit(sortParam, orderParam, limitParam, offsetParam)
}

// makeBrowseTemplate creates the template to be used for directory listings.
func (fsrv *FileServer) makeBrowseTemplate(tplCtx *templateContext) error {
	var tpl *template.Template
	var err error

	if fsrv.Browse.TemplateFile != "" {
		tpl = tplCtx.NewTemplate(path.Base(fsrv.Browse.TemplateFile))
		tpl, err = tpl.ParseFiles(fsrv.Browse.TemplateFile)
		if err != nil {
			return fmt.Errorf("parsing browse template file: %v", err)
		}
	} else {
		tpl = tplCtx.NewTemplate("default_listing")
		tpl, err = tpl.Parse(defaultBrowseTemplate)
		if err != nil {
			return fmt.Errorf("parsing default browse template: %v", err)
		}
	}

	fsrv.Browse.template = tpl

	return nil
}

func (fsrv *FileServer) browseWriteJSON(listing browseTemplateContext) (*bytes.Buffer, error) {
	buf := bufPool.Get().(*bytes.Buffer)
	defer bufPool.Put(buf)
	err := json.NewEncoder(buf).Encode(listing.Items)
	return buf, err
}

func (fsrv *FileServer) browseWriteHTML(tplCtx *templateContext) (*bytes.Buffer, error) {
	buf := bufPool.Get().(*bytes.Buffer)
	defer bufPool.Put(buf)
	err := fsrv.Browse.template.Execute(buf, tplCtx)
	return buf, err
}

// isSymlink return true if f is a symbolic link
func isSymlink(f os.FileInfo) bool {
	return f.Mode()&os.ModeSymlink != 0
}

// isSymlinkTargetDir returns true if f's symbolic link target
// is a directory.
func isSymlinkTargetDir(f os.FileInfo, root, urlPath string) bool {
	if !isSymlink(f) {
		return false
	}
	target := sanitizedPathJoin(root, path.Join(urlPath, f.Name()))
	targetInfo, err := os.Stat(target)
	if err != nil {
		return false
	}
	return targetInfo.IsDir()
}

// templateContext powers the context used when evaluating the browse template.
// It combines browse-specific features with the standard templates handler
// features.
type templateContext struct {
	templates.TemplateContext
	browseTemplateContext
}
<|endoftext|>


<commit_before>package main

import (
	"eaciit/gdrj/model"
	"eaciit/gdrj/modules"
	"os"

	"github.com/eaciit/dbox"
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
	"strings"
	"time"
)

var conn dbox.IConnection
var count int

func setinitialconnection() {
	var err error
	conn, err = modules.GetDboxIConnection("db_godrej")

	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}

	err = gdrj.SetDb(conn)
	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}
}

var (
	shs       = toolkit.M{}
	pcs       = toolkit.M{}
	ccs       = toolkit.M{}
	ledgers   = toolkit.M{}
	prods     = toolkit.M{}
	custs     = toolkit.M{}
	vdistskus = toolkit.M{}
	mapskuids = toolkit.M{}
)

func getCursor(obj orm.IModel) dbox.ICursor {
	c, e := gdrj.Find(obj, nil, nil)
	if e != nil {
		return nil
	}
	return c
}

func prepMaster() {
	pc := new(gdrj.ProfitCenter)
	cc := new(gdrj.CostCenter)
	prod := new(gdrj.Product)
	ledger := new(gdrj.LedgerMaster)

	// mapskuid := new(gdrj.MappingInventory)
	// cmskuid := getCursor(mapskuid)
	// defer cmskuid.Close()
	var e error
	// for e = cmskuid.Fetch(mapskuid, 1, false); e == nil; {
	// 	mapskuids.Set(mapskuid.SKUID_VDIST, mapskuid.ID)
	// 	mapskuid = new(gdrj.MappingInventory)
	// 	e = cmskuid.Fetch(mapskuid, 1, false)
	// }

	cpc := getCursor(pc)
	defer cpc.Close()
	for e = cpc.Fetch(pc, 1, false); e == nil; {
		pcs.Set(pc.ID, pc)
		pc = new(gdrj.ProfitCenter)
		e = cpc.Fetch(pc, 1, false)
	}

	ccc := getCursor(cc)
	defer ccc.Close()
	for e = ccc.Fetch(cc, 1, false); e == nil; {
		ccs.Set(cc.ID, cc)
		cc = new(gdrj.CostCenter)
		e = ccc.Fetch(cc, 1, false)
	}

	cprod := getCursor(prod)
	defer cprod.Close()
	for e = cprod.Fetch(prod, 1, false); e == nil; {
		prods.Set(prod.ID, prod)
		prod = new(gdrj.Product)
		e = cprod.Fetch(prod, 1, false)
	}

	cledger := getCursor(ledger)
	defer cledger.Close()
	for e = cledger.Fetch(ledger, 1, false); e == nil; {
		ledgers.Set(ledger.ID, ledger)
		ledger = new(gdrj.LedgerMaster)
		e = cledger.Fetch(ledger, 1, false)
	}

	cust := new(gdrj.Customer)
	ccust := getCursor(cust)
	defer ccust.Close()
	for e = ccust.Fetch(cust, 1, false); e == nil; {
		custs.Set(cust.ID, cust)
		cust = new(gdrj.Customer)
		e = ccust.Fetch(cust, 1, false)
	}

	sku := new(gdrj.MappingInventory)
	cskus := getCursor(sku)
	defer cskus.Close()
	for e = cskus.Fetch(sku, 1, false); e == nil; {
		vdistskus.Set(sku.SKUID_VDIST, sku.ID)
		sku = new(gdrj.MappingInventory)
		e = cskus.Fetch(sku, 1, false)
	}

	sh := new(gdrj.SalesHeader)
	cshs := getCursor(sh)
	defer cshs.Close()
	for e = cshs.Fetch(sh, 1, false); e == nil; {
		shs.Set(sh.ID, sh)
		sh = new(gdrj.SalesHeader)
		e = cshs.Fetch(sh, 1, false)
	}
}

func main() {
	setinitialconnection()
	defer gdrj.CloseDb()

	toolkit.Println("Reading Master")
	prepMaster()

	toolkit.Println("START...")

	//for i, src := range arrstring {
	//dbf := dbox.Contains("src", src)
	crx, err := gdrj.Find(new(gdrj.SalesDetail),
		//dbox.Eq("salesheaderid","FK/NAS/14002178"),
		nil,
		toolkit.M{}.Set("take", 10000))

	if err != nil {
		toolkit.Println("Error Found : ", err.Error())
		os.Exit(1)
	}
	defer crx.Close()

	lastSalesLine := toolkit.M{}
	count = crx.Count()
	step := count / 100
	i := 0
	t0 := time.Now()
	for {
		i++
		sd := new(gdrj.SalesDetail)
		e := crx.Fetch(sd, 1, false)
		if e != nil {
			break
		}

		st := new(gdrj.SalesTrx)
		st.SalesHeaderID = sd.SalesHeaderID
		if lastSalesLine.Has(sd.SalesHeaderID) {
			lastLineNo := lastSalesLine.GetInt(sd.SalesHeaderID) + 1
			st.LineNo = lastLineNo
			lastSalesLine.Set(sd.SalesHeaderID, lastLineNo)
		} else {
			st.LineNo = 1
			lastSalesLine.Set(sd.SalesHeaderID, 1)
		}

		if shs.Has(sd.SalesHeaderID) {
			sho := shs.Get(sd.SalesHeaderID).(*gdrj.SalesHeader)
			sho.OutletID = strings.ToUpper(sho.OutletID)

			if sho.SalesDiscountAmount != 0 && sho.SalesGrossAmount != 0 {
				st.DiscountAmount = sd.SalesGrossAmount * sho.SalesDiscountAmount / sho.SalesGrossAmount
			}

			if sho.SalesTaxAmount != 0 && sho.SalesGrossAmount != 0 {
				st.TaxAmount = sd.SalesGrossAmount * sho.SalesTaxAmount / sho.SalesGrossAmount
			}

			st.OutletID = sho.BranchID + sho.OutletID
			st.Date = sho.Date
			st.HeaderValid = true

		} else {
			st.HeaderValid = false
		}

		st.SKUID_VDIST = sd.SKUID_VDIST
		if vdistskus.Has(sd.SKUID_VDIST) {
			st.SKUID = toolkit.ToString(vdistskus[sd.SKUID_VDIST])
		} else {
			st.SKUID = "not found"
		}

		st.SalesQty = float64(sd.SalesQty)
		st.GrossAmount = sd.SalesGrossAmount
		st.NetAmount = sd.SalesNetAmount

		if prods.Has(st.SKUID) {
			st.ProductValid = true
			st.Product = prods.Get(st.SKUID).(*gdrj.Product)
		} else {
			st.ProductValid = false
		}

		if custs.Has(st.OutletID) {
			st.CustomerValid = true
			st.Customer = custs.Get(st.OutletID).(*gdrj.Customer)
			if st.Customer.ChannelID == "I1" {
				st.CustomerValid = false
			}
		} else {
			st.CustomerValid = false
		}

		if st.ProductValid && st.CustomerValid {
			pcid := st.Customer.BranchID + st.Product.BrandCategoryID
			if pcs.Has(pcid) {
				st.PCValid = true
				st.PC = pcs.Get(pcid).(*gdrj.ProfitCenter)
			} else {
				st.PCValid = false
			}
		} else {
			st.PCValid = false
		}

		st.Src = "VDIST"

		gdrj.Save(st)
		if i > step {
			toolkit.Printfn("Processing %d of %d %s in %s",
				i, count, sd.SalesHeaderID,
				time.Since(t0).String())
			step += count / 100
		}
	}

	toolkit.Printfn("Processing done in %s",
		time.Since(t0).String())
}
<commit_msg>update<commit_after>package main

import (
	"eaciit/gdrj/model"
	"eaciit/gdrj/modules"
	"os"

	"github.com/eaciit/dbox"
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
	"strings"
	"time"
)

var conn dbox.IConnection
var count int

func setinitialconnection() {
	var err error
	conn, err = modules.GetDboxIConnection("db_godrej")

	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}

	err = gdrj.SetDb(conn)
	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}
}

var (
	shs       = toolkit.M{}
	pcs       = toolkit.M{}
	ccs       = toolkit.M{}
	ledgers   = toolkit.M{}
	prods     = toolkit.M{}
	custs     = toolkit.M{}
	vdistskus = toolkit.M{}
	mapskuids = toolkit.M{}
)

func getCursor(obj orm.IModel) dbox.ICursor {
	c, e := gdrj.Find(obj, nil, nil)
	if e != nil {
		return nil
	}
	return c
}

func prepMaster() {
	pc := new(gdrj.ProfitCenter)
	cc := new(gdrj.CostCenter)
	prod := new(gdrj.Product)
	ledger := new(gdrj.LedgerMaster)

	// mapskuid := new(gdrj.MappingInventory)
	// cmskuid := getCursor(mapskuid)
	// defer cmskuid.Close()
	var e error
	// for e = cmskuid.Fetch(mapskuid, 1, false); e == nil; {
	// 	mapskuids.Set(mapskuid.SKUID_VDIST, mapskuid.ID)
	// 	mapskuid = new(gdrj.MappingInventory)
	// 	e = cmskuid.Fetch(mapskuid, 1, false)
	// }

	cpc := getCursor(pc)
	defer cpc.Close()
	for e = cpc.Fetch(pc, 1, false); e == nil; {
		pcs.Set(pc.ID, pc)
		pc = new(gdrj.ProfitCenter)
		e = cpc.Fetch(pc, 1, false)
	}

	ccc := getCursor(cc)
	defer ccc.Close()
	for e = ccc.Fetch(cc, 1, false); e == nil; {
		ccs.Set(cc.ID, cc)
		cc = new(gdrj.CostCenter)
		e = ccc.Fetch(cc, 1, false)
	}

	cprod := getCursor(prod)
	defer cprod.Close()
	for e = cprod.Fetch(prod, 1, false); e == nil; {
		prods.Set(prod.ID, prod)
		prod = new(gdrj.Product)
		e = cprod.Fetch(prod, 1, false)
	}

	cledger := getCursor(ledger)
	defer cledger.Close()
	for e = cledger.Fetch(ledger, 1, false); e == nil; {
		ledgers.Set(ledger.ID, ledger)
		ledger = new(gdrj.LedgerMaster)
		e = cledger.Fetch(ledger, 1, false)
	}

	cust := new(gdrj.Customer)
	ccust := getCursor(cust)
	defer ccust.Close()
	for e = ccust.Fetch(cust, 1, false); e == nil; {
		custs.Set(cust.ID, cust)
		cust = new(gdrj.Customer)
		e = ccust.Fetch(cust, 1, false)
	}

	sku := new(gdrj.MappingInventory)
	cskus := getCursor(sku)
	defer cskus.Close()
	for e = cskus.Fetch(sku, 1, false); e == nil; {
		vdistskus.Set(sku.SKUID_VDIST, sku.ID)
		sku = new(gdrj.MappingInventory)
		e = cskus.Fetch(sku, 1, false)
	}

	sh := new(gdrj.SalesHeader)
	cshs := getCursor(sh)
	defer cshs.Close()
	for e = cshs.Fetch(sh, 1, false); e == nil; {
		shs.Set(sh.ID, sh)
		sh = new(gdrj.SalesHeader)
		e = cshs.Fetch(sh, 1, false)
	}
}

func main() {
	setinitialconnection()
	defer gdrj.CloseDb()

	toolkit.Println("Reading Master")
	prepMaster()

	toolkit.Println("START...")

	//for i, src := range arrstring {
	//dbf := dbox.Contains("src", src)
	crx, err := gdrj.Find(new(gdrj.SalesDetail),
		nil,
		toolkit.M{})

	if err != nil {
		toolkit.Println("Error Found : ", err.Error())
		os.Exit(1)
	}
	defer crx.Close()

	lastSalesLine := toolkit.M{}
	count = crx.Count()
	step := count / 100
	i := 0
	t0 := time.Now()
	for {
		i++
		sd := new(gdrj.SalesDetail)
		e := crx.Fetch(sd, 1, false)
		if e != nil {
			break
		}

		st := new(gdrj.SalesTrx)
		st.SalesHeaderID = sd.SalesHeaderID
		if lastSalesLine.Has(sd.SalesHeaderID) {
			lastLineNo := lastSalesLine.GetInt(sd.SalesHeaderID) + 1
			st.LineNo = lastLineNo
			lastSalesLine.Set(sd.SalesHeaderID, lastLineNo)
		} else {
			st.LineNo = 1
			lastSalesLine.Set(sd.SalesHeaderID, 1)
		}

		if shs.Has(sd.SalesHeaderID) {
			sho := shs.Get(sd.SalesHeaderID).(*gdrj.SalesHeader)
			sho.OutletID = strings.ToUpper(sho.OutletID)

			if sho.SalesDiscountAmount != 0 && sho.SalesGrossAmount != 0 {
				st.DiscountAmount = sd.SalesGrossAmount * sho.SalesDiscountAmount / sho.SalesGrossAmount
			}

			if sho.SalesTaxAmount != 0 && sho.SalesGrossAmount != 0 {
				st.TaxAmount = sd.SalesGrossAmount * sho.SalesTaxAmount / sho.SalesGrossAmount
			}

			st.OutletID = sho.BranchID + sho.OutletID
			st.Date = sho.Date
			st.HeaderValid = true

		} else {
			st.HeaderValid = false
		}

		st.SKUID_VDIST = sd.SKUID_VDIST
		if vdistskus.Has(sd.SKUID_VDIST) {
			st.SKUID = toolkit.ToString(vdistskus[sd.SKUID_VDIST])
		} else {
			st.SKUID = "not found"
		}

		st.SalesQty = float64(sd.SalesQty)
		st.GrossAmount = sd.SalesGrossAmount
		st.NetAmount = sd.SalesNetAmount

		if prods.Has(st.SKUID) {
			st.ProductValid = true
			st.Product = prods.Get(st.SKUID).(*gdrj.Product)
		} else {
			st.ProductValid = false
		}

		if custs.Has(st.OutletID) {
			st.CustomerValid = true
			st.Customer = custs.Get(st.OutletID).(*gdrj.Customer)
			if st.Customer.ChannelID == "I1" {
				st.CustomerValid = false
			}
		} else {
			st.CustomerValid = false
		}

		if st.ProductValid && st.CustomerValid {
			pcid := st.Customer.BranchID + st.Product.BrandCategoryID
			if pcs.Has(pcid) {
				st.PCValid = true
				st.PC = pcs.Get(pcid).(*gdrj.ProfitCenter)
			} else {
				st.PCValid = false
			}
		} else {
			st.PCValid = false
		}

		st.Src = "VDIST"

		gdrj.Save(st)
		if i > step {
			toolkit.Printfn("Processing %d of %d %s in %s",
				i, count, sd.SalesHeaderID,
				time.Since(t0).String())
			step += count / 100
		}
	}

	toolkit.Printfn("Processing done in %s",
		time.Since(t0).String())
}
<|endoftext|>


<commit_before>package dnsimple

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

// DomainsService handles communication with the domain related
// methods of the DNSimple API.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/
type DomainsService struct {
	client *Client
}

// Date custom type
type Date struct {time.Time}

type Domain struct {
	Id             int        `json:"id,omitempty"`
	UserId         int        `json:"user_id,omitempty"`
	RegistrantId   int        `json:"registrant_id,omitempty"`
	Name           string     `json:"name,omitempty"`
	UnicodeName    string     `json:"unicode_name,omitempty"`
	Token          string     `json:"token,omitempty"`
	State          string     `json:"state,omitempty"`
	Language       string     `json:"language,omitempty"`
	Lockable       bool       `json:"lockable,omitempty"`
	AutoRenew      bool       `json:"auto_renew,omitempty"`
	WhoisProtected bool       `json:"whois_protected,omitempty"`
	RecordCount    int        `json:"record_count,omitempty"`
	ServiceCount   int        `json:"service_count,omitempty"`
	ExpiresOn      *Date `json:"expires_on,omitempty"`
	CreatedAt      *time.Time `json:"created_at,omitempty"`
	UpdatedAt      *time.Time `json:"updated_at,omitempty"`
}

// UnmarshalJSON handles the custom date formats
func (d *Date) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err != nil {
		return fmt.Errorf("date should be a string, got %s", data)
	}
	t, err := time.Parse("2006-01-02", s)
	if err != nil {
		return fmt.Errorf("invalid date: %v", err)
	}
	d.Time = t
	return nil
}

type domainWrapper struct {
	Domain Domain `json:"domain"`
}

// domainRequest represents a generic wrapper for a domain request,
// when domainWrapper cannot be used because of type constraint on Domain.
type domainRequest struct {
	Domain interface{} `json:"domain"`
}

func domainIdentifier(value interface{}) string {
	switch value := value.(type) {
	case string:
		return value
	case int:
		return fmt.Sprintf("%d", value)
	}
	return ""
}

// domainPath generates the resource path for given domain.
func domainPath(domain interface{}) string {
	if domain != nil {
		return fmt.Sprintf("domains/%s", domainIdentifier(domain))
	}
	return "domains"
}

// List the domains.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#list
func (s *DomainsService) List() ([]Domain, *Response, error) {
	path := domainPath(nil)
	returnedDomains := []domainWrapper{}

	res, err := s.client.get(path, &returnedDomains)
	if err != nil {
		fmt.Printf("get errror %v\n", err)
		return []Domain{}, res, err
	}

	domains := []Domain{}
	for _, domain := range returnedDomains {
		domains = append(domains, domain.Domain)
	}

	return domains, res, nil
}

// Create a new domain.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#create
func (s *DomainsService) Create(domainAttributes Domain) (Domain, *Response, error) {
	path := domainPath(nil)
	wrappedDomain := domainWrapper{Domain: domainAttributes}
	returnedDomain := domainWrapper{}

	res, err := s.client.post(path, wrappedDomain, &returnedDomain)
	if err != nil {
		return Domain{}, res, err
	}

	return returnedDomain.Domain, res, nil
}

// Get fetches a domain.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#get
func (s *DomainsService) Get(domain interface{}) (Domain, *Response, error) {
	path := domainPath(domain)
	returnedDomain := domainWrapper{}

	res, err := s.client.get(path, &returnedDomain)
	if err != nil {
		return Domain{}, res, err
	}

	return returnedDomain.Domain, res, nil
}

// Delete a domain.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#delete
func (s *DomainsService) Delete(domain interface{}) (*Response, error) {
	path := domainPath(domain)

	return s.client.delete(path, nil)
}
<commit_msg>Removed the debug line<commit_after>package dnsimple

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

// DomainsService handles communication with the domain related
// methods of the DNSimple API.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/
type DomainsService struct {
	client *Client
}

// Date custom type
type Date struct {time.Time}

type Domain struct {
	Id             int        `json:"id,omitempty"`
	UserId         int        `json:"user_id,omitempty"`
	RegistrantId   int        `json:"registrant_id,omitempty"`
	Name           string     `json:"name,omitempty"`
	UnicodeName    string     `json:"unicode_name,omitempty"`
	Token          string     `json:"token,omitempty"`
	State          string     `json:"state,omitempty"`
	Language       string     `json:"language,omitempty"`
	Lockable       bool       `json:"lockable,omitempty"`
	AutoRenew      bool       `json:"auto_renew,omitempty"`
	WhoisProtected bool       `json:"whois_protected,omitempty"`
	RecordCount    int        `json:"record_count,omitempty"`
	ServiceCount   int        `json:"service_count,omitempty"`
	ExpiresOn      *Date `json:"expires_on,omitempty"`
	CreatedAt      *time.Time `json:"created_at,omitempty"`
	UpdatedAt      *time.Time `json:"updated_at,omitempty"`
}

// UnmarshalJSON handles the custom date formats
func (d *Date) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err != nil {
		return fmt.Errorf("date should be a string, got %s", data)
	}
	t, err := time.Parse("2006-01-02", s)
	if err != nil {
		return fmt.Errorf("invalid date: %v", err)
	}
	d.Time = t
	return nil
}

type domainWrapper struct {
	Domain Domain `json:"domain"`
}

// domainRequest represents a generic wrapper for a domain request,
// when domainWrapper cannot be used because of type constraint on Domain.
type domainRequest struct {
	Domain interface{} `json:"domain"`
}

func domainIdentifier(value interface{}) string {
	switch value := value.(type) {
	case string:
		return value
	case int:
		return fmt.Sprintf("%d", value)
	}
	return ""
}

// domainPath generates the resource path for given domain.
func domainPath(domain interface{}) string {
	if domain != nil {
		return fmt.Sprintf("domains/%s", domainIdentifier(domain))
	}
	return "domains"
}

// List the domains.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#list
func (s *DomainsService) List() ([]Domain, *Response, error) {
	path := domainPath(nil)
	returnedDomains := []domainWrapper{}

	res, err := s.client.get(path, &returnedDomains)
	if err != nil {
		return []Domain{}, res, err
	}

	domains := []Domain{}
	for _, domain := range returnedDomains {
		domains = append(domains, domain.Domain)
	}

	return domains, res, nil
}

// Create a new domain.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#create
func (s *DomainsService) Create(domainAttributes Domain) (Domain, *Response, error) {
	path := domainPath(nil)
	wrappedDomain := domainWrapper{Domain: domainAttributes}
	returnedDomain := domainWrapper{}

	res, err := s.client.post(path, wrappedDomain, &returnedDomain)
	if err != nil {
		return Domain{}, res, err
	}

	return returnedDomain.Domain, res, nil
}

// Get fetches a domain.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#get
func (s *DomainsService) Get(domain interface{}) (Domain, *Response, error) {
	path := domainPath(domain)
	returnedDomain := domainWrapper{}

	res, err := s.client.get(path, &returnedDomain)
	if err != nil {
		return Domain{}, res, err
	}

	return returnedDomain.Domain, res, nil
}

// Delete a domain.
//
// DNSimple API docs: http://developer.dnsimple.com/domains/#delete
func (s *DomainsService) Delete(domain interface{}) (*Response, error) {
	path := domainPath(domain)

	return s.client.delete(path, nil)
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"

	"github.com/wellington/wellington"
)

// Sometimes circleci detects races in these tests. This may prevent it
var wtCmdMu sync.RWMutex

func init() {
	s := new(string)
	wtCmdMu.Lock()
	wtCmd.PersistentFlags().StringVarP(s, "test", "t", "", "dummy for testing")
	wtCmdMu.Unlock()

}

func resetFlags() {
	wtCmdMu.Lock()
	defer wtCmdMu.Unlock()
	wtCmd.ResetFlags()
}

func TestHTTP(t *testing.T) {
	wtCmd.SetArgs([]string{
		"serve",
	})

	// No way to shut this down
	go func() {
		wtCmdMu.RLock()
		defer wtCmdMu.RUnlock()
		main()
	}()

	req, err := http.NewRequest("POST", "http://localhost:12345",
		bytes.NewBufferString(`div { p { color: red; } }`))

	if err != nil {
		t.Fatal(err)
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	if resp.Body == nil {
		t.Fatal("no response")
	}
	bs, _ := ioutil.ReadAll(resp.Body)

	var r wellington.Response
	err = json.Unmarshal(bs, &r)
	if err != nil {
		t.Fatal(err)
	}

	e := "/* line 1, stdin */\ndiv p {\n  color: red; }\n"
	if e != r.Contents {
		t.Errorf("got:\n%s\nwanted:\n%s", r.Contents, e)
	}
}

func TestStdin_import(t *testing.T) {
	resetFlags()

	oldOut := os.Stdout

	r, w, _ := os.Pipe()
	os.Stdout = w
	pwd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	includeDir := filepath.Join(pwd, "..", "test", "sass")
	wtCmd.SetArgs([]string{
		"-p", includeDir,
		"compile", "../test/sass/import.scss"})
	main()

	outC := make(chan string)

	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf.String()
	}()

	w.Close()
	os.Stdout = oldOut

	out := <-outC
	out = strings.Replace(out, includeDir, "", 1)
	e := `div {
  background: #00FF00;
  font-size: 10pt; }
`

	if !bytes.Contains([]byte(out), []byte(e)) {
		t.Errorf("got:\n%s\nwanted:\n%s", out, e)
	}

}

func TestStdin_sprite(t *testing.T) {
	resetFlags()

	oldStd := os.Stdin
	var oldOut *os.File
	oldOut = os.Stdout

	r, w, _ := os.Pipe()
	os.Stdout = w
	wtCmd.SetArgs([]string{
		"--dir", "../test/img",
		"--gen", "../test/img/build",
		"compile"})

	var err error
	os.Stdin, err = os.Open("../test/sass/sprite.scss")
	if err != nil {
		t.Fatal(err)
	}
	main()

	outC := make(chan string)

	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf.String()
	}()

	w.Close()
	os.Stdin = oldStd
	os.Stdout = oldOut

	out := <-outC

	e := `div {
  height: 139px;
  width: 96px;
  background: url("../test/img/build/f0a220.png") 0px 0px; }
`

	if !bytes.Contains([]byte(out), []byte(e)) {
		t.Errorf("got:\n%s\nwanted:\n%s", out, e)
	}

}

func TestFile(t *testing.T) {
	// TODO: Tests for file importing here
}

func TestFile_comprehensive(t *testing.T) {
	resetFlags()

	oldStd := os.Stdin
	oldOut := os.Stdout

	r, w, _ := os.Pipe()
	os.Stdout = w
	wtCmd.SetArgs([]string{
		"--dir", "../test/img",
		"--gen", "../test/img/build",
		"--comment=false",
		"compile", "../test/comprehensive/compreh.scss"})
	main()

	outC := make(chan bytes.Buffer)

	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf
	}()

	w.Close()
	os.Stdin = oldStd
	os.Stdout = oldOut

	out := <-outC

	e, err := ioutil.ReadFile("../test/comprehensive/expected.css")
	if err != nil {
		t.Fatal(err)
	}

	if bytes.Compare(out.Bytes(), e) != 0 {
		t.Errorf("got:\n%s\nwanted:\n%s", out.String(), string(e))
	}

}

func TestWatch_comprehensive(t *testing.T) {
	os.RemoveAll("../test/build/testwatch")
	resetFlags()

	wtCmd.SetArgs([]string{
		"--dir", "../test/img",
		"-b", "../test/build/testwatch",
		"--gen", "../test/build/testwatch/img",
		"--comment=false",
		"watch", "../test/comprehensive/compreh.scss",
	})
	main()
	_, err := os.Stat("../test/build/testwatch/compreh.css")
	if err != nil {
		t.Fatal(err)
	}

	_, err = os.Stat("../test/build/testwatch/img/5905b8.png")
	if err != nil {
		t.Fatal(err)
	}
}
<commit_msg>main() never returns need to fix this, later<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"

	"github.com/wellington/wellington"
)

// Sometimes circleci detects races in these tests. This may prevent it
var wtCmdMu sync.RWMutex

func init() {
	s := new(string)
	wtCmdMu.Lock()
	wtCmd.PersistentFlags().StringVarP(s, "test", "t", "", "dummy for testing")
	wtCmdMu.Unlock()

}

func resetFlags() {
	wtCmdMu.Lock()
	defer wtCmdMu.Unlock()
	wtCmd.ResetFlags()
}

func TestHTTP(t *testing.T) {
	wtCmd.SetArgs([]string{
		"serve",
	})

	// No way to shut this down
	go func() {
		main()
	}()

	req, err := http.NewRequest("POST", "http://localhost:12345",
		bytes.NewBufferString(`div { p { color: red; } }`))

	if err != nil {
		t.Fatal(err)
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	if resp.Body == nil {
		t.Fatal("no response")
	}
	bs, _ := ioutil.ReadAll(resp.Body)

	var r wellington.Response
	err = json.Unmarshal(bs, &r)
	if err != nil {
		t.Fatal(err)
	}

	e := "/* line 1, stdin */\ndiv p {\n  color: red; }\n"
	if e != r.Contents {
		t.Errorf("got:\n%s\nwanted:\n%s", r.Contents, e)
	}
}

func TestStdin_import(t *testing.T) {
	resetFlags()

	oldOut := os.Stdout

	r, w, _ := os.Pipe()
	os.Stdout = w
	pwd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	includeDir := filepath.Join(pwd, "..", "test", "sass")
	wtCmd.SetArgs([]string{
		"-p", includeDir,
		"compile", "../test/sass/import.scss"})
	main()

	outC := make(chan string)

	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf.String()
	}()

	w.Close()
	os.Stdout = oldOut

	out := <-outC
	out = strings.Replace(out, includeDir, "", 1)
	e := `div {
  background: #00FF00;
  font-size: 10pt; }
`

	if !bytes.Contains([]byte(out), []byte(e)) {
		t.Errorf("got:\n%s\nwanted:\n%s", out, e)
	}

}

func TestStdin_sprite(t *testing.T) {
	resetFlags()

	oldStd := os.Stdin
	var oldOut *os.File
	oldOut = os.Stdout

	r, w, _ := os.Pipe()
	os.Stdout = w
	wtCmd.SetArgs([]string{
		"--dir", "../test/img",
		"--gen", "../test/img/build",
		"compile"})

	var err error
	os.Stdin, err = os.Open("../test/sass/sprite.scss")
	if err != nil {
		t.Fatal(err)
	}
	main()

	outC := make(chan string)

	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf.String()
	}()

	w.Close()
	os.Stdin = oldStd
	os.Stdout = oldOut

	out := <-outC

	e := `div {
  height: 139px;
  width: 96px;
  background: url("../test/img/build/f0a220.png") 0px 0px; }
`

	if !bytes.Contains([]byte(out), []byte(e)) {
		t.Errorf("got:\n%s\nwanted:\n%s", out, e)
	}

}

func TestFile(t *testing.T) {
	// TODO: Tests for file importing here
}

func TestFile_comprehensive(t *testing.T) {
	resetFlags()

	oldStd := os.Stdin
	oldOut := os.Stdout

	r, w, _ := os.Pipe()
	os.Stdout = w
	wtCmd.SetArgs([]string{
		"--dir", "../test/img",
		"--gen", "../test/img/build",
		"--comment=false",
		"compile", "../test/comprehensive/compreh.scss"})
	main()

	outC := make(chan bytes.Buffer)

	go func() {
		var buf bytes.Buffer
		io.Copy(&buf, r)
		outC <- buf
	}()

	w.Close()
	os.Stdin = oldStd
	os.Stdout = oldOut

	out := <-outC

	e, err := ioutil.ReadFile("../test/comprehensive/expected.css")
	if err != nil {
		t.Fatal(err)
	}

	if bytes.Compare(out.Bytes(), e) != 0 {
		t.Errorf("got:\n%s\nwanted:\n%s", out.String(), string(e))
	}

}

func TestWatch_comprehensive(t *testing.T) {
	os.RemoveAll("../test/build/testwatch")
	resetFlags()

	wtCmd.SetArgs([]string{
		"--dir", "../test/img",
		"-b", "../test/build/testwatch",
		"--gen", "../test/build/testwatch/img",
		"--comment=false",
		"watch", "../test/comprehensive/compreh.scss",
	})
	main()
	_, err := os.Stat("../test/build/testwatch/compreh.css")
	if err != nil {
		t.Fatal(err)
	}

	_, err = os.Stat("../test/build/testwatch/img/5905b8.png")
	if err != nil {
		t.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func (s *SlackAPI) ChatDelete(channel string, timestamp string) ChannelEvent {
	var response ChannelEvent
	s.GetRequest(&response,
		"chat.delete",
		"token",
		"channel="+channel,
		"ts="+timestamp)
	return response
}

func (s *SlackAPI) ChatDeleteVerbose(channel string, timestamp string) {
	response := s.ChatDelete(channel, timestamp)
	s.PrintJson(response)
}

func (s *SlackAPI) ChatPostMessage(channel string, message string) Message {
	var response Message
	s.GetRequest(&response,
		"chat.postMessage",
		"token",
		"channel="+channel,
		"text="+message,
		"as_user=true",
		"link_names=1")
	return response
}

func (s *SlackAPI) ChatPostMessageVerbose(channel string, message string) {
	response := s.ChatPostMessage(channel, message)
	s.PrintJson(response)
}

func (s *SlackAPI) ChatSession() {
	var command string
	var parts []string
	var channel string = "unknown"
	reader := bufio.NewReader(os.Stdin)

	for {
		fmt.Printf("slack:%s> ", channel)
		message, err := reader.ReadString('\n')

		if err != nil {
			s.ReportError(err)
		}

		message = strings.TrimSpace(message)

		if message == ":exit" {
			// Close the chat session and exit the loop.
			fmt.Printf("Closing...")
			response := s.InstantMessagingClose(channel)
			fmt.Printf("\r")
			s.PrintInlineJson(response)
			fmt.Println("Closed")
			break
		} else if message[0] == ':' {
			// Execute a custom command with the message.
			parts = strings.SplitN(message, "\x20", 2)
			command = parts[0]
			message = parts[1]

			if command == ":open" {
				fmt.Printf("Opening session...")
				response := s.InstantMessagingOpen(message)
				fmt.Printf("\r")
				s.PrintInlineJson(response)

				if response.Ok == true {
					channel = response.Channel.Id
				}
			}
		} else {
			// Send the message to the remote service.
			fmt.Println(message)
		}
	}

	os.Exit(0)
}

func (s *SlackAPI) ChatUpdate(channel string, timestamp string, message string) Message {
	var response Message
	s.GetRequest(&response,
		"chat.update",
		"token",
		"channel="+channel,
		"text="+message,
		"ts="+timestamp,
		"link_names=1")
	return response
}

func (s *SlackAPI) ChatUpdateVerbose(channel string, timestamp string, message string) {
	response := s.ChatUpdate(channel, timestamp, message)
	s.PrintJson(response)
}
<commit_msg>Added validation for chat.session to send message<commit_after>package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func (s *SlackAPI) ChatDelete(channel string, timestamp string) ChannelEvent {
	var response ChannelEvent
	s.GetRequest(&response,
		"chat.delete",
		"token",
		"channel="+channel,
		"ts="+timestamp)
	return response
}

func (s *SlackAPI) ChatDeleteVerbose(channel string, timestamp string) {
	response := s.ChatDelete(channel, timestamp)
	s.PrintJson(response)
}

func (s *SlackAPI) ChatPostMessage(channel string, message string) Message {
	var response Message
	s.GetRequest(&response,
		"chat.postMessage",
		"token",
		"channel="+channel,
		"text="+message,
		"as_user=true",
		"link_names=1")
	return response
}

func (s *SlackAPI) ChatPostMessageVerbose(channel string, message string) {
	response := s.ChatPostMessage(channel, message)
	s.PrintJson(response)
}

func (s *SlackAPI) ChatSession() {
	var command string
	var parts []string
	var channel string = "unknown"
	var is_connected bool = false
	reader := bufio.NewReader(os.Stdin)

	for {
		fmt.Printf("slack:%s> ", channel)
		message, err := reader.ReadString('\n')

		if err != nil {
			s.ReportError(err)
		}

		message = strings.TrimSpace(message)

		if message == "" {
			// Do nothing on empty message.
		} else if message == ":exit" {
			// Close the chat session and exit the loop.
			if is_connected {
				fmt.Printf("Closing...")
				response := s.InstantMessagingClose(channel)
				fmt.Printf("\r")
				s.PrintInlineJson(response)
			}
			fmt.Println("Closed")
			break
		} else if message[0] == ':' {
			// Execute a custom command with the message.
			parts = strings.SplitN(message, "\x20", 2)
			command = parts[0]

			if len(parts) == 2 {
				message = parts[1]
			}

			if command == ":open" {
				fmt.Printf("Opening session...")
				response := s.InstantMessagingOpen(message)
				fmt.Printf("\r")
				s.PrintInlineJson(response)

				if response.Ok == true {
					channel = response.Channel.Id
					is_connected = response.Ok
				}
			}
		} else {
			// Send the message to the remote service.
			if is_connected {
				response := s.ChatPostMessage(channel, message)
				s.PrintInlineJson(response)
			} else {
				fmt.Println("{\"ok\":false,\"error\":\"not_connected\"}")
			}
		}
	}

	os.Exit(0)
}

func (s *SlackAPI) ChatUpdate(channel string, timestamp string, message string) Message {
	var response Message
	s.GetRequest(&response,
		"chat.update",
		"token",
		"channel="+channel,
		"text="+message,
		"ts="+timestamp,
		"link_names=1")
	return response
}

func (s *SlackAPI) ChatUpdateVerbose(channel string, timestamp string, message string) {
	response := s.ChatUpdate(channel, timestamp, message)
	s.PrintJson(response)
}
<|endoftext|>


<commit_before>package karate

type Chopper interface {
    Chop(needle int) (index int)
    Init(haystack []int)
}
<commit_msg>go fmt: replace spaces by tabs<commit_after>package karate

type Chopper interface {
	Chop(needle int) (index int)
	Init(haystack []int)
}
<|endoftext|>


<commit_before>// Package cmac implements AES-CMAC (RFC4493)
package cmac

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/subtle"
	"hash"
)

func shifted(x []byte) []byte {
	d := make([]byte, len(x))
	copy(d, x)
	for i := range d {
		if i > 0 {
			d[i-1] |= d[i] >> 7
		}
		d[i] <<= 1
	}
	return d
}

func padded(d []byte) []byte {
	p := make([]byte, aes.BlockSize)
	copy(p, d)
	p[len(d)] = 0x80
	return p
}

func gensubkey(c cipher.Block, l []byte, rb byte) []byte {
	sk := shifted(l)
	sk[len(sk)-1] ^= byte(subtle.ConstantTimeSelect(int(l[0]>>7), int(rb), 0))
	return sk
}

func gensubkeys(c cipher.Block) ([]byte, []byte) {
	l := make([]byte, c.BlockSize())
	c.Encrypt(l, l)
	k1 := gensubkey(c, l, 0x87)
	return k1, gensubkey(c, k1, 0x87)
}

type cmac struct {
	c  cipher.Block
	k1 []byte
	k2 []byte

	x []byte

	buf []byte
}

func newcmac(c cipher.Block) *cmac {
	k1, k2 := gensubkeys(c)
	m := &cmac{c: c, k1: k1, k2: k2}
	m.Reset()
	return m
}

func (m *cmac) block(b []byte) {
	y := make([]byte, m.c.BlockSize())
	for i := range y {
		y[i] = m.x[i] ^ b[i]
	}
	m.c.Encrypt(m.x, y)
}

func (m *cmac) Write(b []byte) (int, error) {
	d := append(m.buf, b...)

	for len(d) > m.c.BlockSize() {
		m.block(d[:m.c.BlockSize()])
		d = d[m.c.BlockSize():]
	}

	m.buf = d

	return len(b), nil
}

func (m *cmac) Sum(b []byte) []byte {
	last := make([]byte, m.c.BlockSize())

	if len(m.buf) > 0 && len(m.buf)%m.c.BlockSize() == 0 {
		for i := range last {
			last[i] = m.buf[i] ^ m.k1[i]
		}
	} else {
		copy(last, m.buf)
		last[len(m.buf)] = 0x80
		for i := range last {
			last[i] ^= m.k2[i]
		}
	}

	for i := range last {
		last[i] ^= m.x[i]
	}
	m.c.Encrypt(last, last)

	return append(b, last...)
}

func (m *cmac) Reset() {
	m.buf = nil
	m.x = make([]byte, m.c.BlockSize())
}

func (m *cmac) Size() int {
	return m.c.BlockSize()
}

func (m *cmac) BlockSize() int {
	return m.c.BlockSize()
}

// New returns a hash.Hash computing AES-CMAC.
func New(key []byte) hash.Hash {
	c, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	return NewWithCipher(c)
}

// NewWithCipher returns a hash.Hash computing CMAC using the given
// cipher.Block. The block cipher should have a block length of 16 bytes.
func NewWithCipher(c cipher.Block) hash.Hash {
	return newcmac(c)
}
<commit_msg>support 64-bit block size<commit_after>// Package cmac implements AES-CMAC (RFC4493)
package cmac

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/subtle"
	"hash"
)

const (
	_Rb128 = 0x87
	_Rb64  = 0x1b
)

func shifted(x []byte) []byte {
	d := make([]byte, len(x))
	copy(d, x)
	for i := range d {
		if i > 0 {
			d[i-1] |= d[i] >> 7
		}
		d[i] <<= 1
	}
	return d
}

func gensubkey(c cipher.Block, l []byte, rb byte) []byte {
	sk := shifted(l)
	sk[len(sk)-1] ^= byte(subtle.ConstantTimeSelect(int(l[0]>>7), int(rb), 0))
	return sk
}

func gensubkeys(c cipher.Block) ([]byte, []byte) {
	var rb byte

	switch c.BlockSize() {
	case 16:
		rb = _Rb128
	case 8:
		rb = _Rb64
	default:
		panic("cmac: invalid block size")

	}

	l := make([]byte, c.BlockSize())
	c.Encrypt(l, l)

	k1 := gensubkey(c, l, rb)
	return k1, gensubkey(c, k1, rb)
}

type cmac struct {
	c  cipher.Block
	k1 []byte
	k2 []byte

	x []byte

	buf []byte
}

func newcmac(c cipher.Block) *cmac {
	k1, k2 := gensubkeys(c)
	m := &cmac{c: c, k1: k1, k2: k2}
	m.Reset()
	return m
}

func (m *cmac) block(b []byte) {
	y := make([]byte, m.c.BlockSize())
	for i := range y {
		y[i] = m.x[i] ^ b[i]
	}
	m.c.Encrypt(m.x, y)
}

func (m *cmac) Write(b []byte) (int, error) {
	d := append(m.buf, b...)

	for len(d) > m.c.BlockSize() {
		m.block(d[:m.c.BlockSize()])
		d = d[m.c.BlockSize():]
	}

	m.buf = d

	return len(b), nil
}

func (m *cmac) Sum(b []byte) []byte {
	last := make([]byte, m.c.BlockSize())

	if len(m.buf) > 0 && len(m.buf)%m.c.BlockSize() == 0 {
		for i := range last {
			last[i] = m.buf[i] ^ m.k1[i]
		}
	} else {
		copy(last, m.buf)
		last[len(m.buf)] = 0x80
		for i := range last {
			last[i] ^= m.k2[i]
		}
	}

	for i := range last {
		last[i] ^= m.x[i]
	}
	m.c.Encrypt(last, last)

	return append(b, last...)
}

func (m *cmac) Reset() {
	m.buf = nil
	m.x = make([]byte, m.c.BlockSize())
}

func (m *cmac) Size() int {
	return m.c.BlockSize()
}

func (m *cmac) BlockSize() int {
	return m.c.BlockSize()
}

// New returns a hash.Hash computing AES-CMAC.
func New(key []byte) hash.Hash {
	c, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	return NewWithCipher(c)
}

// NewWithCipher returns a hash.Hash computing CMAC using the given
// cipher.Block. The block cipher should have a block length of 8 or 16 bytes.
func NewWithCipher(c cipher.Block) hash.Hash {
	return newcmac(c)
}
<|endoftext|>


<commit_before>package prompt

import (
	"fmt"
	"log"

	linenoise "github.com/GeertJohan/go.linenoise"
	"github.com/julienroland/usg"
	"github.com/ttacon/chalk"
)

type Input struct {
	Question           string
	Default            string
	MaximumNumberOfTry int
	ErrorMessage       func(string) string
	Validation         func(string) bool
}

func NewInput() *Input {
	input := new(Input)
	input.Validation = func(answer string) bool {
		return true
	}
	input.ErrorMessage = func(response string) string {
		return "You can't leave this field empty"
	}
	input.MaximumNumberOfTry = -1
	return input
}

func (input *Input) Run() (string, error) {
	response := ""
	nbOfTry := 0
	for {
		question := input.buildQuestion()
		userResponse, err := linenoise.Line(question)
		if err != nil {
			log.Fatal(err)
		}
		if len(input.Default) > 0 && len(userResponse) <= 0 {
			userResponse = input.Default
		}

		isValid := input.Validation(userResponse)
		if !isValid {
			if nbOfTry >= input.MaximumNumberOfTry && input.MaximumNumberOfTry != -1 {
				return "", fmt.Errorf("%s[%s]%s Number of maximun try reached %d %s\n", chalk.Red, usg.Get.CrossGraph, chalk.Yellow, nbOfTry, chalk.ResetColor)
			}
			fmt.Printf("%s[%s]%s %s %s\n", chalk.Red, usg.Get.CrossGraph, chalk.Yellow, input.ErrorMessage(userResponse), chalk.ResetColor)
			continue
		}

		nbOfTry++
		return userResponse, nil
	}

	return response, nil
}

func (input *Input) buildQuestion() string {
	hasDefaultValue := len(input.Default) > 0
	if hasDefaultValue {
		return fmt.Sprintf("%s[?]%s %s %s[%s]%s: ", chalk.Yellow, chalk.Green, input.Question, chalk.Yellow, input.Default, chalk.ResetColor)
	}
	return fmt.Sprintf("%s[?]%s %s%s: ", chalk.Yellow, chalk.Green, input.Question, chalk.ResetColor)
}
<commit_msg>Return error instead of logging a fatal<commit_after>package prompt

import (
	"fmt"

	linenoise "github.com/GeertJohan/go.linenoise"
	"github.com/julienroland/usg"
	"github.com/ttacon/chalk"
)

type Input struct {
	Question           string
	Default            string
	MaximumNumberOfTry int
	ErrorMessage       func(string) string
	Validation         func(string) bool
}

func NewInput() *Input {
	input := new(Input)
	input.Validation = func(answer string) bool {
		return true
	}
	input.ErrorMessage = func(response string) string {
		return "You can't leave this field empty"
	}
	input.MaximumNumberOfTry = -1
	return input
}

func (input *Input) Run() (string, error) {
	response := ""
	nbOfTry := 0
	for {
		question := input.buildQuestion()
		userResponse, err := linenoise.Line(question)
		if err != nil {
			return "", err
		}
		if len(input.Default) > 0 && len(userResponse) <= 0 {
			userResponse = input.Default
		}

		isValid := input.Validation(userResponse)
		if !isValid {
			if nbOfTry >= input.MaximumNumberOfTry && input.MaximumNumberOfTry != -1 {
				return "", fmt.Errorf("%s[%s]%s Number of maximun try reached %d %s\n", chalk.Red, usg.Get.CrossGraph, chalk.Yellow, nbOfTry, chalk.ResetColor)
			}
			fmt.Printf("%s[%s]%s %s %s\n", chalk.Red, usg.Get.CrossGraph, chalk.Yellow, input.ErrorMessage(userResponse), chalk.ResetColor)
			continue
		}

		nbOfTry++
		return userResponse, nil
	}

	return response, nil
}

func (input *Input) buildQuestion() string {
	hasDefaultValue := len(input.Default) > 0
	if hasDefaultValue {
		return fmt.Sprintf("%s[?]%s %s %s[%s]%s: ", chalk.Yellow, chalk.Green, input.Question, chalk.Yellow, input.Default, chalk.ResetColor)
	}
	return fmt.Sprintf("%s[?]%s %s%s: ", chalk.Yellow, chalk.Green, input.Question, chalk.ResetColor)
}
<|endoftext|>


<commit_before>package espsdk

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	log "github.com/Sirupsen/logrus"
)

const (
	endpoint      = "https://esp-sandbox.api.gettyimages.com/esp"
	oauthEndpoint = "https://api.gettyimages.com/oauth2/token"
	jsonIndent    = "\t"
)

// A Token is a string representation of an OAuth2 token. It grants a user
// access to the ESP API for a limited time.
type Token string

// A Serializable object can be serialized to a byte stream such as JSON.
type serializable interface {
	Marshal() ([]byte, error)
}

func prettyPrint(obj serializable) string {
	prettyOutput, err := obj.Marshal()
	if err != nil {
		log.Fatal(err)
	}
	return string(prettyOutput)
}

// Credentials represent a specific authorized application performing
// operations on objects belonging to a specific ESP user.
type Credentials struct {
	APIKey      string
	APISecret   string
	ESPUsername string
	ESPPassword string
}

func (c *Credentials) areInvalid() bool {
	if len(c.APIKey) < 1 || len(c.APISecret) < 1 || len(c.ESPUsername) < 1 || len(c.ESPPassword) < 1 {
		return true
	}
	return false
}

func (c *Credentials) formValues() url.Values {
	v := url.Values{}
	v.Set("client_id", c.APIKey)
	v.Set("client_secret", c.APISecret)
	v.Set("username", c.ESPUsername)
	v.Set("password", c.ESPPassword)
	v.Set("grant_type", "password")
	return v
}

// A Client is able to request an access token and submit HTTP requests to
// the ESP API.
type Client struct {
	Credentials
	UploadBucket string
}

// GetToken submits the provided credentials to Getty's OAuth2 endpoint
// and returns a token that can be used to authenticate HTTP requests to the
// ESP API.
func (c Client) GetToken() Token {
	if c.Credentials.areInvalid() {
		log.Fatal("Not all required credentials were supplied.")
	}

	uri := oauthEndpoint
	log.Debugf("%s", uri)
	formValues := c.formValues()
	log.Debugf("%s", formValues.Encode())

	resp, err := http.PostForm(uri, formValues)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	payload, err := ioutil.ReadAll(resp.Body)
	log.Debugf("HTTP %d", resp.StatusCode)
	log.Debugf("%s", payload)
	return c.tokenFrom(payload)
}

func (c Client) tokenFrom(payload []byte) Token {
	var response map[string]string
	json.Unmarshal(payload, &response)
	return Token(response["access_token"])
}

// A FulfilledRequest provides an overview of a completed API request and
// its result, including timing and HTTP status codes.
type FulfilledRequest struct {
	*RequestParams
	*Result
}

// Marshal serializes a FulfilledRequest into a byte stream.
func (r *FulfilledRequest) Marshal() ([]byte, error) { return json.Marshal(r) }

// RequestParams are provided to a Request to indicate the specific API
// endpoint and action to take. The Object is optional and applies only to
// endpoints that create or update items (POST and PUT).
type RequestParams struct {
	Verb   string `json:"method"`
	Path   string `json:"path"`
	Token  Token  `json:"-"`
	Object []byte `json:"-"`
}

func (p *RequestParams) requiresAnObject() bool {
	if p.Verb == "POST" || p.Verb == "PUT" || p.Verb == "DELETE" {
		return true
	}
	return false
}

// A Response contains the HTTP status code and text tha represent the API's
// response to a request.
type Response struct {
	StatusCode int    `json:"status_code"`
	Status     string `json:"-"`
}

// A Result contains information relative to a completed request, including
// the time elapsed to fulfill the request and any errors.
type Result struct {
	Response *Response     `json:"response"`
	Payload  []byte        `json:"-"`
	Duration time.Duration `json:"response_ms"`
	Err      error         `json:"-"`
}

// Request performs a request using the provided HTTP verb and returns
// the response as a JSON payload. If the verb is POST, the optional
// serialized object will become the body of the HTTP request.
func (c Client) Request(p *RequestParams) *FulfilledRequest {
	uri := endpoint + p.Path

	if p.requiresAnObject() && p.Object != nil {
		log.Debugf("Received serialized object: %s", p.Object)
	}
	req, err := http.NewRequest(p.Verb, uri, bytes.NewBuffer(p.Object))
	if err != nil {
		log.Fatal(err)
	}
	httpClient := insecureClient()

	result := getJSON(httpClient, req, p.Token, c.APIKey)
	if result.Err != nil {
		log.Fatal(result.Err)
		return &FulfilledRequest{
			p,
			&Result{
				&Response{
					result.Response.StatusCode,
					result.Response.Status,
				},
				nil,
				result.Duration,
				result.Err,
			},
		}
	}
	return &FulfilledRequest{p, result}
}

// Private

func getJSON(c *http.Client, req *http.Request, token Token, apiKey string) *Result {
	httpCommand := req.Method + " " + string(req.URL.Path)
	start := start(httpCommand)
	req.Header.Set("Authorization", "Token token="+string(token))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Api-Key", apiKey)

	resp, err := c.Do(req)
	duration := elapsed(httpCommand, start) / time.Millisecond
	if err != nil {
		log.Fatal(err)
		return getResult(resp, nil, duration)
	}
	defer resp.Body.Close()

	payload, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
		return getResult(resp, payload, duration)
	}
	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		log.Warnf("HTTP %s", resp.Status)
	}
	return getResult(resp, payload, duration)
}

func getResult(resp *http.Response, payload []byte, duration time.Duration) *Result {
	return &Result{
		&Response{
			resp.StatusCode,
			resp.Status,
		},
		payload, duration, nil}
}

// insecureClient returns an HTTP client that will not verify the validity
// of an SSL certificate when performing a request.
func insecureClient() *http.Client {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	return &http.Client{Transport: tr}
}

func start(s string) time.Time { return time.Now() }

func elapsed(s string, startTime time.Time) time.Duration {
	duration := time.Now().Sub(startTime)
	return duration
}

func indentedJSON(obj interface{}) ([]byte, error) {
	return json.MarshalIndent(obj, "", "\t")
}
<commit_msg>update docs<commit_after>/*
The ESP SDK provides a Go interface to the JSON API of Getty Images'
Enterprise Submission Portal (ESP).

You will need a username and password that allows you
to log in to https://sandbox.espaws.com/ as well as
an API Key and and API Secret, both of which are accessible
at https://developer.gettyimages.com/apps/mykeys/.
*/
package espsdk

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	log "github.com/Sirupsen/logrus"
)

const (
	endpoint      = "https://esp-sandbox.api.gettyimages.com/esp"
	oauthEndpoint = "https://api.gettyimages.com/oauth2/token"
	jsonIndent    = "\t"
)

// A Token is a string representation of an OAuth2 token. It grants a user
// access to the ESP API for a limited time.
type Token string

// A Serializable object can be serialized to a byte stream such as JSON.
type serializable interface {
	Marshal() ([]byte, error)
}

func prettyPrint(obj serializable) string {
	prettyOutput, err := obj.Marshal()
	if err != nil {
		log.Fatal(err)
	}
	return string(prettyOutput)
}

// Credentials represent a specific authorized application performing
// operations on objects belonging to a specific ESP user.
type Credentials struct {
	APIKey      string
	APISecret   string
	ESPUsername string
	ESPPassword string
}

func (c *Credentials) areInvalid() bool {
	if len(c.APIKey) < 1 || len(c.APISecret) < 1 || len(c.ESPUsername) < 1 || len(c.ESPPassword) < 1 {
		return true
	}
	return false
}

func (c *Credentials) formValues() url.Values {
	v := url.Values{}
	v.Set("client_id", c.APIKey)
	v.Set("client_secret", c.APISecret)
	v.Set("username", c.ESPUsername)
	v.Set("password", c.ESPPassword)
	v.Set("grant_type", "password")
	return v
}

// A Client is able to request an access token and submit HTTP requests to
// the ESP API.
type Client struct {
	Credentials
	UploadBucket string
}

// GetToken submits the provided credentials to Getty's OAuth2 endpoint
// and returns a token that can be used to authenticate HTTP requests to the
// ESP API.
func (c Client) GetToken() Token {
	if c.Credentials.areInvalid() {
		log.Fatal("Not all required credentials were supplied.")
	}

	uri := oauthEndpoint
	log.Debugf("%s", uri)
	formValues := c.formValues()
	log.Debugf("%s", formValues.Encode())

	resp, err := http.PostForm(uri, formValues)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	payload, err := ioutil.ReadAll(resp.Body)
	log.Debugf("HTTP %d", resp.StatusCode)
	log.Debugf("%s", payload)
	return c.tokenFrom(payload)
}

func (c Client) tokenFrom(payload []byte) Token {
	var response map[string]string
	json.Unmarshal(payload, &response)
	return Token(response["access_token"])
}

// A FulfilledRequest provides an overview of a completed API request and
// its result, including timing and HTTP status codes.
type FulfilledRequest struct {
	*RequestParams
	*Result
}

// Marshal serializes a FulfilledRequest into a byte stream.
func (r *FulfilledRequest) Marshal() ([]byte, error) { return json.Marshal(r) }

// RequestParams are provided to a Request to indicate the specific API
// endpoint and action to take. The Object is optional and applies only to
// endpoints that create or update items (POST and PUT).
type RequestParams struct {
	Verb   string `json:"method"`
	Path   string `json:"path"`
	Token  Token  `json:"-"`
	Object []byte `json:"-"`
}

func (p *RequestParams) requiresAnObject() bool {
	if p.Verb == "POST" || p.Verb == "PUT" || p.Verb == "DELETE" {
		return true
	}
	return false
}

// A Response contains the HTTP status code and text tha represent the API's
// response to a request.
type Response struct {
	StatusCode int    `json:"status_code"`
	Status     string `json:"-"`
}

// A Result contains information relative to a completed request, including
// the time elapsed to fulfill the request and any errors.
type Result struct {
	Response *Response     `json:"response"`
	Payload  []byte        `json:"-"`
	Duration time.Duration `json:"response_ms"`
	Err      error         `json:"-"`
}

// Request performs a request using the provided HTTP verb and returns
// the response as a JSON payload. If the verb is POST, the optional
// serialized object will become the body of the HTTP request.
func (c Client) Request(p *RequestParams) *FulfilledRequest {
	uri := endpoint + p.Path

	if p.requiresAnObject() && p.Object != nil {
		log.Debugf("Received serialized object: %s", p.Object)
	}
	req, err := http.NewRequest(p.Verb, uri, bytes.NewBuffer(p.Object))
	if err != nil {
		log.Fatal(err)
	}
	httpClient := insecureClient()

	result := getJSON(httpClient, req, p.Token, c.APIKey)
	if result.Err != nil {
		log.Fatal(result.Err)
		return &FulfilledRequest{
			p,
			&Result{
				&Response{
					result.Response.StatusCode,
					result.Response.Status,
				},
				nil,
				result.Duration,
				result.Err,
			},
		}
	}
	return &FulfilledRequest{p, result}
}

// Private

func getJSON(c *http.Client, req *http.Request, token Token, apiKey string) *Result {
	httpCommand := req.Method + " " + string(req.URL.Path)
	start := start(httpCommand)
	req.Header.Set("Authorization", "Token token="+string(token))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Api-Key", apiKey)

	resp, err := c.Do(req)
	duration := elapsed(httpCommand, start) / time.Millisecond
	if err != nil {
		log.Fatal(err)
		return getResult(resp, nil, duration)
	}
	defer resp.Body.Close()

	payload, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
		return getResult(resp, payload, duration)
	}
	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		log.Warnf("HTTP %s", resp.Status)
	}
	return getResult(resp, payload, duration)
}

func getResult(resp *http.Response, payload []byte, duration time.Duration) *Result {
	return &Result{
		&Response{
			resp.StatusCode,
			resp.Status,
		},
		payload, duration, nil}
}

// insecureClient returns an HTTP client that will not verify the validity
// of an SSL certificate when performing a request.
func insecureClient() *http.Client {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	return &http.Client{Transport: tr}
}

func start(s string) time.Time { return time.Now() }

func elapsed(s string, startTime time.Time) time.Duration {
	duration := time.Now().Sub(startTime)
	return duration
}

func indentedJSON(obj interface{}) ([]byte, error) {
	return json.MarshalIndent(obj, "", "\t")
}
<|endoftext|>


<commit_before>package main

import (
	"io/ioutil"
	"log"
	"os"
	"strings"
)

var (
	gCmdWords = []string{"set", "map", "cmd"}
	gOptWords = []string{
		"preview",
		"nopreview",
		"preview!",
		"hidden",
		"nohidden",
		"hidden!",
		"tabstop",
		"scrolloff",
		"sortby",
		"showinfo",
		"opener",
		"ratios",
	}
)

func matchLongest(s1, s2 string) string {
	i := 0
	for ; i < len(s1) && i < len(s2); i++ {
		if s1[i] != s2[i] {
			break
		}
	}
	return s1[:i]
}

func matchWord(s string, words []string) string {
	var match string

	for _, w := range words {
		if strings.HasPrefix(w, s) {
			if match != "" {
				match = matchLongest(match, w)
			} else {
				match = w + " "
			}
		}
	}

	if match != "" {
		return match
	}

	return s
}

func matchExec(s string) string {
	var match string

	paths := strings.Split(envPath, ":")

	for _, p := range paths {
		fi, err := ioutil.ReadDir(p)
		if err != nil {
			log.Print(err)
		}

		for _, f := range fi {
			if strings.HasPrefix(f.Name(), s) {
				if !f.Mode().IsRegular() || f.Mode()&0111 == 0 {
					continue
				}
				if match != "" {
					match = matchLongest(match, f.Name())
				} else {
					match = f.Name() + " "
				}
			}
		}
	}

	if match != "" {
		return match
	}

	return s
}

func matchFile(s string) string {
	var match string

	wd, err := os.Getwd()
	if err != nil {
		log.Print(err)
	}

	fi, err := ioutil.ReadDir(wd)
	if err != nil {
		log.Print(err)
	}

	for _, f := range fi {
		if strings.HasPrefix(f.Name(), s) {
			if match != "" {
				match = matchLongest(match, f.Name())
			} else {
				match = f.Name() + " "
			}
		}
	}

	if match != "" {
		return match
	}

	return s
}

func compCmd(acc []rune) []rune {
	if len(acc) == 0 || acc[len(acc)-1] == ' ' {
		return acc
	}

	s := string(acc)
	f := strings.Fields(s)

	switch len(f) {
	case 0: // do nothing
	case 1:
		words := gCmdWords
		for c, _ := range gOpts.cmds {
			words = append(words, c)
		}
		return []rune(matchWord(s, words))
	default:
		switch f[0] {
		case "set":
			opt := matchWord(f[1], gOptWords)
			ret := []rune(f[0])
			ret = append(ret, ' ')
			ret = append(ret, []rune(opt)...)
			return ret
		case "map", "cmd": // do nothing
		default:
			ret := []rune(f[0])
			ret = append(ret, ' ')
			for i := 1; i < len(f); i++ {
				name := matchFile(f[i])
				ret = append(ret, []rune(name)...)
			}
			return ret
		}
	}

	return acc
}

func compShell(acc []rune) []rune {
	if len(acc) == 0 || acc[len(acc)-1] == ' ' {
		return acc
	}

	s := string(acc)
	f := strings.Fields(s)

	switch len(f) {
	case 0: // do nothing
	case 1:
		return []rune(matchExec(s))
	default:
		ret := []rune(f[0])
		ret = append(ret, ' ')
		for i := 1; i < len(f); i++ {
			name := matchFile(f[i])
			ret = append(ret, []rune(name)...)
		}
		return ret
	}

	return acc
}
<commit_msg>handle symlinks in shell completion<commit_after>package main

import (
	"io/ioutil"
	"log"
	"os"
	"path"
	"strings"
)

var (
	gCmdWords = []string{"set", "map", "cmd"}
	gOptWords = []string{
		"preview",
		"nopreview",
		"preview!",
		"hidden",
		"nohidden",
		"hidden!",
		"tabstop",
		"scrolloff",
		"sortby",
		"showinfo",
		"opener",
		"ratios",
	}
)

func matchLongest(s1, s2 string) string {
	i := 0
	for ; i < len(s1) && i < len(s2); i++ {
		if s1[i] != s2[i] {
			break
		}
	}
	return s1[:i]
}

func matchWord(s string, words []string) string {
	var match string

	for _, w := range words {
		if strings.HasPrefix(w, s) {
			if match != "" {
				match = matchLongest(match, w)
			} else {
				match = w + " "
			}
		}
	}

	if match != "" {
		return match
	}

	return s
}

func matchExec(s string) string {
	var match string

	paths := strings.Split(envPath, ":")

	for _, p := range paths {
		fi, err := ioutil.ReadDir(p)
		if err != nil {
			log.Print(err)
		}

		for _, f := range fi {
			if strings.HasPrefix(f.Name(), s) {
				f, err = os.Stat(path.Join(p, f.Name()))
				if err != nil {
					log.Print(err)
				}

				if !f.Mode().IsRegular() || f.Mode()&0111 == 0 {
					continue
				}
				if match != "" {
					match = matchLongest(match, f.Name())
				} else {
					match = f.Name() + " "
				}
			}
		}
	}

	if match != "" {
		return match
	}

	return s
}

func matchFile(s string) string {
	var match string

	wd, err := os.Getwd()
	if err != nil {
		log.Print(err)
	}

	fi, err := ioutil.ReadDir(wd)
	if err != nil {
		log.Print(err)
	}

	for _, f := range fi {
		if strings.HasPrefix(f.Name(), s) {
			if match != "" {
				match = matchLongest(match, f.Name())
			} else {
				match = f.Name() + " "
			}
		}
	}

	if match != "" {
		return match
	}

	return s
}

func compCmd(acc []rune) []rune {
	if len(acc) == 0 || acc[len(acc)-1] == ' ' {
		return acc
	}

	s := string(acc)
	f := strings.Fields(s)

	switch len(f) {
	case 0: // do nothing
	case 1:
		words := gCmdWords
		for c, _ := range gOpts.cmds {
			words = append(words, c)
		}
		return []rune(matchWord(s, words))
	default:
		switch f[0] {
		case "set":
			opt := matchWord(f[1], gOptWords)
			ret := []rune(f[0])
			ret = append(ret, ' ')
			ret = append(ret, []rune(opt)...)
			return ret
		case "map", "cmd": // do nothing
		default:
			ret := []rune(f[0])
			ret = append(ret, ' ')
			for i := 1; i < len(f); i++ {
				name := matchFile(f[i])
				ret = append(ret, []rune(name)...)
			}
			return ret
		}
	}

	return acc
}

func compShell(acc []rune) []rune {
	if len(acc) == 0 || acc[len(acc)-1] == ' ' {
		return acc
	}

	s := string(acc)
	f := strings.Fields(s)

	switch len(f) {
	case 0: // do nothing
	case 1:
		return []rune(matchExec(s))
	default:
		ret := []rune(f[0])
		ret = append(ret, ' ')
		for i := 1; i < len(f); i++ {
			name := matchFile(f[i])
			ret = append(ret, []rune(name)...)
		}
		return ret
	}

	return acc
}
<|endoftext|>


<commit_before>package gform

import (
	"w32"
	"w32/user32"
)

type CustomControl struct {
	W32Control
}

func (this *CustomControl) Init(parent Controller) {
	RegClassOnlyOnce("gform_customcontrol")
	this.hwnd = CreateWindow("gform_customcontrol", parent, 0, w32.WS_CHILD|w32.WS_VISIBLE)
    this.isMouseLeft = true
    this.ControlBase.init(parent)
}

func (this *CustomControl) WndProc(msg uint, wparam, lparam uintptr) uintptr {
    sender := GetMsgHandler(this.hwnd)
    switch msg {
    case w32.WM_CREATE:
        internalTrackMouseEvent(this.hwnd)
        this.onCreate.Fire(NewEventArg(sender, nil))
    case w32.WM_MOUSEMOVE:
        if this.isMouseLeft {
            this.onMouseHover.Fire(NewEventArg(sender, nil))
            internalTrackMouseEvent(this.hwnd)
            this.isMouseLeft = false
        }
    case w32.WM_MOUSELEAVE:
        this.onMouseLeave.Fire(NewEventArg(sender, nil))
        this.isMouseLeft = true
    }
    return user32.DefWindowProc(this.hwnd, msg, wparam, lparam)
}
<commit_msg>Fire OnClose.<commit_after>package gform

import (
	"w32"
	"w32/user32"
)

type CustomControl struct {
	W32Control
}

func (this *CustomControl) Init(parent Controller) {
	RegClassOnlyOnce("gform_customcontrol")
	this.hwnd = CreateWindow("gform_customcontrol", parent, 0, w32.WS_CHILD|w32.WS_VISIBLE)
    this.isMouseLeft = true
    this.ControlBase.init(parent)
}

func (this *CustomControl) WndProc(msg uint, wparam, lparam uintptr) uintptr {
    sender := GetMsgHandler(this.hwnd)
    switch msg {
    case w32.WM_CREATE:
        internalTrackMouseEvent(this.hwnd)
        this.onCreate.Fire(NewEventArg(sender, nil))
    case w32.WM_CLOSE:
        this.onClose.Fire(NewEventArg(sender, nil))
    case w32.WM_MOUSEMOVE:
        if this.isMouseLeft {
            this.onMouseHover.Fire(NewEventArg(sender, nil))
            internalTrackMouseEvent(this.hwnd)
            this.isMouseLeft = false
        }
    case w32.WM_MOUSELEAVE:
        this.onMouseLeave.Fire(NewEventArg(sender, nil))
        this.isMouseLeft = true
    }
    return user32.DefWindowProc(this.hwnd, msg, wparam, lparam)
}
<|endoftext|>


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

// +build darwin freebsd linux openbsd windows

// (Raw) IP sockets

package net

import (
	"os"
	"sync"
	"syscall"
)

var onceReadProtocols sync.Once

func sockaddrToIP(sa syscall.Sockaddr) Addr {
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		return &IPAddr{sa.Addr[0:]}
	case *syscall.SockaddrInet6:
		return &IPAddr{sa.Addr[0:]}
	}
	return nil
}

func (a *IPAddr) family() int {
	if a == nil || len(a.IP) <= IPv4len {
		return syscall.AF_INET
	}
	if a.IP.To4() != nil {
		return syscall.AF_INET
	}
	return syscall.AF_INET6
}

func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) {
	return ipToSockaddr(family, a.IP, 0)
}

func (a *IPAddr) toAddr() sockaddr {
	if a == nil { // nil *IPAddr
		return nil // nil interface
	}
	return a
}

// IPConn is the implementation of the Conn and PacketConn
// interfaces for IP network connections.
type IPConn struct {
	fd *netFD
}

func newIPConn(fd *netFD) *IPConn { return &IPConn{fd} }

func (c *IPConn) ok() bool { return c != nil && c.fd != nil }

// Implementation of the Conn interface - see Conn for documentation.

// Read implements the net.Conn Read method.
func (c *IPConn) Read(b []byte) (n int, err os.Error) {
	n, _, err = c.ReadFrom(b)
	return
}

// Write implements the net.Conn Write method.
func (c *IPConn) Write(b []byte) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	return c.fd.Write(b)
}

// Close closes the IP connection.
func (c *IPConn) Close() os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	err := c.fd.Close()
	c.fd = nil
	return err
}

// LocalAddr returns the local network address.
func (c *IPConn) LocalAddr() Addr {
	if !c.ok() {
		return nil
	}
	return c.fd.laddr
}

// RemoteAddr returns the remote network address, a *IPAddr.
func (c *IPConn) RemoteAddr() Addr {
	if !c.ok() {
		return nil
	}
	return c.fd.raddr
}

// SetTimeout implements the net.Conn SetTimeout method.
func (c *IPConn) SetTimeout(nsec int64) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setTimeout(c.fd, nsec)
}

// SetReadTimeout implements the net.Conn SetReadTimeout method.
func (c *IPConn) SetReadTimeout(nsec int64) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setReadTimeout(c.fd, nsec)
}

// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
func (c *IPConn) SetWriteTimeout(nsec int64) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setWriteTimeout(c.fd, nsec)
}

// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
func (c *IPConn) SetReadBuffer(bytes int) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setReadBuffer(c.fd, bytes)
}

// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
func (c *IPConn) SetWriteBuffer(bytes int) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setWriteBuffer(c.fd, bytes)
}

// IP-specific methods.

// ReadFromIP reads a IP packet from c, copying the payload into b.
// It returns the number of bytes copied into b and the return address
// that was on the packet.
//
// ReadFromIP can be made to time out and return an error with
// Timeout() == true after a fixed time limit; see SetTimeout and
// SetReadTimeout.
func (c *IPConn) ReadFromIP(b []byte) (n int, addr *IPAddr, err os.Error) {
	if !c.ok() {
		return 0, nil, os.EINVAL
	}
	// TODO(cw,rsc): consider using readv if we know the family
	// type to avoid the header trim/copy
	n, sa, err := c.fd.ReadFrom(b)
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		addr = &IPAddr{sa.Addr[0:]}
		if len(b) >= IPv4len { // discard ipv4 header
			hsize := (int(b[0]) & 0xf) * 4
			copy(b, b[hsize:])
			n -= hsize
		}
	case *syscall.SockaddrInet6:
		addr = &IPAddr{sa.Addr[0:]}
	}
	return
}

// ReadFrom implements the net.PacketConn ReadFrom method.
func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
	if !c.ok() {
		return 0, nil, os.EINVAL
	}
	n, uaddr, err := c.ReadFromIP(b)
	return n, uaddr.toAddr(), err
}

// WriteToIP writes a IP packet to addr via c, copying the payload from b.
//
// WriteToIP can be made to time out and return
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	sa, err1 := addr.sockaddr(c.fd.family)
	if err1 != nil {
		return 0, &OpError{Op: "write", Net: "ip", Addr: addr, Error: err1}
	}
	return c.fd.WriteTo(b, sa)
}

// WriteTo implements the net.PacketConn WriteTo method.
func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	a, ok := addr.(*IPAddr)
	if !ok {
		return 0, &OpError{"writeto", "ip", addr, os.EINVAL}
	}
	return c.WriteToIP(b, a)
}

var protocols map[string]int

func readProtocols() {
	protocols = make(map[string]int)
	if file, err := open("/etc/protocols"); err == nil {
		for line, ok := file.readLine(); ok; line, ok = file.readLine() {
			// tcp    6   TCP    # transmission control protocol
			if i := byteIndex(line, '#'); i >= 0 {
				line = line[0:i]
			}
			f := getFields(line)
			if len(f) < 2 {
				continue
			}
			if proto, _, ok := dtoi(f[1], 0); ok {
				protocols[f[0]] = proto
				for _, alias := range f[2:] {
					protocols[alias] = proto
				}
			}
		}
		file.close()
	}
}

func splitNetProto(netProto string) (net string, proto int, err os.Error) {
	onceReadProtocols.Do(readProtocols)
	i := last(netProto, ':')
	if i < 0 { // no colon
		return "", 0, os.NewError("no IP protocol specified")
	}
	net = netProto[0:i]
	protostr := netProto[i+1:]
	proto, i, ok := dtoi(protostr, 0)
	if !ok || i != len(protostr) {
		// lookup by name
		proto, ok = protocols[protostr]
		if ok {
			return
		}
	}
	return
}

// DialIP connects to the remote address raddr on the network net,
// which must be "ip", "ip4", or "ip6".
func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) {
	net, proto, err := splitNetProto(netProto)
	if err != nil {
		return
	}
	switch net {
	case "ip", "ip4", "ip6":
	default:
		return nil, UnknownNetworkError(net)
	}
	if raddr == nil {
		return nil, &OpError{"dial", "ip", nil, errMissingAddress}
	}
	fd, e := internetSocket(net, laddr.toAddr(), raddr.toAddr(), syscall.SOCK_RAW, proto, "dial", sockaddrToIP)
	if e != nil {
		return nil, e
	}
	return newIPConn(fd), nil
}

// ListenIP listens for incoming IP packets addressed to the
// local address laddr.  The returned connection c's ReadFrom
// and WriteTo methods can be used to receive and send IP
// packets with per-packet addressing.
func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err os.Error) {
	net, proto, err := splitNetProto(netProto)
	if err != nil {
		return
	}
	switch net {
	case "ip", "ip4", "ip6":
	default:
		return nil, UnknownNetworkError(net)
	}
	fd, e := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_RAW, proto, "dial", sockaddrToIP)
	if e != nil {
		return nil, e
	}
	return newIPConn(fd), nil
}

// BindToDevice binds an IPConn to a network interface.
func (c *IPConn) BindToDevice(device string) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	c.fd.incref()
	defer c.fd.decref()
	return os.NewSyscallError("setsockopt", syscall.BindToDevice(c.fd.sysfd, device))
}
<commit_msg>net: add File method to IPConn<commit_after>// Copyright 2010 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build darwin freebsd linux openbsd windows

// (Raw) IP sockets

package net

import (
	"os"
	"sync"
	"syscall"
)

var onceReadProtocols sync.Once

func sockaddrToIP(sa syscall.Sockaddr) Addr {
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		return &IPAddr{sa.Addr[0:]}
	case *syscall.SockaddrInet6:
		return &IPAddr{sa.Addr[0:]}
	}
	return nil
}

func (a *IPAddr) family() int {
	if a == nil || len(a.IP) <= IPv4len {
		return syscall.AF_INET
	}
	if a.IP.To4() != nil {
		return syscall.AF_INET
	}
	return syscall.AF_INET6
}

func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) {
	return ipToSockaddr(family, a.IP, 0)
}

func (a *IPAddr) toAddr() sockaddr {
	if a == nil { // nil *IPAddr
		return nil // nil interface
	}
	return a
}

// IPConn is the implementation of the Conn and PacketConn
// interfaces for IP network connections.
type IPConn struct {
	fd *netFD
}

func newIPConn(fd *netFD) *IPConn { return &IPConn{fd} }

func (c *IPConn) ok() bool { return c != nil && c.fd != nil }

// Implementation of the Conn interface - see Conn for documentation.

// Read implements the net.Conn Read method.
func (c *IPConn) Read(b []byte) (n int, err os.Error) {
	n, _, err = c.ReadFrom(b)
	return
}

// Write implements the net.Conn Write method.
func (c *IPConn) Write(b []byte) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	return c.fd.Write(b)
}

// Close closes the IP connection.
func (c *IPConn) Close() os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	err := c.fd.Close()
	c.fd = nil
	return err
}

// LocalAddr returns the local network address.
func (c *IPConn) LocalAddr() Addr {
	if !c.ok() {
		return nil
	}
	return c.fd.laddr
}

// RemoteAddr returns the remote network address, a *IPAddr.
func (c *IPConn) RemoteAddr() Addr {
	if !c.ok() {
		return nil
	}
	return c.fd.raddr
}

// SetTimeout implements the net.Conn SetTimeout method.
func (c *IPConn) SetTimeout(nsec int64) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setTimeout(c.fd, nsec)
}

// SetReadTimeout implements the net.Conn SetReadTimeout method.
func (c *IPConn) SetReadTimeout(nsec int64) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setReadTimeout(c.fd, nsec)
}

// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
func (c *IPConn) SetWriteTimeout(nsec int64) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setWriteTimeout(c.fd, nsec)
}

// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
func (c *IPConn) SetReadBuffer(bytes int) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setReadBuffer(c.fd, bytes)
}

// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
func (c *IPConn) SetWriteBuffer(bytes int) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	return setWriteBuffer(c.fd, bytes)
}

// IP-specific methods.

// ReadFromIP reads a IP packet from c, copying the payload into b.
// It returns the number of bytes copied into b and the return address
// that was on the packet.
//
// ReadFromIP can be made to time out and return an error with
// Timeout() == true after a fixed time limit; see SetTimeout and
// SetReadTimeout.
func (c *IPConn) ReadFromIP(b []byte) (n int, addr *IPAddr, err os.Error) {
	if !c.ok() {
		return 0, nil, os.EINVAL
	}
	// TODO(cw,rsc): consider using readv if we know the family
	// type to avoid the header trim/copy
	n, sa, err := c.fd.ReadFrom(b)
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		addr = &IPAddr{sa.Addr[0:]}
		if len(b) >= IPv4len { // discard ipv4 header
			hsize := (int(b[0]) & 0xf) * 4
			copy(b, b[hsize:])
			n -= hsize
		}
	case *syscall.SockaddrInet6:
		addr = &IPAddr{sa.Addr[0:]}
	}
	return
}

// ReadFrom implements the net.PacketConn ReadFrom method.
func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
	if !c.ok() {
		return 0, nil, os.EINVAL
	}
	n, uaddr, err := c.ReadFromIP(b)
	return n, uaddr.toAddr(), err
}

// WriteToIP writes a IP packet to addr via c, copying the payload from b.
//
// WriteToIP can be made to time out and return
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	sa, err1 := addr.sockaddr(c.fd.family)
	if err1 != nil {
		return 0, &OpError{Op: "write", Net: "ip", Addr: addr, Error: err1}
	}
	return c.fd.WriteTo(b, sa)
}

// WriteTo implements the net.PacketConn WriteTo method.
func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
	if !c.ok() {
		return 0, os.EINVAL
	}
	a, ok := addr.(*IPAddr)
	if !ok {
		return 0, &OpError{"writeto", "ip", addr, os.EINVAL}
	}
	return c.WriteToIP(b, a)
}

var protocols map[string]int

func readProtocols() {
	protocols = make(map[string]int)
	if file, err := open("/etc/protocols"); err == nil {
		for line, ok := file.readLine(); ok; line, ok = file.readLine() {
			// tcp    6   TCP    # transmission control protocol
			if i := byteIndex(line, '#'); i >= 0 {
				line = line[0:i]
			}
			f := getFields(line)
			if len(f) < 2 {
				continue
			}
			if proto, _, ok := dtoi(f[1], 0); ok {
				protocols[f[0]] = proto
				for _, alias := range f[2:] {
					protocols[alias] = proto
				}
			}
		}
		file.close()
	}
}

func splitNetProto(netProto string) (net string, proto int, err os.Error) {
	onceReadProtocols.Do(readProtocols)
	i := last(netProto, ':')
	if i < 0 { // no colon
		return "", 0, os.NewError("no IP protocol specified")
	}
	net = netProto[0:i]
	protostr := netProto[i+1:]
	proto, i, ok := dtoi(protostr, 0)
	if !ok || i != len(protostr) {
		// lookup by name
		proto, ok = protocols[protostr]
		if ok {
			return
		}
	}
	return
}

// DialIP connects to the remote address raddr on the network net,
// which must be "ip", "ip4", or "ip6".
func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) {
	net, proto, err := splitNetProto(netProto)
	if err != nil {
		return
	}
	switch net {
	case "ip", "ip4", "ip6":
	default:
		return nil, UnknownNetworkError(net)
	}
	if raddr == nil {
		return nil, &OpError{"dial", "ip", nil, errMissingAddress}
	}
	fd, e := internetSocket(net, laddr.toAddr(), raddr.toAddr(), syscall.SOCK_RAW, proto, "dial", sockaddrToIP)
	if e != nil {
		return nil, e
	}
	return newIPConn(fd), nil
}

// ListenIP listens for incoming IP packets addressed to the
// local address laddr.  The returned connection c's ReadFrom
// and WriteTo methods can be used to receive and send IP
// packets with per-packet addressing.
func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err os.Error) {
	net, proto, err := splitNetProto(netProto)
	if err != nil {
		return
	}
	switch net {
	case "ip", "ip4", "ip6":
	default:
		return nil, UnknownNetworkError(net)
	}
	fd, e := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_RAW, proto, "dial", sockaddrToIP)
	if e != nil {
		return nil, e
	}
	return newIPConn(fd), nil
}

// BindToDevice binds an IPConn to a network interface.
func (c *IPConn) BindToDevice(device string) os.Error {
	if !c.ok() {
		return os.EINVAL
	}
	c.fd.incref()
	defer c.fd.decref()
	return os.NewSyscallError("setsockopt", syscall.BindToDevice(c.fd.sysfd, device))
}

// File returns a copy of the underlying os.File, set to blocking mode.
// It is the caller's responsibility to close f when finished.
// Closing c does not affect f, and closing f does not affect c.
func (c *IPConn) File() (f *os.File, err os.Error) { return c.fd.dup() }
<|endoftext|>


<commit_before>package alita

import (
	"reflect"
	"regexp"
	"testing"
)

var delimiterSetTests = []struct {
	useRegexp bool
	expr      string
	re        *regexp.Regexp
}{
	// Fixed
	{false, `=`, regexp.MustCompile(`=`)},
	{false, `=+`, regexp.MustCompile(`=\+`)},
	{false, `-*>`, regexp.MustCompile(`-\*>`)},
	{false, `abc`, regexp.MustCompile(`abc`)},
	{false, `\w+:`, regexp.MustCompile(`\\w\+:`)},
	{false, `[:/]+`, regexp.MustCompile(`\[:/\]\+`)},

	// Regexp
	{true, `=`, regexp.MustCompile(`=`)},
	{true, `=+`, regexp.MustCompile(`=+`)},
	{true, `-*>`, regexp.MustCompile(`-*>`)},
	{true, `abc`, regexp.MustCompile(`abc`)},
	{true, `\w+:`, regexp.MustCompile(`\w+:`)},
	{true, `[:/]+`, regexp.MustCompile(`[:/]+`)},
}

func TestDelimiterSet(t *testing.T) {
	d := NewDelimiter()
	for _, test := range delimiterSetTests {
		d.UseRegexp = test.useRegexp
		if err := d.Set(test.expr); err != nil {
			t.Errorf("Set(%q) returns %q; want nil",
				test.expr, err)
		}
		if !reflect.DeepEqual(d.re, test.re) {
			t.Errorf("got %q; want %q",
				d.re, test.re)
		}
	}
}

var delimiterSplitDefaultTests = []struct {
	src string
	dst []string
}{
	// Normal
	{"a", []string{"a"}},
	{"a b", []string{"a", "b"}},
	{"a b c", []string{"a", "b", "c"}},
	{"a b c d", []string{"a", "b", "c", "d"}},
	{"ab cd", []string{"ab", "cd"}},
	{"日本 語", []string{"日本", "語"}},

	// Long spaces
	{"a  b", []string{"a", "b"}},
	{"a  b c", []string{"a", "b", "c"}},
	{"a \t b c", []string{"a", "b", "c"}},

	// Head and tail spaces
	{"  a b c", []string{"", "a", "b", "c"}},
	{"a b c ", []string{"a", "b", "c", ""}},
}

func TestDelimiterDefaultSplit(t *testing.T) {
	d := NewDelimiter()
	for _, test := range delimiterSplitDefaultTests {
		actual := d.Split(test.src)
		expect := test.dst
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Delimiter(%q).Split(%q) = %q; want %q",
				d.re, test.src, actual, expect)
		}
	}
}

var delimiterSplitTests = []struct {
	useRegexp bool
	expr      string
	src       string
	dst       []string
}{
	{false, `=`, "n", []string{"n"}},
	{false, `=`, "n=", []string{"n", "=", ""}},
	{false, `=`, "=n", []string{"", "=", "n"}},

	{false, `=`, "n=100", []string{"n", "=", "100"}},
	{false, `=`, "n  =  100", []string{"n", "=", "100"}},
	{false, `=`, "n  = 100=200", []string{"n", "=", "100", "=", "200"}},
	{false, `=`, "n=100 =  200", []string{"n", "=", "100", "=", "200"}},

	{false, `=`, "n==100", []string{"n", "=", "", "=", "100"}},
	{false, `=`, "n===100", []string{"n", "=", "", "=", "", "=", "100"}},

	{false, `=>`, "a=>b=>c", []string{"a", "=>", "b", "=>", "c"}},
	{false, `=>`, "a => b => c", []string{"a", "=>", "b", "=>", "c"}},
	{false, `=>`, "a==>=b==>=c", []string{"a=", "=>", "=b=", "=>", "=c"}},

	{true, `=+>`, "a => b",
		[]string{"a", "=>", "b"}},
	{true, `=+>`, "a => b ==> c ===> d",
		[]string{"a", "=>", "b", "==>", "c", "===>", "d"}},
	{true, `=+>`, "a=>b==>=c",
		[]string{"a", "=>", "b", "==>", "=c"}},
}

func TestDelimiterSplit(t *testing.T) {
	d := NewDelimiter()
	for _, test := range delimiterSplitTests {
		d.UseRegexp = test.useRegexp
		if err := d.Set(test.expr); err != nil {
			t.Errorf("Set(%q) returns %q; want nil",
				test.expr, err)
		}

		actual := d.Split(test.src)
		expect := test.dst
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Delimiter(%q).Split(%q) = %q; want %q",
				d.re, test.src, actual, expect)
		}
	}
}
<commit_msg>Add test for delimit with count<commit_after>package alita

import (
	"reflect"
	"regexp"
	"testing"
)

var delimiterSetTests = []struct {
	useRegexp bool
	expr      string
	re        *regexp.Regexp
}{
	// Fixed
	{false, `=`, regexp.MustCompile(`=`)},
	{false, `=+`, regexp.MustCompile(`=\+`)},
	{false, `-*>`, regexp.MustCompile(`-\*>`)},
	{false, `abc`, regexp.MustCompile(`abc`)},
	{false, `\w+:`, regexp.MustCompile(`\\w\+:`)},
	{false, `[:/]+`, regexp.MustCompile(`\[:/\]\+`)},

	// Regexp
	{true, `=`, regexp.MustCompile(`=`)},
	{true, `=+`, regexp.MustCompile(`=+`)},
	{true, `-*>`, regexp.MustCompile(`-*>`)},
	{true, `abc`, regexp.MustCompile(`abc`)},
	{true, `\w+:`, regexp.MustCompile(`\w+:`)},
	{true, `[:/]+`, regexp.MustCompile(`[:/]+`)},
}

func TestDelimiterSet(t *testing.T) {
	d := NewDelimiter()
	for _, test := range delimiterSetTests {
		d.UseRegexp = test.useRegexp
		if err := d.Set(test.expr); err != nil {
			t.Errorf("Set(%q) returns %q; want nil",
				test.expr, err)
		}
		if !reflect.DeepEqual(d.re, test.re) {
			t.Errorf("got %q; want %q",
				d.re, test.re)
		}
	}
}

var delimiterSplitDefaultTests = []struct {
	src string
	dst []string
}{
	// Normal
	{"a", []string{"a"}},
	{"a b", []string{"a", "b"}},
	{"a b c", []string{"a", "b", "c"}},
	{"a b c d", []string{"a", "b", "c", "d"}},
	{"ab cd", []string{"ab", "cd"}},
	{"日本 語", []string{"日本", "語"}},

	// Long spaces
	{"a  b", []string{"a", "b"}},
	{"a  b c", []string{"a", "b", "c"}},
	{"a \t b c", []string{"a", "b", "c"}},

	// Head and tail spaces
	{"  a b c", []string{"", "a", "b", "c"}},
	{"a b c ", []string{"a", "b", "c", ""}},
}

func TestDelimiterDefaultSplit(t *testing.T) {
	d := NewDelimiter()
	for _, test := range delimiterSplitDefaultTests {
		actual := d.Split(test.src)
		expect := test.dst
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Delimiter(%q).Split(%q) = %q; want %q",
				d.re, test.src, actual, expect)
		}
	}
}

var delimiterSplitTests = []struct {
	useRegexp bool
	expr      string
	src       string
	dst       []string
}{
	{false, `=`, "n", []string{"n"}},
	{false, `=`, "n=", []string{"n", "=", ""}},
	{false, `=`, "=n", []string{"", "=", "n"}},

	{false, `=`, "n=100", []string{"n", "=", "100"}},
	{false, `=`, "n  =  100", []string{"n", "=", "100"}},
	{false, `=`, "n  = 100=200", []string{"n", "=", "100", "=", "200"}},
	{false, `=`, "n=100 =  200", []string{"n", "=", "100", "=", "200"}},

	{false, `=`, "n==100", []string{"n", "=", "", "=", "100"}},
	{false, `=`, "n===100", []string{"n", "=", "", "=", "", "=", "100"}},

	{false, `=>`, "a=>b=>c", []string{"a", "=>", "b", "=>", "c"}},
	{false, `=>`, "a => b => c", []string{"a", "=>", "b", "=>", "c"}},
	{false, `=>`, "a==>=b==>=c", []string{"a=", "=>", "=b=", "=>", "=c"}},

	{true, `=+>`, "a => b",
		[]string{"a", "=>", "b"}},
	{true, `=+>`, "a => b ==> c ===> d",
		[]string{"a", "=>", "b", "==>", "c", "===>", "d"}},
	{true, `=+>`, "a=>b==>=c",
		[]string{"a", "=>", "b", "==>", "=c"}},
}

func TestDelimiterSplit(t *testing.T) {
	d := NewDelimiter()
	for _, test := range delimiterSplitTests {
		d.UseRegexp = test.useRegexp
		if err := d.Set(test.expr); err != nil {
			t.Errorf("Set(%q) returns %q; want nil",
				test.expr, err)
		}

		actual := d.Split(test.src)
		expect := test.dst
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Delimiter(%q).Split(%q) = %q; want %q",
				d.re, test.src, actual, expect)
		}
	}
}

var delimiterSplitWithCountTests = []struct {
	count int
	src   string
	dst   []string
}{
	// Less than 0
	{-2, "n =  m   =    100", []string{"n", "=", "m", "=", "100"}},
	{-1, "n =  m   =    100", []string{"n", "=", "m", "=", "100"}},

	// Equal 0
	{0, "n =  m   =    100", []string{"n =  m   =    100"}},

	// Greater than 0
	{1, "n =  m   =    100", []string{"n", "=  m   =    100"}},
	{2, "n =  m   =    100", []string{"n", "=", "m   =    100"}},
	{3, "n =  m   =    100", []string{"n", "=", "m", "=    100"}},
	{4, "n =  m   =    100", []string{"n", "=", "m", "=", "100"}},
	{5, "n =  m   =    100", []string{"n", "=", "m", "=", "100"}},
}

func TestSplitWithCount(t *testing.T) {
	d := NewDelimiter()
	if err := d.Set(`=`); err != nil {
		t.Errorf("Delimiter(\"=\").Split(%q) = %q; want %q", err)
	}
	for _, test := range delimiterSplitWithCountTests {
		d.Count = test.count

		actual := d.Split(test.src)
		expect := test.dst
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("Delimiter(%q, %d).Split(%q) = %q; want %q",
				d.re, d.Count, test.src, actual, expect)
		}
	}
}
<|endoftext|>