<commit_before>/*
 * connector.go
 *
 * Copyright 2017 Bill Zissimopoulos
 */
/*
 * This file is part of netchan.
 *
 * It is licensed under the MIT license. The full license text can be found
 * in the License.txt file at the root of this project.
 */

package netchan

import (
	"net/url"
	"reflect"
	"sync"
)

type coninfo struct {
	slist []reflect.SelectCase
	ilist []string
	elist []chan error
}

type connector struct {
	transport Transport
	conmux    sync.RWMutex
	conmap    map[Link]coninfo
	chanset   map[interface{}]struct{}
	wchanmap  *weakmap
}

func newConnector(transport Transport) *connector {
	self := &connector{
		transport: transport,
		conmap:    make(map[Link]coninfo),
		chanset:   make(map[interface{}]struct{}),
		wchanmap:  newWeakmap(),
	}
	transport.SetChanDecoder(self)
	transport.SetSender(self.sender)
	return self
}

func (self *connector) Connect(iuri interface{}, ichan interface{}, echan chan error) error {
	vchan := reflect.ValueOf(ichan)
	if reflect.Chan != vchan.Kind() || 0 == vchan.Type().ChanDir()&reflect.SendDir {
		panic(ErrArgumentInvalid)
	}

	var uri *url.URL
	var err error
	switch u := iuri.(type) {
	case string:
		uri, err = url.Parse(u)
		if nil != err {
			return newErrTransport(err)
		}
	case *url.URL:
		uri = u
	default:
		panic(ErrArgumentInvalid)
	}

	id, link, err := self.transport.Connect(uri)
	if nil != err {
		return err
	}

	/*
	 * At this point Transport.Connect() has allocated a link and may have allocated
	 * additional resources. Ideally we would not want the connect() operation below
	 * to fail. Unfortunately there is still the possibility of getting an already
	 * connected channel, which we must treat as an error.
	 *
	 * Although we could check for that possibility before the Transport.Connect()
	 * call, to do this without race conditions we would have to hold the conmux lock
	 * over Transport.Connect() which is a potentially slow call. So we choose the
	 * least worse evil, which is to sometimes fail the connect() operation after a
	 * successful Transport.Connect().
	 */

	return self.connect(id, link, vchan, echan)
}

func (self *connector) connect(id string, link Link, vchan reflect.Value, echan chan error) error {
	self.conmux.Lock()
	defer self.conmux.Unlock()

	ichan := vchan.Interface()
	_, ok := self.chanset[ichan]
	if ok {
		return ErrArgumentChanConnected
	}

	info := self.conmap[link]
	found := false
	for _, s := range info.slist {
		if s.Chan == vchan {
			found = true
			break
		}
	}

	if !found {
		if nil == info.slist {
			info.slist = append(info.slist,
				reflect.SelectCase{
					Dir:  reflect.SelectRecv,
					Chan: reflect.ValueOf(make(chan struct{}, 0x7fffffff)),
				})
			info.ilist = append(info.ilist, "")
			info.elist = append(info.elist, nil)
		}

		info.slist = append(info.slist,
			reflect.SelectCase{Dir: reflect.SelectRecv, Chan: vchan})
		info.ilist = append(info.ilist, id)
		info.elist = append(info.elist, echan)

		self.conmap[link] = info
		info.slist[0].Chan.Send(reflect.ValueOf(struct{}{}))

		link.Open()
	}

	self.chanset[ichan] = struct{}{}

	return nil
}

func (self *connector) disconnect(link Link, vchan reflect.Value) {
	self.conmux.Lock()
	defer self.conmux.Unlock()

	info := self.conmap[link]
	for i, s := range info.slist {
		if s.Chan == vchan {
			info.slist = append(info.slist[:i], info.slist[i+1:]...)
			info.ilist = append(info.ilist[:i], info.ilist[i+1:]...)
			info.elist = append(info.elist[:i], info.elist[i+1:]...)

			self.conmap[link] = info

			return
		}
	}
}

func (self *connector) sender(link Link) error {
outer:
	for {
		// make a copy so that we can safely use it outside the read lock
		self.conmux.RLock()
		info := self.conmap[link]
		slist := append([]reflect.SelectCase(nil), info.slist...)
		ilist := append([]string(nil), info.ilist...)
		elist := append([]chan error(nil), info.elist...)
		self.conmux.RUnlock()

		for {
			i, vmsg, ok := reflect.Select(slist)
			if 0 == i {
				continue outer
			}
			if !ok {
				self.disconnect(link, slist[i].Chan)
				continue outer
			}

			err := link.Send(ilist[i], vmsg)
			if nil != err {
				if nil != elist[i] {
					if e, ok := err.(errArgs); ok {
						e.args(slist[i].Chan.Interface())
					}

					func() {
						defer recover()
						elist[i] <- err
					}()
				}

				if _, ok := err.(*ErrTransport); ok {
					return err
				}
			}
		}
	}
}

func (self *connector) ChanDecode(link Link, ichan interface{}, buf []byte) error {
	v := reflect.ValueOf(ichan).Elem()

	var w weakref
	copy(w[:], buf)

	s := self.wchanmap.strongref(w, func() interface{} {
		return reflect.MakeChan(v.Type(), 1).Interface()
	})
	if nil == s {
		return ErrMarshalerRefInvalid
	}

	v.Set(reflect.ValueOf(s))

	id := RefEncode(w)
	self.connect(id, link, reflect.ValueOf(s), nil)

	return nil
}

var DefaultConnector Connector = newConnector(DefaultTransport)

// Connect uses the DefaultConnector and
// connects a local channel to a remote channel that is addressed by uri. The uri
// depends on the underlying network transport and may contain addressing and id information.
//
// The uri may be of type string or *url.URL. An error channel (type: chan error) may be
// supplied as well; it will receive Connector network errors.
func Connect(uri interface{}, ichan interface{}, echan chan error) error {
	return DefaultConnector.Connect(uri, ichan, echan)
}
<commit_msg>connector: improvements<commit_after>/*
 * connector.go
 *
 * Copyright 2017 Bill Zissimopoulos
 */
/*
 * This file is part of netchan.
 *
 * It is licensed under the MIT license. The full license text can be found
 * in the License.txt file at the root of this project.
 */

package netchan

import (
	"net/url"
	"reflect"
	"sync"
)

type coninfo struct {
	slist []reflect.SelectCase
	ilist []string
	elist []chan error
}

type connector struct {
	transport Transport
	conmux    sync.RWMutex
	conmap    map[Link]coninfo
	conset    map[interface{}]struct{}
}

func newConnector(transport Transport) *connector {
	self := &connector{
		transport: transport,
		conmap:    make(map[Link]coninfo),
		conset:    make(map[interface{}]struct{}),
	}
	transport.SetChanDecoder(self)
	transport.SetSender(self.sender)
	return self
}

func (self *connector) Connect(iuri interface{}, ichan interface{}, echan chan error) error {
	vchan := reflect.ValueOf(ichan)
	if reflect.Chan != vchan.Kind() || 0 == vchan.Type().ChanDir()&reflect.SendDir {
		panic(ErrArgumentInvalid)
	}

	var uri *url.URL
	var err error
	switch u := iuri.(type) {
	case string:
		uri, err = url.Parse(u)
		if nil != err {
			return newErrTransport(err)
		}
	case *url.URL:
		uri = u
	default:
		panic(ErrArgumentInvalid)
	}

	id, link, err := self.transport.Connect(uri)
	if nil != err {
		return err
	}

	/*
	 * At this point Transport.Connect() has allocated a link and may have allocated
	 * additional resources. Ideally we would not want the connect() operation below
	 * to fail. Unfortunately there is still the possibility of getting an already
	 * connected channel, which we must treat as an error.
	 *
	 * Although we could check for that possibility before the Transport.Connect()
	 * call, to do this without race conditions we would have to hold the conmux lock
	 * over Transport.Connect() which is a potentially slow call. So we choose the
	 * least worse evil, which is to sometimes fail the connect() operation after a
	 * successful Transport.Connect().
	 */

	return self.connect(id, link, vchan, echan)
}

func (self *connector) connect(id string, link Link, vchan reflect.Value, echan chan error) error {
	self.conmux.Lock()
	defer self.conmux.Unlock()

	ichan := vchan.Interface()
	_, ok := self.conset[ichan]
	if ok {
		return ErrArgumentChanConnected
	}

	info := self.conmap[link]
	found := false
	for _, s := range info.slist {
		if s.Chan == vchan {
			found = true
			break
		}
	}

	if !found {
		if nil == info.slist {
			info.slist = append(info.slist,
				reflect.SelectCase{
					Dir:  reflect.SelectRecv,
					Chan: reflect.ValueOf(make(chan struct{}, 0x7fffffff)),
				})
			info.ilist = append(info.ilist, "")
			info.elist = append(info.elist, nil)
		}

		info.slist = append(info.slist,
			reflect.SelectCase{Dir: reflect.SelectRecv, Chan: vchan})
		info.ilist = append(info.ilist, id)
		info.elist = append(info.elist, echan)

		self.conmap[link] = info
		info.slist[0].Chan.Send(reflect.ValueOf(struct{}{}))

		link.Open()
	}

	self.conset[ichan] = struct{}{}

	return nil
}

func (self *connector) disconnect(link Link, vchan reflect.Value) {
	self.conmux.Lock()
	defer self.conmux.Unlock()

	info := self.conmap[link]
	for i, s := range info.slist {
		if s.Chan == vchan {
			info.slist = append(info.slist[:i], info.slist[i+1:]...)
			info.ilist = append(info.ilist[:i], info.ilist[i+1:]...)
			info.elist = append(info.elist[:i], info.elist[i+1:]...)

			self.conmap[link] = info

			return
		}
	}
}

func (self *connector) sender(link Link) error {
outer:
	for {
		// make a copy so that we can safely use it outside the read lock
		self.conmux.RLock()
		info := self.conmap[link]
		slist := append([]reflect.SelectCase(nil), info.slist...)
		ilist := append([]string(nil), info.ilist...)
		elist := append([]chan error(nil), info.elist...)
		self.conmux.RUnlock()

		for {
			i, vmsg, ok := reflect.Select(slist)
			if 0 == i {
				continue outer
			}
			if !ok {
				self.disconnect(link, slist[i].Chan)
				continue outer
			}

			err := link.Send(ilist[i], vmsg)
			if nil != err {
				if nil != elist[i] {
					if e, ok := err.(errArgs); ok {
						e.args(slist[i].Chan.Interface())
					}

					func() {
						defer recover()
						elist[i] <- err
					}()
				}

				if _, ok := err.(*ErrTransport); ok {
					return err
				}
			}
		}
	}
}

func (self *connector) ChanDecode(link Link, ichan interface{}, buf []byte) error {
	var w weakref
	copy(w[:], buf)
	id := RefEncode(w)

	v := reflect.ValueOf(ichan).Elem()
	u := reflect.MakeChan(v.Type(), 1)
	v.Set(u)

	/*
	 * connect() may only return "chan is already connected" error,
	 * which cannot happen in this scenario (because we always create
	 * new channels with reflect.MakeChan()).
	 */

	self.connect(id, link, u, nil)

	return nil
}

var DefaultConnector Connector = newConnector(DefaultTransport)

// Connect uses the DefaultConnector and
// connects a local channel to a remote channel that is addressed by uri. The uri
// depends on the underlying network transport and may contain addressing and id information.
//
// The uri may be of type string or *url.URL. An error channel (type: chan error) may be
// supplied as well; it will receive Connector network errors.
func Connect(uri interface{}, ichan interface{}, echan chan error) error {
	return DefaultConnector.Connect(uri, ichan, echan)
}
<|endoftext|>


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

package media

import (
	"encoding/json"
	"errors"
	"fmt"
	"sort"
	"strings"

	"github.com/gohugoio/hugo/common/maps"

	"github.com/mitchellh/mapstructure"
)

const (
	defaultDelimiter = "."
)

// Type (also known as MIME type and content type) is a two-part identifier for
// file formats and format contents transmitted on the Internet.
// For Hugo's use case, we use the top-level type name / subtype name + suffix.
// One example would be application/svg+xml
// If suffix is not provided, the sub type will be used.
// See // https://en.wikipedia.org/wiki/Media_type
type Type struct {
	MainType string `json:"mainType"` // i.e. text
	SubType  string `json:"subType"`  // i.e. html

	// This is the optional suffix after the "+" in the MIME type,
	//  e.g. "xml" in "applicatiion/rss+xml".
	mimeSuffix string

	Delimiter string `json:"delimiter"` // e.g. "."

	// TODO(bep) make this a string to make it hashable + method
	Suffixes []string `json:"suffixes"`

	// Set when doing lookup by suffix.
	fileSuffix string
}

// FromStringAndExt is same as FromString, but adds the file extension to the type.
func FromStringAndExt(t, ext string) (Type, error) {
	tp, err := fromString(t)
	if err != nil {
		return tp, err
	}
	tp.Suffixes = []string{strings.TrimPrefix(ext, ".")}
	return tp, nil
}

// FromString creates a new Type given a type string on the form MainType/SubType and
// an optional suffix, e.g. "text/html" or "text/html+html".
func fromString(t string) (Type, error) {
	t = strings.ToLower(t)
	parts := strings.Split(t, "/")
	if len(parts) != 2 {
		return Type{}, fmt.Errorf("cannot parse %q as a media type", t)
	}
	mainType := parts[0]
	subParts := strings.Split(parts[1], "+")

	subType := strings.Split(subParts[0], ";")[0]

	var suffix string

	if len(subParts) > 1 {
		suffix = subParts[1]
	}

	return Type{MainType: mainType, SubType: subType, mimeSuffix: suffix}, nil
}

// Type returns a string representing the main- and sub-type of a media type, e.g. "text/css".
// A suffix identifier will be appended after a "+" if set, e.g. "image/svg+xml".
// Hugo will register a set of default media types.
// These can be overridden by the user in the configuration,
// by defining a media type with the same Type.
func (m Type) Type() string {
	// Examples are
	// image/svg+xml
	// text/css
	if m.mimeSuffix != "" {
		return fmt.Sprintf("%s/%s+%s", m.MainType, m.SubType, m.mimeSuffix)
	}
	return fmt.Sprintf("%s/%s", m.MainType, m.SubType)

}

func (m Type) String() string {
	return m.Type()
}

// FullSuffix returns the file suffix with any delimiter prepended.
func (m Type) FullSuffix() string {
	return m.Delimiter + m.Suffix()
}

// Suffix returns the file suffix without any delmiter prepended.
func (m Type) Suffix() string {
	if m.fileSuffix != "" {
		return m.fileSuffix
	}
	if len(m.Suffixes) > 0 {
		return m.Suffixes[0]
	}
	// There are MIME types without file suffixes.
	return ""
}

// Definitions from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types etc.
// Note that from Hugo 0.44 we only set Suffix if it is part of the MIME type.
var (
	CalendarType   = Type{MainType: "text", SubType: "calendar", Suffixes: []string{"ics"}, Delimiter: defaultDelimiter}
	CSSType        = Type{MainType: "text", SubType: "css", Suffixes: []string{"css"}, Delimiter: defaultDelimiter}
	SCSSType       = Type{MainType: "text", SubType: "x-scss", Suffixes: []string{"scss"}, Delimiter: defaultDelimiter}
	SASSType       = Type{MainType: "text", SubType: "x-sass", Suffixes: []string{"sass"}, Delimiter: defaultDelimiter}
	CSVType        = Type{MainType: "text", SubType: "csv", Suffixes: []string{"csv"}, Delimiter: defaultDelimiter}
	HTMLType       = Type{MainType: "text", SubType: "html", Suffixes: []string{"html"}, Delimiter: defaultDelimiter}
	JavascriptType = Type{MainType: "application", SubType: "javascript", Suffixes: []string{"js"}, Delimiter: defaultDelimiter}
	JSONType       = Type{MainType: "application", SubType: "json", Suffixes: []string{"json"}, Delimiter: defaultDelimiter}
	RSSType        = Type{MainType: "application", SubType: "rss", mimeSuffix: "xml", Suffixes: []string{"xml"}, Delimiter: defaultDelimiter}
	XMLType        = Type{MainType: "application", SubType: "xml", Suffixes: []string{"xml"}, Delimiter: defaultDelimiter}
	SVGType        = Type{MainType: "image", SubType: "svg", mimeSuffix: "xml", Suffixes: []string{"svg"}, Delimiter: defaultDelimiter}
	TextType       = Type{MainType: "text", SubType: "plain", Suffixes: []string{"txt"}, Delimiter: defaultDelimiter}
	TOMLType       = Type{MainType: "application", SubType: "toml", Suffixes: []string{"toml"}, Delimiter: defaultDelimiter}
	YAMLType       = Type{MainType: "application", SubType: "yaml", Suffixes: []string{"yaml", "yml"}, Delimiter: defaultDelimiter}

	// Common image types
	PNGType  = Type{MainType: "image", SubType: "png", Suffixes: []string{"png"}, Delimiter: defaultDelimiter}
	JPGType  = Type{MainType: "image", SubType: "jpg", Suffixes: []string{"jpg", "jpeg"}, Delimiter: defaultDelimiter}
	GIFType  = Type{MainType: "image", SubType: "gif", Suffixes: []string{"gif"}, Delimiter: defaultDelimiter}
	TIFFType = Type{MainType: "image", SubType: "tiff", Suffixes: []string{"tif", "tiff"}, Delimiter: defaultDelimiter}
	BMPType  = Type{MainType: "image", SubType: "bmp", Suffixes: []string{"bmp"}, Delimiter: defaultDelimiter}

	OctetType = Type{MainType: "application", SubType: "octet-stream"}
)

// DefaultTypes is the default media types supported by Hugo.
var DefaultTypes = Types{
	CalendarType,
	CSSType,
	CSVType,
	SCSSType,
	SASSType,
	HTMLType,
	JavascriptType,
	JSONType,
	RSSType,
	XMLType,
	SVGType,
	TextType,
	OctetType,
	YAMLType,
	TOMLType,
	PNGType,
	JPGType,
}

func init() {
	sort.Sort(DefaultTypes)
}

// Types is a slice of media types.
type Types []Type

func (t Types) Len() int           { return len(t) }
func (t Types) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
func (t Types) Less(i, j int) bool { return t[i].Type() < t[j].Type() }

// GetByType returns a media type for tp.
func (t Types) GetByType(tp string) (Type, bool) {
	for _, tt := range t {
		if strings.EqualFold(tt.Type(), tp) {
			return tt, true
		}
	}

	if !strings.Contains(tp, "+") {
		// Try with the main and sub type
		parts := strings.Split(tp, "/")
		if len(parts) == 2 {
			return t.GetByMainSubType(parts[0], parts[1])
		}
	}

	return Type{}, false
}

// BySuffix will return all media types matching a suffix.
func (t Types) BySuffix(suffix string) []Type {
	var types []Type
	for _, tt := range t {
		if match := tt.matchSuffix(suffix); match != "" {
			types = append(types, tt)
		}
	}
	return types
}

// GetFirstBySuffix will return the first media type matching the given suffix.
func (t Types) GetFirstBySuffix(suffix string) (Type, bool) {
	for _, tt := range t {
		if match := tt.matchSuffix(suffix); match != "" {
			tt.fileSuffix = match
			return tt, true
		}
	}
	return Type{}, false
}

// GetBySuffix gets a media type given as suffix, e.g. "html".
// It will return false if no format could be found, or if the suffix given
// is ambiguous.
// The lookup is case insensitive.
func (t Types) GetBySuffix(suffix string) (tp Type, found bool) {
	for _, tt := range t {
		if match := tt.matchSuffix(suffix); match != "" {
			if found {
				// ambiguous
				found = false
				return
			}
			tp = tt
			tp.fileSuffix = match
			found = true
		}
	}
	return
}

func (m Type) matchSuffix(suffix string) string {
	for _, s := range m.Suffixes {
		if strings.EqualFold(suffix, s) {
			return s
		}
	}

	return ""
}

// GetByMainSubType gets a media type given a main and a sub type e.g. "text" and "plain".
// It will return false if no format could be found, or if the combination given
// is ambiguous.
// The lookup is case insensitive.
func (t Types) GetByMainSubType(mainType, subType string) (tp Type, found bool) {
	for _, tt := range t {
		if strings.EqualFold(mainType, tt.MainType) && strings.EqualFold(subType, tt.SubType) {
			if found {
				// ambiguous
				found = false
				return
			}

			tp = tt
			found = true
		}
	}
	return
}

func suffixIsRemoved() error {
	return errors.New(`MediaType.Suffix is removed. Before Hugo 0.44 this was used both to set a custom file suffix and as way
to augment the mediatype definition (what you see after the "+", e.g. "image/svg+xml").

This had its limitations. For one, it was only possible with one file extension per MIME type.

Now you can specify multiple file suffixes using "suffixes", but you need to specify the full MIME type
identifier:

[mediaTypes]
[mediaTypes."image/svg+xml"]
suffixes = ["svg", "abc" ]

In most cases, it will be enough to just change:

[mediaTypes]
[mediaTypes."my/custom-mediatype"]
suffix = "txt"

To:

[mediaTypes]
[mediaTypes."my/custom-mediatype"]
suffixes = ["txt"]

Note that you can still get the Media Type's suffix from a template: {{ $mediaType.Suffix }}. But this will now map to the MIME type filename.
`)
}

// DecodeTypes takes a list of media type configurations and merges those,
// in the order given, with the Hugo defaults as the last resort.
func DecodeTypes(mms ...map[string]interface{}) (Types, error) {
	var m Types

	// Maps type string to Type. Type string is the full application/svg+xml.
	mmm := make(map[string]Type)
	for _, dt := range DefaultTypes {
		suffixes := make([]string, len(dt.Suffixes))
		copy(suffixes, dt.Suffixes)
		dt.Suffixes = suffixes
		mmm[dt.Type()] = dt
	}

	for _, mm := range mms {
		for k, v := range mm {
			var mediaType Type

			mediaType, found := mmm[k]
			if !found {
				var err error
				mediaType, err = fromString(k)
				if err != nil {
					return m, err
				}
			}

			if err := mapstructure.WeakDecode(v, &mediaType); err != nil {
				return m, err
			}

			vm := v.(map[string]interface{})
			maps.ToLower(vm)
			_, delimiterSet := vm["delimiter"]
			_, suffixSet := vm["suffix"]

			if suffixSet {
				return Types{}, suffixIsRemoved()
			}

			// The user may set the delimiter as an empty string.
			if !delimiterSet && len(mediaType.Suffixes) != 0 {
				mediaType.Delimiter = defaultDelimiter
			}

			mmm[k] = mediaType

		}
	}

	for _, v := range mmm {
		m = append(m, v)
	}
	sort.Sort(m)

	return m, nil
}

// MarshalJSON returns the JSON encoding of m.
func (m Type) MarshalJSON() ([]byte, error) {
	type Alias Type
	return json.Marshal(&struct {
		Type   string `json:"type"`
		String string `json:"string"`
		Alias
	}{
		Type:   m.Type(),
		String: m.String(),
		Alias:  (Alias)(m),
	})
}
<commit_msg>media: Use + to create the Type string<commit_after>// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package media

import (
	"encoding/json"
	"errors"
	"fmt"
	"sort"
	"strings"

	"github.com/gohugoio/hugo/common/maps"

	"github.com/mitchellh/mapstructure"
)

const (
	defaultDelimiter = "."
)

// Type (also known as MIME type and content type) is a two-part identifier for
// file formats and format contents transmitted on the Internet.
// For Hugo's use case, we use the top-level type name / subtype name + suffix.
// One example would be application/svg+xml
// If suffix is not provided, the sub type will be used.
// See // https://en.wikipedia.org/wiki/Media_type
type Type struct {
	MainType string `json:"mainType"` // i.e. text
	SubType  string `json:"subType"`  // i.e. html

	// This is the optional suffix after the "+" in the MIME type,
	//  e.g. "xml" in "applicatiion/rss+xml".
	mimeSuffix string

	Delimiter string `json:"delimiter"` // e.g. "."

	// TODO(bep) make this a string to make it hashable + method
	Suffixes []string `json:"suffixes"`

	// Set when doing lookup by suffix.
	fileSuffix string
}

// FromStringAndExt is same as FromString, but adds the file extension to the type.
func FromStringAndExt(t, ext string) (Type, error) {
	tp, err := fromString(t)
	if err != nil {
		return tp, err
	}
	tp.Suffixes = []string{strings.TrimPrefix(ext, ".")}
	return tp, nil
}

// FromString creates a new Type given a type string on the form MainType/SubType and
// an optional suffix, e.g. "text/html" or "text/html+html".
func fromString(t string) (Type, error) {
	t = strings.ToLower(t)
	parts := strings.Split(t, "/")
	if len(parts) != 2 {
		return Type{}, fmt.Errorf("cannot parse %q as a media type", t)
	}
	mainType := parts[0]
	subParts := strings.Split(parts[1], "+")

	subType := strings.Split(subParts[0], ";")[0]

	var suffix string

	if len(subParts) > 1 {
		suffix = subParts[1]
	}

	return Type{MainType: mainType, SubType: subType, mimeSuffix: suffix}, nil
}

// Type returns a string representing the main- and sub-type of a media type, e.g. "text/css".
// A suffix identifier will be appended after a "+" if set, e.g. "image/svg+xml".
// Hugo will register a set of default media types.
// These can be overridden by the user in the configuration,
// by defining a media type with the same Type.
func (m Type) Type() string {
	// Examples are
	// image/svg+xml
	// text/css
	if m.mimeSuffix != "" {
		return m.MainType + "/" + m.SubType + "+" + m.mimeSuffix
	}
	return m.MainType + "/" + m.SubType
}

func (m Type) String() string {
	return m.Type()
}

// FullSuffix returns the file suffix with any delimiter prepended.
func (m Type) FullSuffix() string {
	return m.Delimiter + m.Suffix()
}

// Suffix returns the file suffix without any delmiter prepended.
func (m Type) Suffix() string {
	if m.fileSuffix != "" {
		return m.fileSuffix
	}
	if len(m.Suffixes) > 0 {
		return m.Suffixes[0]
	}
	// There are MIME types without file suffixes.
	return ""
}

// Definitions from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types etc.
// Note that from Hugo 0.44 we only set Suffix if it is part of the MIME type.
var (
	CalendarType   = Type{MainType: "text", SubType: "calendar", Suffixes: []string{"ics"}, Delimiter: defaultDelimiter}
	CSSType        = Type{MainType: "text", SubType: "css", Suffixes: []string{"css"}, Delimiter: defaultDelimiter}
	SCSSType       = Type{MainType: "text", SubType: "x-scss", Suffixes: []string{"scss"}, Delimiter: defaultDelimiter}
	SASSType       = Type{MainType: "text", SubType: "x-sass", Suffixes: []string{"sass"}, Delimiter: defaultDelimiter}
	CSVType        = Type{MainType: "text", SubType: "csv", Suffixes: []string{"csv"}, Delimiter: defaultDelimiter}
	HTMLType       = Type{MainType: "text", SubType: "html", Suffixes: []string{"html"}, Delimiter: defaultDelimiter}
	JavascriptType = Type{MainType: "application", SubType: "javascript", Suffixes: []string{"js"}, Delimiter: defaultDelimiter}
	JSONType       = Type{MainType: "application", SubType: "json", Suffixes: []string{"json"}, Delimiter: defaultDelimiter}
	RSSType        = Type{MainType: "application", SubType: "rss", mimeSuffix: "xml", Suffixes: []string{"xml"}, Delimiter: defaultDelimiter}
	XMLType        = Type{MainType: "application", SubType: "xml", Suffixes: []string{"xml"}, Delimiter: defaultDelimiter}
	SVGType        = Type{MainType: "image", SubType: "svg", mimeSuffix: "xml", Suffixes: []string{"svg"}, Delimiter: defaultDelimiter}
	TextType       = Type{MainType: "text", SubType: "plain", Suffixes: []string{"txt"}, Delimiter: defaultDelimiter}
	TOMLType       = Type{MainType: "application", SubType: "toml", Suffixes: []string{"toml"}, Delimiter: defaultDelimiter}
	YAMLType       = Type{MainType: "application", SubType: "yaml", Suffixes: []string{"yaml", "yml"}, Delimiter: defaultDelimiter}

	// Common image types
	PNGType  = Type{MainType: "image", SubType: "png", Suffixes: []string{"png"}, Delimiter: defaultDelimiter}
	JPGType  = Type{MainType: "image", SubType: "jpg", Suffixes: []string{"jpg", "jpeg"}, Delimiter: defaultDelimiter}
	GIFType  = Type{MainType: "image", SubType: "gif", Suffixes: []string{"gif"}, Delimiter: defaultDelimiter}
	TIFFType = Type{MainType: "image", SubType: "tiff", Suffixes: []string{"tif", "tiff"}, Delimiter: defaultDelimiter}
	BMPType  = Type{MainType: "image", SubType: "bmp", Suffixes: []string{"bmp"}, Delimiter: defaultDelimiter}

	OctetType = Type{MainType: "application", SubType: "octet-stream"}
)

// DefaultTypes is the default media types supported by Hugo.
var DefaultTypes = Types{
	CalendarType,
	CSSType,
	CSVType,
	SCSSType,
	SASSType,
	HTMLType,
	JavascriptType,
	JSONType,
	RSSType,
	XMLType,
	SVGType,
	TextType,
	OctetType,
	YAMLType,
	TOMLType,
	PNGType,
	JPGType,
}

func init() {
	sort.Sort(DefaultTypes)
}

// Types is a slice of media types.
type Types []Type

func (t Types) Len() int           { return len(t) }
func (t Types) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
func (t Types) Less(i, j int) bool { return t[i].Type() < t[j].Type() }

// GetByType returns a media type for tp.
func (t Types) GetByType(tp string) (Type, bool) {
	for _, tt := range t {
		if strings.EqualFold(tt.Type(), tp) {
			return tt, true
		}
	}

	if !strings.Contains(tp, "+") {
		// Try with the main and sub type
		parts := strings.Split(tp, "/")
		if len(parts) == 2 {
			return t.GetByMainSubType(parts[0], parts[1])
		}
	}

	return Type{}, false
}

// BySuffix will return all media types matching a suffix.
func (t Types) BySuffix(suffix string) []Type {
	var types []Type
	for _, tt := range t {
		if match := tt.matchSuffix(suffix); match != "" {
			types = append(types, tt)
		}
	}
	return types
}

// GetFirstBySuffix will return the first media type matching the given suffix.
func (t Types) GetFirstBySuffix(suffix string) (Type, bool) {
	for _, tt := range t {
		if match := tt.matchSuffix(suffix); match != "" {
			tt.fileSuffix = match
			return tt, true
		}
	}
	return Type{}, false
}

// GetBySuffix gets a media type given as suffix, e.g. "html".
// It will return false if no format could be found, or if the suffix given
// is ambiguous.
// The lookup is case insensitive.
func (t Types) GetBySuffix(suffix string) (tp Type, found bool) {
	for _, tt := range t {
		if match := tt.matchSuffix(suffix); match != "" {
			if found {
				// ambiguous
				found = false
				return
			}
			tp = tt
			tp.fileSuffix = match
			found = true
		}
	}
	return
}

func (m Type) matchSuffix(suffix string) string {
	for _, s := range m.Suffixes {
		if strings.EqualFold(suffix, s) {
			return s
		}
	}

	return ""
}

// GetByMainSubType gets a media type given a main and a sub type e.g. "text" and "plain".
// It will return false if no format could be found, or if the combination given
// is ambiguous.
// The lookup is case insensitive.
func (t Types) GetByMainSubType(mainType, subType string) (tp Type, found bool) {
	for _, tt := range t {
		if strings.EqualFold(mainType, tt.MainType) && strings.EqualFold(subType, tt.SubType) {
			if found {
				// ambiguous
				found = false
				return
			}

			tp = tt
			found = true
		}
	}
	return
}

func suffixIsRemoved() error {
	return errors.New(`MediaType.Suffix is removed. Before Hugo 0.44 this was used both to set a custom file suffix and as way
to augment the mediatype definition (what you see after the "+", e.g. "image/svg+xml").

This had its limitations. For one, it was only possible with one file extension per MIME type.

Now you can specify multiple file suffixes using "suffixes", but you need to specify the full MIME type
identifier:

[mediaTypes]
[mediaTypes."image/svg+xml"]
suffixes = ["svg", "abc" ]

In most cases, it will be enough to just change:

[mediaTypes]
[mediaTypes."my/custom-mediatype"]
suffix = "txt"

To:

[mediaTypes]
[mediaTypes."my/custom-mediatype"]
suffixes = ["txt"]

Note that you can still get the Media Type's suffix from a template: {{ $mediaType.Suffix }}. But this will now map to the MIME type filename.
`)
}

// DecodeTypes takes a list of media type configurations and merges those,
// in the order given, with the Hugo defaults as the last resort.
func DecodeTypes(mms ...map[string]interface{}) (Types, error) {
	var m Types

	// Maps type string to Type. Type string is the full application/svg+xml.
	mmm := make(map[string]Type)
	for _, dt := range DefaultTypes {
		suffixes := make([]string, len(dt.Suffixes))
		copy(suffixes, dt.Suffixes)
		dt.Suffixes = suffixes
		mmm[dt.Type()] = dt
	}

	for _, mm := range mms {
		for k, v := range mm {
			var mediaType Type

			mediaType, found := mmm[k]
			if !found {
				var err error
				mediaType, err = fromString(k)
				if err != nil {
					return m, err
				}
			}

			if err := mapstructure.WeakDecode(v, &mediaType); err != nil {
				return m, err
			}

			vm := v.(map[string]interface{})
			maps.ToLower(vm)
			_, delimiterSet := vm["delimiter"]
			_, suffixSet := vm["suffix"]

			if suffixSet {
				return Types{}, suffixIsRemoved()
			}

			// The user may set the delimiter as an empty string.
			if !delimiterSet && len(mediaType.Suffixes) != 0 {
				mediaType.Delimiter = defaultDelimiter
			}

			mmm[k] = mediaType

		}
	}

	for _, v := range mmm {
		m = append(m, v)
	}
	sort.Sort(m)

	return m, nil
}

// MarshalJSON returns the JSON encoding of m.
func (m Type) MarshalJSON() ([]byte, error) {
	type Alias Type
	return json.Marshal(&struct {
		Type   string `json:"type"`
		String string `json:"string"`
		Alias
	}{
		Type:   m.Type(),
		String: m.String(),
		Alias:  (Alias)(m),
	})
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"errors"
	"fmt"
	"github.com/mavricknz/ldap"
	"net/url"
	"strconv"
	"strings"
)

func ldapHost() *url.URL {
	_url, err := url.Parse(Config.LdapServer)
	perror(err)
	return _url
}

func NewLdapConnection() *ldap.LDAPConnection {
	lh := ldapHost()
	hoster := strings.Split(lh.Host, ":")
	port := func() uint16 {
		if len(hoster) < 2 {
			return uint16(389)
		} else {
			var e error
			port, e := strconv.Atoi(hoster[1])
			if e != nil {
				panic(e)
			}
			return uint16(port)
		}
	}
	var ldapCon *ldap.LDAPConnection
	if strings.Contains(lh.String(), "ldaps") {
		ldapCon = ldap.NewLDAPSSLConnection(hoster[0], port(), &tls.Config{InsecureSkipVerify: true})
	} else {
		ldapCon = ldap.NewLDAPConnection(hoster[0], port())
	}
	err := ldapCon.Connect()
	perror(err)
	return ldapCon
}

func LdapSearch(search *ldap.SearchRequest) (*ldap.SearchResult, error) {
	ldapCon := NewLdapConnection()
	s, er := ldapCon.Search(search)
	defer ldapCon.Close()
	if er != nil {
		logger.Log(kv{"fn": "meta_store_auth.LdapSearch", "msg": fmt.Sprintf("LDAP ERR: %S", er.Error())})
		return nil, er
	}
	if s == nil {
		return nil, errNoLdapSearchResults
	}
	s.String()
	return s, er
}

// boolean bind request
func LdapBind(user string, password string) bool {
	ldapCon := NewLdapConnection()
	reqE := ldapCon.Bind(user, password)
	defer ldapCon.Close()
	resp := false
	if reqE == nil {
		resp = true
	}
	return resp
}

// authenticate uses the authorization string to determine whether
// or not to proceed. This server assumes an HTTP Basic auth format.
func authenticateLdap(user, password string) bool {
	dn, err := findUserDn(user)
	if err != nil {
		logger.Log(kv{"fn": "meta_store_auth", "msg": fmt.Sprintf("LDAP ERR: %S", err.Error())})
		return false
	}
	return LdapBind(dn, password)
}

func findUserDn(user string) (string, error) {
	fltr := fmt.Sprintf("(&(objectClass=%s)(%s=%s))", Config.LdapUserObjectClass, Config.LdapUserCn, user)
//	m := fmt.Sprintf("LDAP Search Host '%s' Filter '%s' base '%s'\n", ldapHost().String(), fltr, Config.LdapBase)
//	logger.Log(kv{"fn": "meta_store_auth.findUserDn", "msg": m})
	base := fmt.Sprintf("%s=%s,%s", Config.LdapUserCn, user, Config.LdapBase)
	search := &ldap.SearchRequest{
		BaseDN: base,
		Filter: fltr,
	}
	r, err := LdapSearch(search)
	if err != nil {
		logger.Log(kv{"fn": "meta_store_auth.findUserDn", "msg_error": err.Error()})
		return "", err
	}
	if len(r.Entries) > 0 {
//		logger.Log(kv{"fn": "meta_store_auth.findUserDn", "Found DN": r.Entries[0].DN})
		return r.Entries[0].DN, nil
	}
	return "", errLdapUsertNotFound
}

type authError struct {
	error
}

func (e authError) AuthError() bool {
	return true
}

func newAuthError() error {
	return authError{errors.New("Forbidden")}
}
<commit_msg>format code<commit_after>package main

import (
	"crypto/tls"
	"errors"
	"fmt"
	"github.com/mavricknz/ldap"
	"net/url"
	"strconv"
	"strings"
)

func ldapHost() *url.URL {
	_url, err := url.Parse(Config.LdapServer)
	perror(err)
	return _url
}

func NewLdapConnection() *ldap.LDAPConnection {
	lh := ldapHost()
	hoster := strings.Split(lh.Host, ":")
	port := func() uint16 {
		if len(hoster) < 2 {
			return uint16(389)
		} else {
			var e error
			port, e := strconv.Atoi(hoster[1])
			if e != nil {
				panic(e)
			}
			return uint16(port)
		}
	}
	var ldapCon *ldap.LDAPConnection
	if strings.Contains(lh.String(), "ldaps") {
		ldapCon = ldap.NewLDAPSSLConnection(hoster[0], port(), &tls.Config{InsecureSkipVerify: true})
	} else {
		ldapCon = ldap.NewLDAPConnection(hoster[0], port())
	}
	err := ldapCon.Connect()
	perror(err)
	return ldapCon
}

func LdapSearch(search *ldap.SearchRequest) (*ldap.SearchResult, error) {
	ldapCon := NewLdapConnection()
	s, er := ldapCon.Search(search)
	defer ldapCon.Close()
	if er != nil {
		logger.Log(kv{"fn": "meta_store_auth.LdapSearch", "msg": fmt.Sprintf("LDAP ERR: %S", er.Error())})
		return nil, er
	}
	if s == nil {
		return nil, errNoLdapSearchResults
	}
	s.String()
	return s, er
}

// boolean bind request
func LdapBind(user string, password string) bool {
	ldapCon := NewLdapConnection()
	reqE := ldapCon.Bind(user, password)
	defer ldapCon.Close()
	resp := false
	if reqE == nil {
		resp = true
	}
	return resp
}

// authenticate uses the authorization string to determine whether
// or not to proceed. This server assumes an HTTP Basic auth format.
func authenticateLdap(user, password string) bool {
	dn, err := findUserDn(user)
	if err != nil {
		logger.Log(kv{"fn": "meta_store_auth", "msg": fmt.Sprintf("LDAP ERR: %S", err.Error())})
		return false
	}
	return LdapBind(dn, password)
}

func findUserDn(user string) (string, error) {
	fltr := fmt.Sprintf("(&(objectClass=%s)(%s=%s))", Config.LdapUserObjectClass, Config.LdapUserCn, user)
	//	m := fmt.Sprintf("LDAP Search Host '%s' Filter '%s' base '%s'\n", ldapHost().String(), fltr, Config.LdapBase)
	//	logger.Log(kv{"fn": "meta_store_auth.findUserDn", "msg": m})
	base := fmt.Sprintf("%s=%s,%s", Config.LdapUserCn, user, Config.LdapBase)
	search := &ldap.SearchRequest{
		BaseDN: base,
		Filter: fltr,
	}
	r, err := LdapSearch(search)
	if err != nil {
		logger.Log(kv{"fn": "meta_store_auth.findUserDn", "msg_error": err.Error()})
		return "", err
	}
	if len(r.Entries) > 0 {
		//		logger.Log(kv{"fn": "meta_store_auth.findUserDn", "Found DN": r.Entries[0].DN})
		return r.Entries[0].DN, nil
	}
	return "", errLdapUsertNotFound
}

type authError struct {
	error
}

func (e authError) AuthError() bool {
	return true
}

func newAuthError() error {
	return authError{errors.New("Forbidden")}
}
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 project

import (
	"fmt"

	"github.com/spf13/cobra"
	"mynewt.apache.org/newt/newt/cli"
	"mynewt.apache.org/newt/newt/interfaces"
)

var Force bool = false

func installRunCmd(cmd *cobra.Command, args []string) {
	proj := GetProject()
	interfaces.SetProject(proj)

	if err := proj.Install(false, Force); err != nil {
		cli.NewtUsage(cmd, err)
	}

	fmt.Println("Repos successfully installed")
}

func upgradeRunCmd(cmd *cobra.Command, args []string) {
	proj := GetProject()
	interfaces.SetProject(proj)

	if err := proj.Upgrade(Force); err != nil {
		cli.NewtUsage(cmd, err)
	}

	fmt.Println("Repos successfully upgrade")
}

func AddCommands(cmd *cobra.Command) {
	installHelpText := ""
	installHelpEx := ""
	installCmd := &cobra.Command{
		Use:     "install",
		Short:   "Command to install project dependencies",
		Long:    installHelpText,
		Example: installHelpEx,
		Run:     installRunCmd,
	}
	installCmd.PersistentFlags().BoolVarP(&Force, "force", "f", false,
		"Force install of the repositories in project, regardless of what "+
			"exists in repos directory")

	cmd.AddCommand(installCmd)

	upgradeHelpText := ""
	upgradeHelpEx := ""
	upgradeCmd := &cobra.Command{
		Use:     "upgrade",
		Short:   "Command to upgrade project dependencies",
		Long:    upgradeHelpText,
		Example: upgradeHelpEx,
		Run:     upgradeRunCmd,
	}
	upgradeCmd.PersistentFlags().BoolVarP(&Force, "force", "f", false,
		"Force upgrade of the repositories to latest state in project.yml")

	cmd.AddCommand(upgradeCmd)

}
<commit_msg>pretty up the help a little<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 project

import (
	"fmt"

	"github.com/spf13/cobra"
	"mynewt.apache.org/newt/newt/cli"
	"mynewt.apache.org/newt/newt/interfaces"
)

var Force bool = false

func installRunCmd(cmd *cobra.Command, args []string) {
	proj := GetProject()
	interfaces.SetProject(proj)

	if err := proj.Install(false, Force); err != nil {
		cli.NewtUsage(cmd, err)
	}

	fmt.Println("Repos successfully installed")
}

func upgradeRunCmd(cmd *cobra.Command, args []string) {
	proj := GetProject()
	interfaces.SetProject(proj)

	if err := proj.Upgrade(Force); err != nil {
		cli.NewtUsage(cmd, err)
	}

	fmt.Println("Repos successfully upgrade")
}

func AddCommands(cmd *cobra.Command) {
	installHelpText := ""
	installHelpEx := ""
	installCmd := &cobra.Command{
		Use:     "install",
		Short:   "Install project dependencies",
		Long:    installHelpText,
		Example: installHelpEx,
		Run:     installRunCmd,
	}
	installCmd.PersistentFlags().BoolVarP(&Force, "force", "f", false,
		"Force install of the repositories in project, regardless of what "+
			"exists in repos directory")

	cmd.AddCommand(installCmd)

	upgradeHelpText := ""
	upgradeHelpEx := ""
	upgradeCmd := &cobra.Command{
		Use:     "upgrade",
		Short:   "Upgrade project dependencies",
		Long:    upgradeHelpText,
		Example: upgradeHelpEx,
		Run:     upgradeRunCmd,
	}
	upgradeCmd.PersistentFlags().BoolVarP(&Force, "force", "f", false,
		"Force upgrade of the repositories to latest state in project.yml")

	cmd.AddCommand(upgradeCmd)

}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"

	"camlistore.org/third_party/code.google.com/p/goauth2/oauth"
	compute "camlistore.org/third_party/code.google.com/p/google-api-go-client/compute/v1"
	storage "camlistore.org/third_party/code.google.com/p/google-api-go-client/storage/v1"
)

var (
	proj     = flag.String("project", "", "name of Project")
	zone     = flag.String("zone", "us-central1-a", "GCE zone")
	mach     = flag.String("machinetype", "g1-small", "e.g. n1-standard-1, f1-micro, g1-small")
	instance = flag.String("instance_name", "camlistore-server", "Name of VM instance.")
	sshPub   = flag.String("ssh_public_key", "", "ssh public key file to authorize. Can modify later in Google's web UI anyway.")
)

func readFile(v string) string {
	slurp, err := ioutil.ReadFile(v)
	if err != nil {
		log.Fatalf("Error reading %s: %v", v, err)
	}
	return strings.TrimSpace(string(slurp))
}

var config = &oauth.Config{
	// The client-id and secret should be for an "Installed Application" when using
	// the CLI. Later we'll use a web application with a callback.
	ClientId:     readFile("client-id.dat"),
	ClientSecret: readFile("client-secret.dat"),
	Scope: strings.Join([]string{
		compute.DevstorageFull_controlScope,
		compute.ComputeScope,
		"https://www.googleapis.com/auth/sqlservice",
		"https://www.googleapis.com/auth/sqlservice.admin",
	}, " "),
	AuthURL:     "https://accounts.google.com/o/oauth2/auth",
	TokenURL:    "https://accounts.google.com/o/oauth2/token",
	RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
}

func main() {
	flag.Parse()
	if *proj == "" {
		log.Fatalf("Missing --project flag")
	}
	prefix := "https://www.googleapis.com/compute/v1/projects/" + *proj
	imageURL := "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-alpha-402-2-0-v20140807"
	machType := prefix + "/zones/" + *zone + "/machineTypes/" + *mach

	tr := &oauth.Transport{
		Config: config,
	}

	cloudConfig := `#cloud-config
coreos:
  units:
    - name: systemd-journal-gatewayd.socket
      command: start
      enable: true
    - name: cam-journal-gatewayd.service
      content: |
        [Unit]
        Description=Journal Gateway Service
        Requires=cam-journal-gatewayd.socket

        [Service]
        ExecStart=/usr/lib/systemd/systemd-journal-gatewayd
        User=systemd-journal-gateway
        Group=systemd-journal-gateway
        SupplementaryGroups=systemd-journal
        PrivateTmp=yes
        PrivateDevices=yes
        PrivateNetwork=yes
        ProtectSystem=full
        ProtectHome=yes

        [Install]
        Also=cam-journal-gatewayd.socket
    - name: cam-journal-gatewayd.socket
      command: start
      content: |
        [Unit]
        Description=Journal Gateway Service Socket

        [Socket]
        ListenStream=/run/camjournald.sock

        [Install]
        WantedBy=sockets.target
    - name: camlistored.service
      command: start
      content: |
        [Unit]
        Description=Camlistore
        After=docker.service
        Requires=docker.service

        [Service]
        ExecStart=/usr/bin/docker run -p 80:80 -p 443:443 -v /run/camjournald.sock:/run/camjournald.sock camlistore/camlistored
        RestartSec=500ms
        Restart=always

        [Install]
        WantedBy=multi-user.target
`

	if *sshPub != "" {
		key := strings.TrimSpace(readFile(*sshPub))
		cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n    - %s\n", key)
	}

	tokenCache := oauth.CacheFile("token.dat")
	token, err := tokenCache.Token()
	if err != nil {
		log.Printf("Error getting token from %s: %v", string(tokenCache), err)
		log.Printf("Get auth code from %v", config.AuthCodeURL("my-state"))
		os.Stdout.Write([]byte("\nEnter auth code: "))
		sc := bufio.NewScanner(os.Stdin)
		sc.Scan()
		authCode := strings.TrimSpace(sc.Text())
		token, err = tr.Exchange(authCode)
		if err != nil {
			log.Fatalf("Error exchanging auth code for a token: %v", err)
		}
		tokenCache.PutToken(token)
	}

	tr.Token = token
	computeService, _ := compute.New(&http.Client{Transport: tr})
	storageService, _ := storage.New(&http.Client{Transport: tr})

	blobBucket := *proj + "-camlistore-blobs"
	configBucket := *proj + "-camlistore-config"
	needBucket := map[string]bool{
		blobBucket:   true,
		configBucket: true,
	}

	buckets, err := storageService.Buckets.List(*proj).Do()
	if err != nil {
		log.Fatalf("Error listing buckets: %v", err)
	}
	for _, it := range buckets.Items {
		delete(needBucket, it.Name)
	}
	if len(needBucket) > 0 {
		log.Printf("Need to create buckets: %v", needBucket)
		var waitBucket sync.WaitGroup
		for name := range needBucket {
			name := name
			waitBucket.Add(1)
			go func() {
				defer waitBucket.Done()
				log.Printf("Creating bucket %s", name)
				b, err := storageService.Buckets.Insert(*proj, &storage.Bucket{
					Id:   name,
					Name: name,
				}).Do()
				if err != nil {
					log.Fatalf("Error creating bucket %s: %v", name, err)
				}
				log.Printf("Created bucket %s: %+v", name, b)
			}()
		}
		waitBucket.Wait()
	}

	instance := &compute.Instance{
		Name:        *instance,
		Description: "Camlistore server",
		MachineType: machType,
		Disks: []*compute.AttachedDisk{
			{
				AutoDelete: true,
				Boot:       true,
				Type:       "PERSISTENT",
				InitializeParams: &compute.AttachedDiskInitializeParams{
					DiskName:    *instance + "-coreos-stateless-pd",
					SourceImage: imageURL,
				},
			},
		},
		Tags: &compute.Tags{
			Items: []string{"http-server", "https-server"},
		},
		Metadata: &compute.Metadata{
			Items: []*compute.MetadataItems{
				{
					Key:   "camlistore-username",
					Value: "test",
				},
				{
					Key:   "camlistore-password",
					Value: "insecure", // TODO: this won't be cleartext later
				},
				{
					Key:   "camlistore-blob-bucket",
					Value: "gs://" + blobBucket,
				},
				{
					Key:   "camlistore-config-bucket",
					Value: "gs://" + configBucket,
				},
				{
					Key:   "user-data",
					Value: cloudConfig,
				},
			},
		},
		NetworkInterfaces: []*compute.NetworkInterface{
			&compute.NetworkInterface{
				AccessConfigs: []*compute.AccessConfig{
					&compute.AccessConfig{
						Type: "ONE_TO_ONE_NAT",
						Name: "External NAT",
					},
				},
				Network: prefix + "/global/networks/default",
			},
		},
		ServiceAccounts: []*compute.ServiceAccount{
			{
				Email: "default",
				Scopes: []string{
					compute.DevstorageFull_controlScope,
					compute.ComputeScope,
					"https://www.googleapis.com/auth/sqlservice",
					"https://www.googleapis.com/auth/sqlservice.admin",
				},
			},
		},
	}
	const localMySQL = false // later
	if localMySQL {
		instance.Disks = append(instance.Disks, &compute.AttachedDisk{
			AutoDelete: false,
			Boot:       false,
			Type:       "PERSISTENT",
			InitializeParams: &compute.AttachedDiskInitializeParams{
				DiskName:   "camlistore-mysql-index-pd",
				DiskSizeGb: 4,
			},
		})
	}

	log.Printf("Creating instance...")
	op, err := computeService.Instances.Insert(*proj, *zone, instance).Do()
	if err != nil {
		log.Fatalf("Failed to create instance: %v", err)
	}
	opName := op.Name
	log.Printf("Created. Waiting on operation %v", opName)
	for {
		time.Sleep(2 * time.Second)
		op, err := computeService.ZoneOperations.Get(*proj, *zone, opName).Do()
		if err != nil {
			log.Fatalf("Failed to get op %s: %v", opName, err)
		}
		switch op.Status {
		case "PENDING", "RUNNING":
			log.Printf("Waiting on operation %v", opName)
			continue
		case "DONE":
			if op.Error != nil {
				for _, operr := range op.Error.Errors {
					log.Printf("Error: %+v", operr)
				}
				log.Fatalf("Failed to start.")
			}
			log.Printf("Success. %+v", op)
			return
		default:
			log.Fatalf("Unknown status %q: %+v", op.Status, op)
		}
	}
}
<commit_msg>GCE: use host's /tmp dir instead of inside container.<commit_after>package main

import (
	"bufio"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"

	"camlistore.org/third_party/code.google.com/p/goauth2/oauth"
	compute "camlistore.org/third_party/code.google.com/p/google-api-go-client/compute/v1"
	storage "camlistore.org/third_party/code.google.com/p/google-api-go-client/storage/v1"
)

var (
	proj     = flag.String("project", "", "name of Project")
	zone     = flag.String("zone", "us-central1-a", "GCE zone")
	mach     = flag.String("machinetype", "g1-small", "e.g. n1-standard-1, f1-micro, g1-small")
	instance = flag.String("instance_name", "camlistore-server", "Name of VM instance.")
	sshPub   = flag.String("ssh_public_key", "", "ssh public key file to authorize. Can modify later in Google's web UI anyway.")
)

func readFile(v string) string {
	slurp, err := ioutil.ReadFile(v)
	if err != nil {
		log.Fatalf("Error reading %s: %v", v, err)
	}
	return strings.TrimSpace(string(slurp))
}

var config = &oauth.Config{
	// The client-id and secret should be for an "Installed Application" when using
	// the CLI. Later we'll use a web application with a callback.
	ClientId:     readFile("client-id.dat"),
	ClientSecret: readFile("client-secret.dat"),
	Scope: strings.Join([]string{
		compute.DevstorageFull_controlScope,
		compute.ComputeScope,
		"https://www.googleapis.com/auth/sqlservice",
		"https://www.googleapis.com/auth/sqlservice.admin",
	}, " "),
	AuthURL:     "https://accounts.google.com/o/oauth2/auth",
	TokenURL:    "https://accounts.google.com/o/oauth2/token",
	RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
}

func main() {
	flag.Parse()
	if *proj == "" {
		log.Fatalf("Missing --project flag")
	}
	prefix := "https://www.googleapis.com/compute/v1/projects/" + *proj
	imageURL := "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-alpha-402-2-0-v20140807"
	machType := prefix + "/zones/" + *zone + "/machineTypes/" + *mach

	tr := &oauth.Transport{
		Config: config,
	}

	cloudConfig := `#cloud-config
write_files:
  - path: /tmp/camlistore-tmp/README
    permissions: 0644
    content: |
      This is the Camlistore /tmp directory.
coreos:
  units:
    - name: systemd-journal-gatewayd.socket
      command: start
      enable: true
    - name: cam-journal-gatewayd.service
      content: |
        [Unit]
        Description=Journal Gateway Service
        Requires=cam-journal-gatewayd.socket

        [Service]
        ExecStart=/usr/lib/systemd/systemd-journal-gatewayd
        User=systemd-journal-gateway
        Group=systemd-journal-gateway
        SupplementaryGroups=systemd-journal
        PrivateTmp=yes
        PrivateDevices=yes
        PrivateNetwork=yes
        ProtectSystem=full
        ProtectHome=yes

        [Install]
        Also=cam-journal-gatewayd.socket
    - name: cam-journal-gatewayd.socket
      command: start
      content: |
        [Unit]
        Description=Journal Gateway Service Socket

        [Socket]
        ListenStream=/run/camjournald.sock

        [Install]
        WantedBy=sockets.target
    - name: camlistored.service
      command: start
      content: |
        [Unit]
        Description=Camlistore
        After=docker.service
        Requires=docker.service

        [Service]
        ExecStart=/usr/bin/docker run -p 80:80 -p 443:443 -v /run/camjournald.sock:/run/camjournald.sock -v /tmp/camlistore-tmp:/tmp camlistore/camlistored
        RestartSec=500ms
        Restart=always

        [Install]
        WantedBy=multi-user.target
`

	if *sshPub != "" {
		key := strings.TrimSpace(readFile(*sshPub))
		cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n    - %s\n", key)
	}

	tokenCache := oauth.CacheFile("token.dat")
	token, err := tokenCache.Token()
	if err != nil {
		log.Printf("Error getting token from %s: %v", string(tokenCache), err)
		log.Printf("Get auth code from %v", config.AuthCodeURL("my-state"))
		os.Stdout.Write([]byte("\nEnter auth code: "))
		sc := bufio.NewScanner(os.Stdin)
		sc.Scan()
		authCode := strings.TrimSpace(sc.Text())
		token, err = tr.Exchange(authCode)
		if err != nil {
			log.Fatalf("Error exchanging auth code for a token: %v", err)
		}
		tokenCache.PutToken(token)
	}

	tr.Token = token
	computeService, _ := compute.New(&http.Client{Transport: tr})
	storageService, _ := storage.New(&http.Client{Transport: tr})

	blobBucket := *proj + "-camlistore-blobs"
	configBucket := *proj + "-camlistore-config"
	needBucket := map[string]bool{
		blobBucket:   true,
		configBucket: true,
	}

	buckets, err := storageService.Buckets.List(*proj).Do()
	if err != nil {
		log.Fatalf("Error listing buckets: %v", err)
	}
	for _, it := range buckets.Items {
		delete(needBucket, it.Name)
	}
	if len(needBucket) > 0 {
		log.Printf("Need to create buckets: %v", needBucket)
		var waitBucket sync.WaitGroup
		for name := range needBucket {
			name := name
			waitBucket.Add(1)
			go func() {
				defer waitBucket.Done()
				log.Printf("Creating bucket %s", name)
				b, err := storageService.Buckets.Insert(*proj, &storage.Bucket{
					Id:   name,
					Name: name,
				}).Do()
				if err != nil {
					log.Fatalf("Error creating bucket %s: %v", name, err)
				}
				log.Printf("Created bucket %s: %+v", name, b)
			}()
		}
		waitBucket.Wait()
	}

	instance := &compute.Instance{
		Name:        *instance,
		Description: "Camlistore server",
		MachineType: machType,
		Disks: []*compute.AttachedDisk{
			{
				AutoDelete: true,
				Boot:       true,
				Type:       "PERSISTENT",
				InitializeParams: &compute.AttachedDiskInitializeParams{
					DiskName:    *instance + "-coreos-stateless-pd",
					SourceImage: imageURL,
				},
			},
		},
		Tags: &compute.Tags{
			Items: []string{"http-server", "https-server"},
		},
		Metadata: &compute.Metadata{
			Items: []*compute.MetadataItems{
				{
					Key:   "camlistore-username",
					Value: "test",
				},
				{
					Key:   "camlistore-password",
					Value: "insecure", // TODO: this won't be cleartext later
				},
				{
					Key:   "camlistore-blob-bucket",
					Value: "gs://" + blobBucket,
				},
				{
					Key:   "camlistore-config-bucket",
					Value: "gs://" + configBucket,
				},
				{
					Key:   "user-data",
					Value: cloudConfig,
				},
			},
		},
		NetworkInterfaces: []*compute.NetworkInterface{
			&compute.NetworkInterface{
				AccessConfigs: []*compute.AccessConfig{
					&compute.AccessConfig{
						Type: "ONE_TO_ONE_NAT",
						Name: "External NAT",
					},
				},
				Network: prefix + "/global/networks/default",
			},
		},
		ServiceAccounts: []*compute.ServiceAccount{
			{
				Email: "default",
				Scopes: []string{
					compute.DevstorageFull_controlScope,
					compute.ComputeScope,
					"https://www.googleapis.com/auth/sqlservice",
					"https://www.googleapis.com/auth/sqlservice.admin",
				},
			},
		},
	}
	const localMySQL = false // later
	if localMySQL {
		instance.Disks = append(instance.Disks, &compute.AttachedDisk{
			AutoDelete: false,
			Boot:       false,
			Type:       "PERSISTENT",
			InitializeParams: &compute.AttachedDiskInitializeParams{
				DiskName:   "camlistore-mysql-index-pd",
				DiskSizeGb: 4,
			},
		})
	}

	log.Printf("Creating instance...")
	op, err := computeService.Instances.Insert(*proj, *zone, instance).Do()
	if err != nil {
		log.Fatalf("Failed to create instance: %v", err)
	}
	opName := op.Name
	log.Printf("Created. Waiting on operation %v", opName)
	for {
		time.Sleep(2 * time.Second)
		op, err := computeService.ZoneOperations.Get(*proj, *zone, opName).Do()
		if err != nil {
			log.Fatalf("Failed to get op %s: %v", opName, err)
		}
		switch op.Status {
		case "PENDING", "RUNNING":
			log.Printf("Waiting on operation %v", opName)
			continue
		case "DONE":
			if op.Error != nil {
				for _, operr := range op.Error.Errors {
					log.Printf("Error: %+v", operr)
				}
				log.Fatalf("Failed to start.")
			}
			log.Printf("Success. %+v", op)
			return
		default:
			log.Fatalf("Unknown status %q: %+v", op.Status, op)
		}
	}
}
<|endoftext|>


<commit_before>package factory

import (
	"os"
	"time"

	"github.com/blevesearch/bleve"
)

type BleveEngine struct {
}

/* Implements the SearchEngine interface */

func (be *BleveEngine) BatchIndex(documents *[]*Document) (int64, error) {
	start := time.Now().UnixNano() / int64(time.Millisecond)
	var index bleve.Index
	mapping := bleve.NewIndexMapping()
	index, err := bleve.New(INDEX, mapping)
	if err != nil {
		index, _ = bleve.Open(INDEX)
	}

	batch := index.NewBatch()

	for _, document := range *documents {
		batch.Index((*document).Id, (*document).Data)
	}

	index.Batch(batch)
	index.Close()

	return time.Now().UnixNano()/int64(time.Millisecond) - start, nil
}

func (be *BleveEngine) Index(document *Document) (int64, error) {
	start := time.Now().UnixNano() / int64(time.Millisecond)

	var index bleve.Index
	mapping := bleve.NewIndexMapping()
	index, err := bleve.New(INDEX, mapping)
	if err != nil {
		index, _ = bleve.Open(INDEX)
	}
	id := (*document).Id
	data := (*document).Data
	index.Index(id, data)
	index.Close()

	return time.Now().UnixNano()/int64(time.Millisecond) - start, nil
}

func (be *BleveEngine) Search(query string) (interface{}, error) {
	index, _ := bleve.Open(INDEX)
	bleveQuery := bleve.NewQueryStringQuery(query)
	searchRequest := bleve.NewSearchRequest(bleveQuery)
	searchResults, err := index.Search(searchRequest)
	if err != nil {
		return nil, err
	}
	return searchResults, nil
}

func (be *BleveEngine) Delete() error {
	index, err := bleve.Open(INDEX)
	if err != nil {
		return err
	}
	index.Close()
	os.RemoveAll(INDEX)
	return nil
}
<commit_msg>gofmt<commit_after>package factory

import (
	"os"
	"time"

	"github.com/blevesearch/bleve"
)

type BleveEngine struct {
}

/* Implements the SearchEngine interface */

func (be *BleveEngine) BatchIndex(documents *[]*Document) (int64, error) {
	start := time.Now().UnixNano() / int64(time.Millisecond)
	var index bleve.Index
	mapping := bleve.NewIndexMapping()
	index, err := bleve.New(INDEX, mapping)
	if err != nil {
		index, _ = bleve.Open(INDEX)
	}

	batch := index.NewBatch()

	for _, document := range *documents {
		batch.Index((*document).Id, (*document).Data)
	}

	index.Batch(batch)
	index.Close()

	return time.Now().UnixNano()/int64(time.Millisecond) - start, nil
}

func (be *BleveEngine) Index(document *Document) (int64, error) {
	start := time.Now().UnixNano() / int64(time.Millisecond)

	var index bleve.Index
	mapping := bleve.NewIndexMapping()
	index, err := bleve.New(INDEX, mapping)
	if err != nil {
		index, _ = bleve.Open(INDEX)
	}
	id := (*document).Id
	data := (*document).Data
	index.Index(id, data)
	index.Close()

	return time.Now().UnixNano()/int64(time.Millisecond) - start, nil
}

func (be *BleveEngine) Search(query string) (interface{}, error) {
	index, _ := bleve.Open(INDEX)
	bleveQuery := bleve.NewQueryStringQuery(query)
	searchRequest := bleve.NewSearchRequest(bleveQuery)
	searchResults, err := index.Search(searchRequest)
	if err != nil {
		return nil, err
	}

	return searchResults, nil
}

func (be *BleveEngine) Delete() error {
	index, err := bleve.Open(INDEX)
	if err != nil {
		return err
	}
	index.Close()
	os.RemoveAll(INDEX)
	return nil
}
<|endoftext|>


<commit_before>package neoutils

import (
	"github.com/Financial-Times/neo-cypher-runner-go/neocypherrunner"
	log "github.com/Sirupsen/logrus"
	"github.com/jmcvetta/neoism"
)

// StringerDb wraps neoism Database to provide a String function, which outputs the database URL
type StringerDb struct{ *neoism.Database }

func (sdb StringerDb) String() string {
	return sdb.Url
}

// Check will use the supplied CypherRunner to check connectivity to Neo4j
func Check(cr neocypherrunner.CypherRunner) error {
	results := []struct {
		node interface{}
	}{}

	query := &neoism.CypherQuery{
		Statement: `MATCH (n) RETURN id(n) LIMIT 1`,
		Result:    &results,
	}

	err := cr.CypherBatch([]*neoism.CypherQuery{query})

	if err != nil {
		return err
	}
	return nil
}

// EnsureIndexes will, for a map of labels and properties, check whether an index exists for a given property on a given label, and if missing will create one
func EnsureIndexes(im IndexManager, indexes map[string]string) error {
	for label, propertyName := range indexes {
		err := ensureIndex(im, label, propertyName)
		if err != nil { // stop as soon as something goes wrong
			return err
		}
	}
	return nil
}

// EnsureConstraints will, for a map of labels and properties, check whether a constraint exists for a given property on a given label, and
// if missing will create one. Creating the unique constraint ensures an index automatically.
func EnsureConstraints(im IndexManager, indexes map[string]string) error {
	for label, propertyName := range indexes {
		err := ensureConstraint(im, label, propertyName)
		if err != nil { // stop as soon as something goes wrong
			return err
		}
	}
	return nil
}

func ensureIndex(im IndexManager, label string, propertyName string) error {

	indexes, err := im.Indexes(label)

	var indexFound bool

	if err != nil && err != neoism.NotFound {
		return err
	}

	for _, index := range indexes {
		if len(index.PropertyKeys) == 1 && index.PropertyKeys[0] == propertyName {
			indexFound = true
			break
		}
	}

	if !indexFound {
		log.Infof("Creating index for type %s on property %s\n", label, propertyName)
		_, err := im.CreateIndex(label, propertyName)
		if err != nil {
			return err
		}
	}
	return nil

}

func ensureConstraint(im IndexManager, label string, propertyName string) error {
	_, err := im.UniqueConstraints(label, propertyName)

	if err != nil {
		if err == neoism.NotFound {
			log.Infof("Creating unique constraint for type %s on property %s\n", label, propertyName)
			_, err = im.CreateUniqueConstraint(label, propertyName)
			if err != nil {
				log.Errorf("Cannot create constraint for type %s on property %s\n", label, propertyName)
				return err
			}
		}
		return err
	}
	return nil

}

func getIndex(im IndexManager, label string, propertyName string) (*neoism.Index, error) {
	indexes, err := im.Indexes(label)

	if err != nil {
		return nil, err
	}

	for _, index := range indexes {
		if len(index.PropertyKeys) == 1 && index.PropertyKeys[0] == propertyName {
			return index, nil
		}
	}
	return nil, nil
}

// IndexManager manages the maintenance of indexes and unique constraints
type IndexManager interface {
	CreateIndex(label string, propertyName string) (*neoism.Index, error)
	Indexes(label string) ([]*neoism.Index, error)
	CreateUniqueConstraint(label string, propertyName string) (*neoism.UniqueConstraint, error)
	UniqueConstraints(label string, propertyName string) ([]*neoism.UniqueConstraint, error)
}
<commit_msg>removed dependency on cypher runner<commit_after>package neoutils

import (
	log "github.com/Sirupsen/logrus"
	"github.com/jmcvetta/neoism"
)

// StringerDb wraps neoism Database to provide a String function, which outputs the database URL
type StringerDb struct{ *neoism.Database }

func (sdb StringerDb) String() string {
	return sdb.Url
}

// Check will use the supplied CypherRunner to check connectivity to Neo4j
func Check(cr CypherRunner) error {
	results := []struct {
		node interface{}
	}{}

	query := &neoism.CypherQuery{
		Statement: `MATCH (n) RETURN id(n) LIMIT 1`,
		Result:    &results,
	}

	err := cr.CypherBatch([]*neoism.CypherQuery{query})

	if err != nil {
		return err
	}
	return nil
}

// EnsureIndexes will, for a map of labels and properties, check whether an index exists for a given property on a given label, and if missing will create one
func EnsureIndexes(im IndexManager, indexes map[string]string) error {
	for label, propertyName := range indexes {
		err := ensureIndex(im, label, propertyName)
		if err != nil { // stop as soon as something goes wrong
			return err
		}
	}
	return nil
}

// EnsureConstraints will, for a map of labels and properties, check whether a constraint exists for a given property on a given label, and
// if missing will create one. Creating the unique constraint ensures an index automatically.
func EnsureConstraints(im IndexManager, indexes map[string]string) error {
	for label, propertyName := range indexes {
		err := ensureConstraint(im, label, propertyName)
		if err != nil { // stop as soon as something goes wrong
			return err
		}
	}
	return nil
}

func ensureIndex(im IndexManager, label string, propertyName string) error {

	indexes, err := im.Indexes(label)

	var indexFound bool

	if err != nil && err != neoism.NotFound {
		return err
	}

	for _, index := range indexes {
		if len(index.PropertyKeys) == 1 && index.PropertyKeys[0] == propertyName {
			indexFound = true
			break
		}
	}

	if !indexFound {
		log.Infof("Creating index for type %s on property %s\n", label, propertyName)
		_, err := im.CreateIndex(label, propertyName)
		if err != nil {
			return err
		}
	}
	return nil

}

func ensureConstraint(im IndexManager, label string, propertyName string) error {
	_, err := im.UniqueConstraints(label, propertyName)

	if err != nil {
		if err == neoism.NotFound {
			log.Infof("Creating unique constraint for type %s on property %s\n", label, propertyName)
			_, err = im.CreateUniqueConstraint(label, propertyName)
			if err != nil {
				log.Errorf("Cannot create constraint for type %s on property %s\n", label, propertyName)
				return err
			}
		}
		return err
	}
	return nil

}

func getIndex(im IndexManager, label string, propertyName string) (*neoism.Index, error) {
	indexes, err := im.Indexes(label)

	if err != nil {
		return nil, err
	}

	for _, index := range indexes {
		if len(index.PropertyKeys) == 1 && index.PropertyKeys[0] == propertyName {
			return index, nil
		}
	}
	return nil, nil
}

// IndexManager manages the maintenance of indexes and unique constraints
type IndexManager interface {
	CreateIndex(label string, propertyName string) (*neoism.Index, error)
	Indexes(label string) ([]*neoism.Index, error)
	CreateUniqueConstraint(label string, propertyName string) (*neoism.UniqueConstraint, error)
	UniqueConstraints(label string, propertyName string) ([]*neoism.UniqueConstraint, error)
}
<|endoftext|>


<commit_before>package subscription

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestCreateSubscription(t *testing.T) {
	sub := New()

	assert := assert.New(t)
	assert.Equal(time.Time{}, sub.SubscribeAt)
	assert.Equal(time.Time{}, sub.UnsubscribeAt)
	assert.Nil(sub.Err())
}

func TestSubscription(t *testing.T) {
	var first time.Time
	go func() {
		first = time.Now()
	}()

	sub := New().Subscribe()
	<-time.After(10 * time.Millisecond)
	sub = sub.Unsubscribe()

	assert := assert.New(t)
	assert.WithinDuration(first, sub.SubscribeAt, 5*time.Millisecond)
	assert.WithinDuration(first, sub.SubscribeAt, 15*time.Millisecond)
}
<commit_msg>remove unnecessary goroutine and with that fix the possible data race condition in tests<commit_after>package subscription

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestCreateSubscription(t *testing.T) {
	sub := New()

	assert := assert.New(t)
	assert.Equal(time.Time{}, sub.SubscribeAt)
	assert.Equal(time.Time{}, sub.UnsubscribeAt)
	assert.Nil(sub.Err())
}

func TestSubscription(t *testing.T) {
	sub := New().Subscribe()
	first := sub.SubscribeAt
	<-time.After(10 * time.Millisecond)
	sub = sub.Unsubscribe()

	assert := assert.New(t)
	assert.WithinDuration(first, sub.SubscribeAt, 5*time.Millisecond)
	assert.WithinDuration(first, sub.SubscribeAt, 15*time.Millisecond)
}
<|endoftext|>


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

package apiserver

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	// embed pprof server.
	_ "net/http/pprof"

	"github.com/fiorix/freegeoip"
	"github.com/fiorix/go-redis/redis"
	gorilla "github.com/gorilla/handlers"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/net/http2"
)

// Version tag.
var Version = "3.0.7"

var maxmindDB = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"

var (
	flAPIPrefix      = flag.String("api-prefix", "/", "Prefix for API endpoints")
	flCORSOrigin     = flag.String("cors-origin", "*", "CORS origin API endpoints")
	flHTTPAddr       = flag.String("http", ":8080", "Address in form of ip:port to listen on for HTTP")
	flHTTPSAddr      = flag.String("https", "", "Address in form of ip:port to listen on for HTTPS")
	flCertFile       = flag.String("cert", "cert.pem", "X.509 certificate file")
	flKeyFile        = flag.String("key", "key.pem", "X.509 key file")
	flReadTimeout    = flag.Duration("read-timeout", 30*time.Second, "Read timeout for HTTP and HTTPS client conns")
	flWriteTimeout   = flag.Duration("write-timeout", 15*time.Second, "Write timeout for HTTP and HTTPS client conns")
	flPublicDir      = flag.String("public", "", "Public directory to serve at the {prefix}/ endpoint")
	flDB             = flag.String("db", maxmindDB, "IP database file or URL")
	flUpdateIntvl    = flag.Duration("update", 24*time.Hour, "Database update check interval")
	flRetryIntvl     = flag.Duration("retry", time.Hour, "Max time to wait before retrying to download database")
	flUseXFF         = flag.Bool("use-x-forwarded-for", false, "Use the X-Forwarded-For header when available (e.g. when running behind proxies)")
	flSilent         = flag.Bool("silent", false, "Do not log HTTP or HTTPS requests to stderr")
	flLogToStdout    = flag.Bool("logtostdout", false, "Log to stdout instead of stderr")
	flRedisAddr      = flag.String("redis", "127.0.0.1:6379", "Redis address in form of ip:port[,ip:port] for quota")
	flRedisTimeout   = flag.Duration("redis-timeout", time.Second, "Redis read/write timeout")
	flQuotaMax       = flag.Int("quota-max", 0, "Max requests per source IP per interval; set 0 to turn off")
	flQuotaIntvl     = flag.Duration("quota-interval", time.Hour, "Quota expiration interval per source IP querying the API")
	flVersion        = flag.Bool("version", false, "Show version and exit")
	flInternalServer = flag.String("internal-server", "", "Address in form of ip:port to listen on for /metrics and /debug/pprof")
)

// Run is the entrypoint for the freegeoip daemon tool.
func Run() error {
	flag.Parse()

	if *flVersion {
		fmt.Printf("freegeoip v%s\n", Version)
		return nil
	}

	if *flLogToStdout {
		log.SetOutput(os.Stdout)
	}

	log.SetPrefix("[freegeoip] ")

	addrs := strings.Split(*flRedisAddr, ",")
	rc, err := redis.NewClient(addrs...)
	if err != nil {
		return err
	}
	rc.SetTimeout(*flRedisTimeout)

	db, err := openDB(*flDB, *flUpdateIntvl, *flRetryIntvl)
	if err != nil {
		return err
	}
	go watchEvents(db)

	ah := NewHandler(&HandlerConfig{
		Prefix:    *flAPIPrefix,
		Origin:    *flCORSOrigin,
		PublicDir: *flPublicDir,
		DB:        db,
		RateLimiter: RateLimiter{
			Redis:    rc,
			Max:      *flQuotaMax,
			Interval: *flQuotaIntvl,
		},
		UseXForwardedFor: *flUseXFF,
	})

	if !*flSilent {
		ah = gorilla.CombinedLoggingHandler(os.Stderr, ah)
	}

	if *flUseXFF {
		ah = freegeoip.ProxyHandler(ah)
	}

	if len(*flInternalServer) > 0 {
		http.Handle("/metrics", prometheus.Handler())
		log.Println("freegeoip internal server starting on", *flInternalServer)
		go func() { log.Fatal(http.ListenAndServe(*flInternalServer, nil)) }()
	}

	if *flHTTPAddr != "" {
		log.Println("freegeoip http server starting on", *flHTTPAddr)
		srv := &http.Server{
			Addr:         *flHTTPAddr,
			Handler:      ah,
			ReadTimeout:  *flReadTimeout,
			WriteTimeout: *flWriteTimeout,
			ConnState:    ConnStateMetrics("http"),
		}
		go func() { log.Fatal(srv.ListenAndServe()) }()
	}

	if *flHTTPSAddr != "" {
		log.Println("freegeoip https server starting on", *flHTTPSAddr)
		srv := &http.Server{
			Addr:         *flHTTPSAddr,
			Handler:      ah,
			ReadTimeout:  *flReadTimeout,
			WriteTimeout: *flWriteTimeout,
			ConnState:    ConnStateMetrics("https"),
		}
		http2.ConfigureServer(srv, nil)
		go func() { log.Fatal(srv.ListenAndServeTLS(*flCertFile, *flKeyFile)) }()
	}

	select {}
}
<commit_msg>Cleanup<commit_after>// Copyright 2009-2015 The freegeoip authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package apiserver

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	// embed pprof server.
	_ "net/http/pprof"

	"github.com/fiorix/freegeoip"
	"github.com/fiorix/go-redis/redis"
	gorilla "github.com/gorilla/handlers"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/net/http2"
)

// Version tag.
var Version = "3.0.7"

var maxmindDB = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"

var (
	flAPIPrefix      = flag.String("api-prefix", "/", "Prefix for API endpoints")
	flCORSOrigin     = flag.String("cors-origin", "*", "CORS origin API endpoints")
	flHTTPAddr       = flag.String("http", ":8080", "Address in form of ip:port to listen on for HTTP")
	flHTTPSAddr      = flag.String("https", "", "Address in form of ip:port to listen on for HTTPS")
	flCertFile       = flag.String("cert", "cert.pem", "X.509 certificate file")
	flKeyFile        = flag.String("key", "key.pem", "X.509 key file")
	flReadTimeout    = flag.Duration("read-timeout", 30*time.Second, "Read timeout for HTTP and HTTPS client conns")
	flWriteTimeout   = flag.Duration("write-timeout", 15*time.Second, "Write timeout for HTTP and HTTPS client conns")
	flPublicDir      = flag.String("public", "", "Public directory to serve at the {prefix}/ endpoint")
	flDB             = flag.String("db", maxmindDB, "IP database file or URL")
	flUpdateIntvl    = flag.Duration("update", 24*time.Hour, "Database update check interval")
	flRetryIntvl     = flag.Duration("retry", time.Hour, "Max time to wait before retrying to download database")
	flUseXFF         = flag.Bool("use-x-forwarded-for", false, "Use the X-Forwarded-For header when available (e.g. when running behind proxies)")
	flSilent         = flag.Bool("silent", false, "Do not log HTTP or HTTPS requests to stderr")
	flLogToStdout    = flag.Bool("logtostdout", false, "Log to stdout instead of stderr")
	flRedisAddr      = flag.String("redis", "127.0.0.1:6379", "Redis address in form of ip:port[,ip:port] for quota")
	flRedisTimeout   = flag.Duration("redis-timeout", time.Second, "Redis read/write timeout")
	flQuotaMax       = flag.Int("quota-max", 0, "Max requests per source IP per interval; set 0 to turn off")
	flQuotaIntvl     = flag.Duration("quota-interval", time.Hour, "Quota expiration interval per source IP querying the API")
	flVersion        = flag.Bool("version", false, "Show version and exit")
	flInternalServer = flag.String("internal-server", "", "Address in form of ip:port to listen on for /metrics and /debug/pprof")
)

// Run is the entrypoint for the freegeoip daemon tool.
func Run() error {
	flag.Parse()

	if *flVersion {
		fmt.Printf("freegeoip %s\n", Version)
		return nil
	}

	if *flLogToStdout {
		log.SetOutput(os.Stdout)
	}

	log.SetPrefix("[freegeoip] ")

	addrs := strings.Split(*flRedisAddr, ",")
	rc, err := redis.NewClient(addrs...)
	if err != nil {
		return err
	}
	rc.SetTimeout(*flRedisTimeout)

	db, err := openDB(*flDB, *flUpdateIntvl, *flRetryIntvl)
	if err != nil {
		return err
	}
	go watchEvents(db)

	ah := NewHandler(&HandlerConfig{
		Prefix:    *flAPIPrefix,
		Origin:    *flCORSOrigin,
		PublicDir: *flPublicDir,
		DB:        db,
		RateLimiter: RateLimiter{
			Redis:    rc,
			Max:      *flQuotaMax,
			Interval: *flQuotaIntvl,
		},
		UseXForwardedFor: *flUseXFF,
	})

	if !*flSilent {
		ah = gorilla.CombinedLoggingHandler(os.Stderr, ah)
	}

	if *flUseXFF {
		ah = freegeoip.ProxyHandler(ah)
	}

	if len(*flInternalServer) > 0 {
		http.Handle("/metrics", prometheus.Handler())
		log.Println("freegeoip internal server starting on", *flInternalServer)
		go func() { log.Fatal(http.ListenAndServe(*flInternalServer, nil)) }()
	}

	if *flHTTPAddr != "" {
		log.Println("freegeoip http server starting on", *flHTTPAddr)
		srv := &http.Server{
			Addr:         *flHTTPAddr,
			Handler:      ah,
			ReadTimeout:  *flReadTimeout,
			WriteTimeout: *flWriteTimeout,
			ConnState:    ConnStateMetrics("http"),
		}
		go func() { log.Fatal(srv.ListenAndServe()) }()
	}

	if *flHTTPSAddr != "" {
		log.Println("freegeoip https server starting on", *flHTTPSAddr)
		srv := &http.Server{
			Addr:         *flHTTPSAddr,
			Handler:      ah,
			ReadTimeout:  *flReadTimeout,
			WriteTimeout: *flWriteTimeout,
			ConnState:    ConnStateMetrics("https"),
		}
		http2.ConfigureServer(srv, nil)
		go func() { log.Fatal(srv.ListenAndServeTLS(*flCertFile, *flKeyFile)) }()
	}

	select {}
}
<|endoftext|>


<commit_before>package tunnel

import (
	"net"
	"time"
)

type Client struct {
	Server      string
	AESKey      string
	ServiceName string
	ServicePort uint16
	Connections int
}

func (client *Client) Run() {
	for i := 0; i < client.Connections-1; i++ {
		go client.dial()
	}
	client.dial()
}

func (client *Client) dial() {
	for {
		conn, err := dial("tcp", client.Server, client.AESKey)
		if err != nil {
			log.Warnf("service(%s): dial remote: %v", client.ServiceName, err)
			time.Sleep(time.Second)
			continue
		}

		err = sendMessage(conn, "hello", []byte(client.ServiceName))
		if err != nil {
			conn.Close()
			continue
		}

		buf := make([]byte, 1)
		_, err = conn.Read(buf)
		if err != nil || buf[0] != 1 {
			conn.Close()
			continue
		}

		client.heartBeat(conn)
	}
}

func (client *Client) heartBeat(conn net.Conn) {
	for {
		ec := make(chan error, 1)
		msg := make(chan byte, 1)

		go func() {
			_, err := conn.Write([]byte{'!'})
			if err != nil {
				ec <- err
				return
			}

			buf := make([]byte, 1)
			_, err = conn.Read(buf)
			if err != nil {
				ec <- err
				return
			}

			ec <- nil
			msg <- buf[0]
		}()

		select {
		case err := <-ec:
			if err != nil {
				conn.Close()
				return
			}
		case <-time.After(3 * time.Second):
			conn.Close()
			return
		}

		if <-msg == 1 {
			go client.proxy(conn)
			return
		}
	}
}

func (client *Client) proxy(conn net.Conn) {
	proxyConn, err := dial("tcp", strf(":%d", client.ServicePort), "")
	if err != nil {
		log.Warnf("service(%s): dial local failed: %v", client.ServiceName, err)
		conn.Close()
		return
	}

	proxy(conn, proxyConn)
}
<commit_msg>send 0 to msg channel<commit_after>package tunnel

import (
	"net"
	"time"
)

type Client struct {
	Server      string
	AESKey      string
	ServiceName string
	ServicePort uint16
	Connections int
}

func (client *Client) Run() {
	for i := 0; i < client.Connections-1; i++ {
		go client.dial()
	}
	client.dial()
}

func (client *Client) dial() {
	for {
		conn, err := dial("tcp", client.Server, client.AESKey)
		if err != nil {
			log.Warnf("service(%s): dial remote: %v", client.ServiceName, err)
			time.Sleep(time.Second)
			continue
		}

		err = sendMessage(conn, "hello", []byte(client.ServiceName))
		if err != nil {
			conn.Close()
			continue
		}

		buf := make([]byte, 1)
		_, err = conn.Read(buf)
		if err != nil || buf[0] != 1 {
			conn.Close()
			continue
		}

		client.heartBeat(conn)
	}
}

func (client *Client) heartBeat(conn net.Conn) {
	for {
		ec := make(chan error, 1)
		msg := make(chan byte, 1)

		go func() {
			_, err := conn.Write([]byte{'!'})
			if err != nil {
				ec <- err
				return
			}

			buf := make([]byte, 1)
			_, err = conn.Read(buf)
			if err != nil {
				ec <- err
				return
			}

			ec <- nil
			msg <- buf[0]
		}()

		select {
		case err := <-ec:
			if err != nil {
				conn.Close()
				return
			}
		case <-time.After(3 * time.Second):
			msg <- 0
			conn.Close()
			return
		}

		if <-msg == 1 {
			go client.proxy(conn)
			return
		}
	}
}

func (client *Client) proxy(conn net.Conn) {
	proxyConn, err := dial("tcp", strf(":%d", client.ServicePort), "")
	if err != nil {
		log.Warnf("service(%s): dial local failed: %v", client.ServiceName, err)
		conn.Close()
		return
	}

	proxy(conn, proxyConn)
}
<|endoftext|>


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

package netcdf

// #include <stdlib.h>
// #include <netcdf.h>
import "C"

import (
	"unsafe"
)

// Attr represents an attribute associated with a variable.
type Attr struct {
	v    Var
	name string
}

// Name returns the name of attribute a.
func (a Attr) Name() string {
	return a.name
}

// Type returns the data type of attribute a.
func (a Attr) Type() (t Type, err error) {
	// TODO: convert a.name to CString only once instead of in
	// each method of a.
	cname := C.CString(a.name)
	defer C.free(unsafe.Pointer(cname))
	var ct C.nc_type
	err = newError(C.nc_inq_atttype(C.int(a.v.ds), C.int(a.v.id), cname, &ct))
	t = Type(ct)
	return
}

// Len returns the length of the attribute value.
func (a Attr) Len() (n uint64, err error) {
	cname := C.CString(a.name)
	defer C.free(unsafe.Pointer(cname))
	var cn C.size_t
	err = newError(C.nc_inq_attlen(C.int(a.v.ds), C.int(a.v.id), cname, &cn))
	n = uint64(cn)
	return
}

// Attr returns attribute named name.
func (v Var) Attr(name string) (a Attr) {
	return Attr{v: v, name: name}
}

// AttrN returns attribute for attribute number n.
func (v Var) AttrN(n int) (a Attr, err error) {
	buf := C.CString(string(make([]byte, C.NC_MAX_NAME+1)))
	defer C.free(unsafe.Pointer(buf))
	err = newError(C.nc_inq_attname(C.int(v.ds), C.int(v.id), C.int(n), buf))
	a = Attr{v: v, name: C.GoString(buf)}
	return
}

// Attr returns global attribute named name.
func (ds Dataset) Attr(name string) (a Attr) {
	return Var{ds, C.NC_GLOBAL}.Attr(name)
}

// AttrN returns global attribute for attribute number n.
func (ds Dataset) AttrN(n int) (a Attr, err error) {
	return Var{ds, C.NC_GLOBAL}.AttrN(n)
}
<commit_msg>document creation of new attribute<commit_after>// Copyright 2014 The Go-NetCDF Authors. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package netcdf

// #include <stdlib.h>
// #include <netcdf.h>
import "C"

import (
	"unsafe"
)

// Attr represents an attribute associated with a variable.
type Attr struct {
	v    Var
	name string
}

// Name returns the name of attribute a.
func (a Attr) Name() string {
	return a.name
}

// Type returns the data type of attribute a.
func (a Attr) Type() (t Type, err error) {
	// TODO: convert a.name to CString only once instead of in
	// each method of a.
	cname := C.CString(a.name)
	defer C.free(unsafe.Pointer(cname))
	var ct C.nc_type
	err = newError(C.nc_inq_atttype(C.int(a.v.ds), C.int(a.v.id), cname, &ct))
	t = Type(ct)
	return
}

// Len returns the length of the attribute value.
func (a Attr) Len() (n uint64, err error) {
	cname := C.CString(a.name)
	defer C.free(unsafe.Pointer(cname))
	var cn C.size_t
	err = newError(C.nc_inq_attlen(C.int(a.v.ds), C.int(a.v.id), cname, &cn))
	n = uint64(cn)
	return
}

// Attr returns attribute named name. If the attribute does not yet exist,
// it'll be created once it's written.
func (v Var) Attr(name string) (a Attr) {
	return Attr{v: v, name: name}
}

// AttrN returns attribute for attribute number n.
func (v Var) AttrN(n int) (a Attr, err error) {
	buf := C.CString(string(make([]byte, C.NC_MAX_NAME+1)))
	defer C.free(unsafe.Pointer(buf))
	err = newError(C.nc_inq_attname(C.int(v.ds), C.int(v.id), C.int(n), buf))
	a = Attr{v: v, name: C.GoString(buf)}
	return
}

// Attr returns global attribute named name. If the attribute does not yet
// exist, it'll be created once it's written.
func (ds Dataset) Attr(name string) (a Attr) {
	return Var{ds, C.NC_GLOBAL}.Attr(name)
}

// AttrN returns global attribute for attribute number n.
func (ds Dataset) AttrN(n int) (a Attr, err error) {
	return Var{ds, C.NC_GLOBAL}.AttrN(n)
}
<|endoftext|>


<commit_before>package filestream

import (
	"io"
	"os"
)

type Positioner interface {
	SeekInFile() (io.Reader, error)
	Move(int)
}

type Position struct {
	SeekPos int64  `json:"seek_position"`
	Path    string `json:"path"`
}

func (pos *Position) SeekInFile() (reader io.Reader, err error) {
	fd, err := os.Open(pos.Path)
	if err != nil {
		return
	}

	reader = fd

	// Try to get to our seek position, if our seek is 0, then start at the
	// beginning.
	if pos.SeekPos == 0 {
		return
	}

	_, err = fd.Seek(pos.SeekPos, 0)
	if err != nil {
		return
	}

	return
}

func (pos *Position) Move(n int64) {
	pos.SeekPos += n
}
<commit_msg>update position<commit_after>package filestream

import (
	"io"
	"os"

	"github.com/foreversmart/gotools/fileswitcher"
)

type Positioner interface {
	SeekInFile() (io.Reader, error)
	Move(int64)
}

type Position struct {
	SeekPos  int64                     `json:"seek_position"`
	FileSize int64                     `json:"file_size"`
	Switcher fileswitcher.FileSwitcher `json:"path"`
}

func NewPosition(switcher fileswitcher.FileSwitcher) *Position {
	return &Position{
		SeekPos:  0,
		FileSize: 0,
		Switcher: switcher,
	}
}

func (pos *Position) SeekInFile() (reader io.Reader, err error) {
	fileInfo, err := os.Stat(pos.Switcher.CurrentFile())
	if err != nil {
		return
	}

	// if current file Modtime is newer than hold file indicate files switched
	if fileInfo.Size() < pos.FileSize {
		_, err = pos.Switcher.OlderFile()
		if err != nil {
			return
		}

		// switch to older file success update fileinfo
		fileInfo, err = os.Stat(pos.Switcher.CurrentFile())
		if err != nil {
			return
		}
	}

	// if current pos is tail of the file move to new file
	if pos.SeekPos >= fileInfo.Size() {
		_, err = pos.Switcher.NewerFile()

		if err == nil {
			// switch to newer file success update fileinfo
			fileInfo, err = os.Stat(pos.Switcher.CurrentFile())
			if err != nil {
				return
			}

			// update seekPos to zero
			pos.SeekPos = 0
		}
	}

	// update file size
	pos.FileSize = fileInfo.Size()

	fd, err := os.Open(pos.Switcher.CurrentFile())
	if err != nil {
		return
	}

	reader = fd

	// Try to get to our seek position, if our seek is 0, then start at the
	// beginning.
	if pos.SeekPos == 0 {
		return
	}

	_, err = fd.Seek(pos.SeekPos, 0)
	if err != nil {
		return
	}

	return
}

func (pos *Position) UpdateFileInfo() error {
	fileInfo, err := os.Stat(pos.Switcher.CurrentFile())
	if err != nil {
		return err
	}

	pos.FileSize = fileInfo.Size()

	return nil
}

func (pos *Position) Move(n int64) {
	pos.SeekPos += n
}
<|endoftext|>