<commit_before>package locking

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/rubyist/tracerx"

	"github.com/git-lfs/git-lfs/api"
	"github.com/git-lfs/git-lfs/config"
	"github.com/git-lfs/git-lfs/filepathfilter"
	"github.com/git-lfs/git-lfs/git"
	"github.com/git-lfs/git-lfs/tools/kv"
)

var (
	// ErrNoMatchingLocks is an error returned when no matching locks were
	// able to be resolved
	ErrNoMatchingLocks = errors.New("lfs: no matching locks found")
	// ErrLockAmbiguous is an error returned when multiple matching locks
	// were found
	ErrLockAmbiguous = errors.New("lfs: multiple locks found; ambiguous")
)

// Client is the main interface object for the locking package
type Client struct {
	cfg              *config.Configuration
	apiClient        *api.Client
	cache            *LockCache
	lockablePatterns []string
	lockableFilter   *filepathfilter.Filter
	lockableMutex    sync.Mutex
}

// NewClient creates a new locking client with the given configuration
// You must call the returned object's `Close` method when you are finished with
// it
func NewClient(cfg *config.Configuration) (*Client, error) {

	apiClient := api.NewClient(api.NewHttpLifecycle(cfg))

	lockDir := filepath.Join(config.LocalGitStorageDir, "lfs")
	err := os.MkdirAll(lockDir, 0755)
	if err != nil {
		return nil, err
	}
	lockFile := filepath.Join(lockDir, "lockcache.db")
	cache, err := NewLockCache(lockFile)
	if err != nil {
		return nil, err
	}
	return &Client{cfg: cfg, apiClient: apiClient, cache: cache}, nil
}

// Close this client instance; must be called to dispose of resources
func (c *Client) Close() error {
	return c.cache.Save()
}

// LockFile attempts to lock a file on the current remote
// path must be relative to the root of the repository
// Returns the lock id if successful, or an error
func (c *Client) LockFile(path string) (Lock, error) {

	// TODO: this is not really the constraint we need to avoid merges, improve as per proposal
	latest, err := git.CurrentRemoteRef()
	if err != nil {
		return Lock{}, err
	}

	s, resp := c.apiClient.Locks.Lock(&api.LockRequest{
		Path:               path,
		Committer:          api.NewCommitter(c.cfg.CurrentCommitter()),
		LatestRemoteCommit: latest.Sha,
	})

	if _, err := c.apiClient.Do(s); err != nil {
		return Lock{}, fmt.Errorf("Error communicating with LFS API: %v", err)
	}

	if len(resp.Err) > 0 {
		return Lock{}, fmt.Errorf("Server unable to create lock: %v", resp.Err)
	}

	lock := c.newLockFromApi(*resp.Lock)

	if err := c.cache.Add(lock); err != nil {
		return Lock{}, fmt.Errorf("Error caching lock information: %v", err)
	}

	return lock, nil
}

// UnlockFile attempts to unlock a file on the current remote
// path must be relative to the root of the repository
// Force causes the file to be unlocked from other users as well
func (c *Client) UnlockFile(path string, force bool) error {

	id, err := c.lockIdFromPath(path)
	if err != nil {
		return fmt.Errorf("Unable to get lock id: %v", err)
	}

	return c.UnlockFileById(id, force)

}

// UnlockFileById attempts to unlock a lock with a given id on the current remote
// Force causes the file to be unlocked from other users as well
func (c *Client) UnlockFileById(id string, force bool) error {
	s, resp := c.apiClient.Locks.Unlock(id, force)

	if _, err := c.apiClient.Do(s); err != nil {
		return fmt.Errorf("Error communicating with LFS API: %v", err)
	}

	if len(resp.Err) > 0 {
		return fmt.Errorf("Server unable to unlock lock: %v", resp.Err)
	}

	if err := c.cache.RemoveById(id); err != nil {
		return fmt.Errorf("Error caching unlock information: %v", err)
	}

	return nil
}

// Lock is a record of a locked file
type Lock struct {
	// Id is the unique identifier corresponding to this particular Lock. It
	// must be consistent with the local copy, and the server's copy.
	Id string
	// Path is an absolute path to the file that is locked as a part of this
	// lock.
	Path string
	// Name is the name of the person holding this lock
	Name string
	// Email address of the person holding this lock
	Email string
	// LockedAt is the time at which this lock was acquired.
	LockedAt time.Time
}

func (c *Client) newLockFromApi(a api.Lock) Lock {
	return Lock{
		Id:       a.Id,
		Path:     a.Path,
		Name:     a.Committer.Name,
		Email:    a.Committer.Email,
		LockedAt: a.LockedAt,
	}
}

// SearchLocks returns a channel of locks which match the given name/value filter
// If limit > 0 then search stops at that number of locks
// If localOnly = true, don't query the server & report only own local locks
func (c *Client) SearchLocks(filter map[string]string, limit int, localOnly bool) (locks []Lock, err error) {

	if localOnly {
		return c.searchCachedLocks(filter, limit)
	} else {
		return c.searchRemoteLocks(filter, limit)
	}
}

func (c *Client) searchCachedLocks(filter map[string]string, limit int) ([]Lock, error) {
	cachedlocks := c.cache.Locks()
	path, filterByPath := filter["path"]
	id, filterById := filter["id"]
	lockCount := 0
	locks := make([]Lock, 0, len(cachedlocks))
	for _, l := range cachedlocks {
		// Manually filter by Path/Id
		if (filterByPath && path != l.Path) ||
			(filterById && id != l.Id) {
			continue
		}
		locks = append(locks, l)
		lockCount++
		if limit > 0 && lockCount >= limit {
			break
		}
	}
	return locks, nil
}

func (c *Client) searchRemoteLocks(filter map[string]string, limit int) ([]Lock, error) {
	locks := make([]Lock, 0, limit)

	apifilters := make([]api.Filter, 0, len(filter))
	for k, v := range filter {
		apifilters = append(apifilters, api.Filter{k, v})
	}
	query := &api.LockSearchRequest{Filters: apifilters}
	for {
		s, resp := c.apiClient.Locks.Search(query)
		if _, err := c.apiClient.Do(s); err != nil {
			return locks, fmt.Errorf("Error communicating with LFS API: %v", err)
		}

		if resp.Err != "" {
			return locks, fmt.Errorf("Error response from LFS API: %v", resp.Err)
		}

		for _, l := range resp.Locks {
			locks = append(locks, c.newLockFromApi(l))
			if limit > 0 && len(locks) >= limit {
				// Exit outer loop too
				return locks, nil
			}
		}

		if resp.NextCursor != "" {
			query.Cursor = resp.NextCursor
		} else {
			break
		}
	}

	return locks, nil

}

// lockIdFromPath makes a call to the LFS API and resolves the ID for the locked
// locked at the given path.
//
// If the API call failed, an error will be returned. If multiple locks matched
// the given path (should not happen during real-world usage), an error will be
// returnd. If no locks matched the given path, an error will be returned.
//
// If the API call is successful, and only one lock matches the given filepath,
// then its ID will be returned, along with a value of "nil" for the error.
func (c *Client) lockIdFromPath(path string) (string, error) {
	s, resp := c.apiClient.Locks.Search(&api.LockSearchRequest{
		Filters: []api.Filter{
			{"path", path},
		},
	})

	if _, err := c.apiClient.Do(s); err != nil {
		return "", err
	}

	switch len(resp.Locks) {
	case 0:
		return "", ErrNoMatchingLocks
	case 1:
		return resp.Locks[0].Id, nil
	default:
		return "", ErrLockAmbiguous
	}
}

// Fetch locked files for the current committer and cache them locally
// This can be used to sync up locked files when moving machines
func (c *Client) refreshLockCache() error {
	// TODO: filters don't seem to currently define how to search for a
	// committer's email. Is it "committer.email"? For now, just iterate
	locks, err := c.SearchLocks(nil, 0, false)
	if err != nil {
		return err
	}

	// We're going to overwrite the entire local cache
	c.cache.Clear()

	_, email := c.cfg.CurrentCommitter()
	for _, l := range locks {
		if l.Email == email {
			c.cache.Add(l)
		}
	}

	return nil
}

// IsFileLockedByCurrentCommitter returns whether a file is locked by the
// current committer, as cached locally
func (c *Client) IsFileLockedByCurrentCommitter(path string) bool {

	filter := map[string]string{"path": path}
	locks, err := c.searchCachedLocks(filter, 1)
	if err != nil {
		tracerx.Printf("Error searching cached locks: %s\nForcing remote search", err)
		locks, _ = c.searchRemoteLocks(filter, 1)
	}
	return len(locks) > 0
}

func init() {
	kv.RegisterTypeForStorage(&Lock{})
}
<commit_msg>Make lockable files read-only on unlock & writeable on lock<commit_after>package locking

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/rubyist/tracerx"

	"github.com/git-lfs/git-lfs/api"
	"github.com/git-lfs/git-lfs/config"
	"github.com/git-lfs/git-lfs/filepathfilter"
	"github.com/git-lfs/git-lfs/git"
	"github.com/git-lfs/git-lfs/tools"
	"github.com/git-lfs/git-lfs/tools/kv"
)

var (
	// ErrNoMatchingLocks is an error returned when no matching locks were
	// able to be resolved
	ErrNoMatchingLocks = errors.New("lfs: no matching locks found")
	// ErrLockAmbiguous is an error returned when multiple matching locks
	// were found
	ErrLockAmbiguous = errors.New("lfs: multiple locks found; ambiguous")
)

// Client is the main interface object for the locking package
type Client struct {
	cfg              *config.Configuration
	apiClient        *api.Client
	cache            *LockCache
	lockablePatterns []string
	lockableFilter   *filepathfilter.Filter
	lockableMutex    sync.Mutex
}

// NewClient creates a new locking client with the given configuration
// You must call the returned object's `Close` method when you are finished with
// it
func NewClient(cfg *config.Configuration) (*Client, error) {

	apiClient := api.NewClient(api.NewHttpLifecycle(cfg))

	lockDir := filepath.Join(config.LocalGitStorageDir, "lfs")
	err := os.MkdirAll(lockDir, 0755)
	if err != nil {
		return nil, err
	}
	lockFile := filepath.Join(lockDir, "lockcache.db")
	cache, err := NewLockCache(lockFile)
	if err != nil {
		return nil, err
	}
	return &Client{cfg: cfg, apiClient: apiClient, cache: cache}, nil
}

// Close this client instance; must be called to dispose of resources
func (c *Client) Close() error {
	return c.cache.Save()
}

// LockFile attempts to lock a file on the current remote
// path must be relative to the root of the repository
// Returns the lock id if successful, or an error
func (c *Client) LockFile(path string) (Lock, error) {

	// TODO: this is not really the constraint we need to avoid merges, improve as per proposal
	latest, err := git.CurrentRemoteRef()
	if err != nil {
		return Lock{}, err
	}

	s, resp := c.apiClient.Locks.Lock(&api.LockRequest{
		Path:               path,
		Committer:          api.NewCommitter(c.cfg.CurrentCommitter()),
		LatestRemoteCommit: latest.Sha,
	})

	if _, err := c.apiClient.Do(s); err != nil {
		return Lock{}, fmt.Errorf("Error communicating with LFS API: %v", err)
	}

	if len(resp.Err) > 0 {
		return Lock{}, fmt.Errorf("Server unable to create lock: %v", resp.Err)
	}

	lock := c.newLockFromApi(*resp.Lock)

	if err := c.cache.Add(lock); err != nil {
		return Lock{}, fmt.Errorf("Error caching lock information: %v", err)
	}

	// Ensure writeable on return
	return lock, tools.SetFileWriteFlag(path, true)
}

// UnlockFile attempts to unlock a file on the current remote
// path must be relative to the root of the repository
// Force causes the file to be unlocked from other users as well
func (c *Client) UnlockFile(path string, force bool) error {

	id, err := c.lockIdFromPath(path)
	if err != nil {
		return fmt.Errorf("Unable to get lock id: %v", err)
	}

	err = c.UnlockFileById(id, force)
	if err != nil {
		return err
	}

	// Make non-writeable if required
	if c.IsFileLockable(path) &&
		config.Config.Os.Bool("GIT_LFS_SET_LOCKABLE_READONLY", true) {
		return tools.SetFileWriteFlag(path, false)
	}
	return nil

}

// UnlockFileById attempts to unlock a lock with a given id on the current remote
// Force causes the file to be unlocked from other users as well
func (c *Client) UnlockFileById(id string, force bool) error {
	s, resp := c.apiClient.Locks.Unlock(id, force)

	if _, err := c.apiClient.Do(s); err != nil {
		return fmt.Errorf("Error communicating with LFS API: %v", err)
	}

	if len(resp.Err) > 0 {
		return fmt.Errorf("Server unable to unlock lock: %v", resp.Err)
	}

	if err := c.cache.RemoveById(id); err != nil {
		return fmt.Errorf("Error caching unlock information: %v", err)
	}

	return nil
}

// Lock is a record of a locked file
type Lock struct {
	// Id is the unique identifier corresponding to this particular Lock. It
	// must be consistent with the local copy, and the server's copy.
	Id string
	// Path is an absolute path to the file that is locked as a part of this
	// lock.
	Path string
	// Name is the name of the person holding this lock
	Name string
	// Email address of the person holding this lock
	Email string
	// LockedAt is the time at which this lock was acquired.
	LockedAt time.Time
}

func (c *Client) newLockFromApi(a api.Lock) Lock {
	return Lock{
		Id:       a.Id,
		Path:     a.Path,
		Name:     a.Committer.Name,
		Email:    a.Committer.Email,
		LockedAt: a.LockedAt,
	}
}

// SearchLocks returns a channel of locks which match the given name/value filter
// If limit > 0 then search stops at that number of locks
// If localOnly = true, don't query the server & report only own local locks
func (c *Client) SearchLocks(filter map[string]string, limit int, localOnly bool) (locks []Lock, err error) {

	if localOnly {
		return c.searchCachedLocks(filter, limit)
	} else {
		return c.searchRemoteLocks(filter, limit)
	}
}

func (c *Client) searchCachedLocks(filter map[string]string, limit int) ([]Lock, error) {
	cachedlocks := c.cache.Locks()
	path, filterByPath := filter["path"]
	id, filterById := filter["id"]
	lockCount := 0
	locks := make([]Lock, 0, len(cachedlocks))
	for _, l := range cachedlocks {
		// Manually filter by Path/Id
		if (filterByPath && path != l.Path) ||
			(filterById && id != l.Id) {
			continue
		}
		locks = append(locks, l)
		lockCount++
		if limit > 0 && lockCount >= limit {
			break
		}
	}
	return locks, nil
}

func (c *Client) searchRemoteLocks(filter map[string]string, limit int) ([]Lock, error) {
	locks := make([]Lock, 0, limit)

	apifilters := make([]api.Filter, 0, len(filter))
	for k, v := range filter {
		apifilters = append(apifilters, api.Filter{k, v})
	}
	query := &api.LockSearchRequest{Filters: apifilters}
	for {
		s, resp := c.apiClient.Locks.Search(query)
		if _, err := c.apiClient.Do(s); err != nil {
			return locks, fmt.Errorf("Error communicating with LFS API: %v", err)
		}

		if resp.Err != "" {
			return locks, fmt.Errorf("Error response from LFS API: %v", resp.Err)
		}

		for _, l := range resp.Locks {
			locks = append(locks, c.newLockFromApi(l))
			if limit > 0 && len(locks) >= limit {
				// Exit outer loop too
				return locks, nil
			}
		}

		if resp.NextCursor != "" {
			query.Cursor = resp.NextCursor
		} else {
			break
		}
	}

	return locks, nil

}

// lockIdFromPath makes a call to the LFS API and resolves the ID for the locked
// locked at the given path.
//
// If the API call failed, an error will be returned. If multiple locks matched
// the given path (should not happen during real-world usage), an error will be
// returnd. If no locks matched the given path, an error will be returned.
//
// If the API call is successful, and only one lock matches the given filepath,
// then its ID will be returned, along with a value of "nil" for the error.
func (c *Client) lockIdFromPath(path string) (string, error) {
	s, resp := c.apiClient.Locks.Search(&api.LockSearchRequest{
		Filters: []api.Filter{
			{"path", path},
		},
	})

	if _, err := c.apiClient.Do(s); err != nil {
		return "", err
	}

	switch len(resp.Locks) {
	case 0:
		return "", ErrNoMatchingLocks
	case 1:
		return resp.Locks[0].Id, nil
	default:
		return "", ErrLockAmbiguous
	}
}

// Fetch locked files for the current committer and cache them locally
// This can be used to sync up locked files when moving machines
func (c *Client) refreshLockCache() error {
	// TODO: filters don't seem to currently define how to search for a
	// committer's email. Is it "committer.email"? For now, just iterate
	locks, err := c.SearchLocks(nil, 0, false)
	if err != nil {
		return err
	}

	// We're going to overwrite the entire local cache
	c.cache.Clear()

	_, email := c.cfg.CurrentCommitter()
	for _, l := range locks {
		if l.Email == email {
			c.cache.Add(l)
		}
	}

	return nil
}

// IsFileLockedByCurrentCommitter returns whether a file is locked by the
// current committer, as cached locally
func (c *Client) IsFileLockedByCurrentCommitter(path string) bool {

	filter := map[string]string{"path": path}
	locks, err := c.searchCachedLocks(filter, 1)
	if err != nil {
		tracerx.Printf("Error searching cached locks: %s\nForcing remote search", err)
		locks, _ = c.searchRemoteLocks(filter, 1)
	}
	return len(locks) > 0
}

func init() {
	kv.RegisterTypeForStorage(&Lock{})
}
<|endoftext|>


<commit_before>// Copyright 2016, RadiantBlue Technologies, Inc.
//
// 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 logger

import (
	_ "fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/venicegeo/pz-gocommon/gocommon"
)

type Server struct {
	service *Service
	Routes  []piazza.RouteData
}

func (server *Server) handleGetRoot(c *gin.Context) {
	resp := server.service.GetRoot()
	c.IndentedJSON(resp.StatusCode, resp)
}

func (server *Server) handlePostMessage(c *gin.Context) {
	var mssg Message
	err := c.BindJSON(&mssg)
	if err != nil {
		resp := &piazza.JsonResponse{StatusCode: http.StatusBadRequest, Message: err.Error()}
		c.IndentedJSON(resp.StatusCode, resp)
	}
	resp := server.service.PostMessage(&mssg)
	c.IndentedJSON(resp.StatusCode, resp)
}

func (server *Server) handleGetStats(c *gin.Context) {
	resp := server.service.GetStats()
	c.IndentedJSON(resp.StatusCode, resp)
}

func (server *Server) handleGetMessage(c *gin.Context) {
	params := piazza.NewQueryParams(c.Request)
	resp := server.service.GetMessage(params)
	c.IndentedJSON(resp.StatusCode, resp)
}

func (server *Server) Init(service *Service) {
	server.service = service

	server.Routes = []piazza.RouteData{
		{"GET", "/", server.handleGetRoot},
		{"GET", "/message", server.handleGetMessage},
		{"POST", "/message", server.handlePostMessage},
		{"GET", "/admin/stats", server.handleGetStats},
	}
}
<commit_msg>debugging<commit_after>// Copyright 2016, RadiantBlue Technologies, Inc.
//
// 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 logger

import (
	_ "fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/venicegeo/pz-gocommon/gocommon"
)

type Server struct {
	service *Service
	Routes  []piazza.RouteData
}

func (server *Server) handleGetRoot(c *gin.Context) {
	resp := server.service.GetRoot()
	piazza.GinReturnJson(c, resp)
}

func (server *Server) handlePostMessage(c *gin.Context) {
	var mssg Message
	err := c.BindJSON(&mssg)
	if err != nil {
		resp := &piazza.JsonResponse{StatusCode: http.StatusBadRequest, Message: err.Error()}
		c.IndentedJSON(resp.StatusCode, resp)
	}
	resp := server.service.PostMessage(&mssg)
	piazza.GinReturnJson(c, resp)
}

func (server *Server) handleGetStats(c *gin.Context) {
	resp := server.service.GetStats()
	piazza.GinReturnJson(c, resp)
}

func (server *Server) handleGetMessage(c *gin.Context) {
	params := piazza.NewQueryParams(c.Request)
	resp := server.service.GetMessage(params)
	piazza.GinReturnJson(c, resp)
}

func (server *Server) Init(service *Service) {
	server.service = service

	server.Routes = []piazza.RouteData{
		{"GET", "/", server.handleGetRoot},
		{"GET", "/message", server.handleGetMessage},
		{"POST", "/message", server.handlePostMessage},
		{"GET", "/admin/stats", server.handleGetStats},
	}
}
<|endoftext|>


<commit_before>// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This pckage should not import any other terraform packages.
package version

import (
	"fmt"

	version "github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
const Version = "0.11.4"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
var Prerelease = ""

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer = version.Must(version.NewVersion(Version))

// Header is the header name used to send the current terraform version
// in http requests.
const Header = "Terraform-Version"

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}
<commit_msg>release: clean up after v0.11.4<commit_after>// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This pckage should not import any other terraform packages.
package version

import (
	"fmt"

	version "github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
const Version = "0.11.5"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
var Prerelease = "dev"

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer = version.Must(version.NewVersion(Version))

// Header is the header name used to send the current terraform version
// in http requests.
const Header = "Terraform-Version"

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}
<|endoftext|>


<commit_before>package version

// NOTE: we should probably be versioning the ABCI and the abci-cli separately

const Maj = "0"
const Min = "7"
const Fix = "0"

const Version = "0.7.0"
<commit_msg>update version<commit_after>package version

// NOTE: we should probably be versioning the ABCI and the abci-cli separately

const Maj = "0"
const Min = "7"
const Fix = "1"

const Version = "0.7.1"
<|endoftext|>


<commit_before>/*
   Copyright 2014 CoreOS, Inc.

   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 version

const (
	Version = "0.1.9+git"
)
<commit_msg>version: bump to 0.2.0<commit_after>/*
   Copyright 2014 CoreOS, Inc.

   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 version

const (
	Version = "0.2.0"
)
<|endoftext|>


<commit_before>package version

const Version = "0.1.3+git"
<commit_msg>chore(release): bump version to 0.1.4+git<commit_after>package version

const Version = "0.1.4+git"
<|endoftext|>


<commit_before>package lua

//#include <lua.h>
//#include <lauxlib.h>
//#include <lualib.h>
//#include <stdlib.h>
//#include "golua.h"
import "C"
import "unsafe"

type LuaError struct {
	code       int
	message    string
	stackTrace []LuaStackEntry
}

func (err *LuaError) Error() string {
	return err.message
}

func (err *LuaError) Code() int {
	return err.code
}

func (err *LuaError) StackTrace() []LuaStackEntry {
	return err.stackTrace
}

// luaL_argcheck
func (L *State) ArgCheck(cond bool, narg int, extramsg string) {
	if cond {
		Cextramsg := C.CString(extramsg)
		defer C.free(unsafe.Pointer(Cextramsg))
		C.luaL_argerror(L.s, C.int(narg), Cextramsg)
	}
}

// luaL_argerror
func (L *State) ArgError(narg int, extramsg string) int {
	Cextramsg := C.CString(extramsg)
	defer C.free(unsafe.Pointer(Cextramsg))
	return int(C.luaL_argerror(L.s, C.int(narg), Cextramsg))
}

// luaL_callmeta
func (L *State) CallMeta(obj int, e string) int {
	Ce := C.CString(e)
	defer C.free(unsafe.Pointer(Ce))
	return int(C.luaL_callmeta(L.s, C.int(obj), Ce))
}

// luaL_checkany
func (L *State) CheckAny(narg int) {
	C.luaL_checkany(L.s, C.int(narg))
}

// luaL_checkinteger
func (L *State) CheckInteger(narg int) int {
	return int(C.luaL_checkinteger(L.s, C.int(narg)))
}

// luaL_checknumber
func (L *State) CheckNumber(narg int) float64 {
	return float64(C.luaL_checknumber(L.s, C.int(narg)))
}

// luaL_checkstring
func (L *State) CheckString(narg int) string {
	var length C.size_t
	return C.GoString(C.luaL_checklstring(L.s, C.int(narg), &length))
}

// luaL_checkoption
//
// BUG(everyone_involved): not implemented
func (L *State) CheckOption(narg int, def string, lst []string) int {
	//TODO: complication: lst conversion to const char* lst[] from string slice
	return 0
}

// luaL_checktype
func (L *State) CheckType(narg int, t LuaValType) {
	C.luaL_checktype(L.s, C.int(narg), C.int(t))
}

// luaL_checkudata
func (L *State) CheckUdata(narg int, tname string) unsafe.Pointer {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	return unsafe.Pointer(C.luaL_checkudata(L.s, C.int(narg), Ctname))
}

// Executes file, returns nil for no errors or the lua error string on failure
func (L *State) DoFile(filename string) error {
	if r := L.LoadFile(filename); r != 0 {
		return &LuaError{r, L.ToString(-1), L.StackTrace()}
	}
	return L.Call(0, LUA_MULTRET)
}

// Executes the string, returns nil for no errors or the lua error string on failure
func (L *State) DoString(str string) error {
	if r := L.LoadString(str); r != 0 {
		return &LuaError{r, L.ToString(-1), L.StackTrace()}
	}
	return L.Call(0, LUA_MULTRET)
}

// Like DoString but panics on error
func (L *State) MustDoString(str string) {
	if err := L.DoString(str); err != nil {
		panic(err)
	}
}

// luaL_getmetafield
func (L *State) GetMetaField(obj int, e string) bool {
	Ce := C.CString(e)
	defer C.free(unsafe.Pointer(Ce))
	return C.luaL_getmetafield(L.s, C.int(obj), Ce) != 0
}

// luaL_getmetatable
func (L *State) LGetMetaTable(tname string) {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	C.lua_getfield(L.s, LUA_REGISTRYINDEX, Ctname)
}

// luaL_gsub
func (L *State) GSub(s string, p string, r string) string {
	Cs := C.CString(s)
	Cp := C.CString(p)
	Cr := C.CString(r)
	defer func() {
		C.free(unsafe.Pointer(Cs))
		C.free(unsafe.Pointer(Cp))
		C.free(unsafe.Pointer(Cr))
	}()

	return C.GoString(C.luaL_gsub(L.s, Cs, Cp, Cr))
}

// luaL_loadfile
func (L *State) LoadFile(filename string) int {
	Cfilename := C.CString(filename)
	defer C.free(unsafe.Pointer(Cfilename))
	return int(C.luaL_loadfile(L.s, Cfilename))
}

// luaL_loadstring
func (L *State) LoadString(s string) int {
	Cs := C.CString(s)
	defer C.free(unsafe.Pointer(Cs))
	return int(C.luaL_loadstring(L.s, Cs))
}

// luaL_loadbuffer
func (L *State) LoadBuffer(buff string, size int, name string) int {
	Cbuff := C.CString(buff)
	Cname := C.CString(name)
	Csize := C.size_t(size)
	defer C.free(unsafe.Pointer(Cbuff))
	defer C.free(unsafe.Pointer(Cname))
	//defer C.free(unsafe.Pointer(Csize))
	return int(C.luaL_loadbuffer(L.s, Cbuff, Csize, Cname))
}

// luaL_newmetatable
func (L *State) NewMetaTable(tname string) bool {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	return C.luaL_newmetatable(L.s, Ctname) != 0
}

// luaL_newstate
func NewState() *State {
	ls := (C.luaL_newstate())
	L := newState(ls)
	return L
}

// luaL_openlibs
func (L *State) OpenLibs() {
	C.luaL_openlibs(L.s)
	//C.clua_hide_pcall(L.s)
}

// luaL_optinteger
func (L *State) OptInteger(narg int, d int) int {
	return int(C.luaL_optinteger(L.s, C.int(narg), C.lua_Integer(d)))
}

// luaL_optnumber
func (L *State) OptNumber(narg int, d float64) float64 {
	return float64(C.luaL_optnumber(L.s, C.int(narg), C.lua_Number(d)))
}

// luaL_optstring
func (L *State) OptString(narg int, d string) string {
	var length C.size_t
	Cd := C.CString(d)
	defer C.free(unsafe.Pointer(Cd))
	return C.GoString(C.luaL_optlstring(L.s, C.int(narg), Cd, &length))
}

// luaL_ref
func (L *State) Ref(t int) int {
	return int(C.luaL_ref(L.s, C.int(t)))
}

// luaL_typename
func (L *State) LTypename(index int) string {
	return C.GoString(C.lua_typename(L.s, C.lua_type(L.s, C.int(index))))
}

// luaL_unref
func (L *State) Unref(t int, ref int) {
	C.luaL_unref(L.s, C.int(t), C.int(ref))
}

// luaL_where
func (L *State) Where(lvl int) {
	C.luaL_where(L.s, C.int(lvl))
}

// clua_fdump
func (L *State) fdump() string {
	var sz *C.int
	defer C.free(unsafe.Pointer(sz))
	return C.GoStringN(C.clua_fdump(L.s, sz), *sz)
}
<commit_msg>Export FDump<commit_after>package lua

//#include <lua.h>
//#include <lauxlib.h>
//#include <lualib.h>
//#include <stdlib.h>
//#include "golua.h"
import "C"
import "unsafe"

type LuaError struct {
	code       int
	message    string
	stackTrace []LuaStackEntry
}

func (err *LuaError) Error() string {
	return err.message
}

func (err *LuaError) Code() int {
	return err.code
}

func (err *LuaError) StackTrace() []LuaStackEntry {
	return err.stackTrace
}

// luaL_argcheck
func (L *State) ArgCheck(cond bool, narg int, extramsg string) {
	if cond {
		Cextramsg := C.CString(extramsg)
		defer C.free(unsafe.Pointer(Cextramsg))
		C.luaL_argerror(L.s, C.int(narg), Cextramsg)
	}
}

// luaL_argerror
func (L *State) ArgError(narg int, extramsg string) int {
	Cextramsg := C.CString(extramsg)
	defer C.free(unsafe.Pointer(Cextramsg))
	return int(C.luaL_argerror(L.s, C.int(narg), Cextramsg))
}

// luaL_callmeta
func (L *State) CallMeta(obj int, e string) int {
	Ce := C.CString(e)
	defer C.free(unsafe.Pointer(Ce))
	return int(C.luaL_callmeta(L.s, C.int(obj), Ce))
}

// luaL_checkany
func (L *State) CheckAny(narg int) {
	C.luaL_checkany(L.s, C.int(narg))
}

// luaL_checkinteger
func (L *State) CheckInteger(narg int) int {
	return int(C.luaL_checkinteger(L.s, C.int(narg)))
}

// luaL_checknumber
func (L *State) CheckNumber(narg int) float64 {
	return float64(C.luaL_checknumber(L.s, C.int(narg)))
}

// luaL_checkstring
func (L *State) CheckString(narg int) string {
	var length C.size_t
	return C.GoString(C.luaL_checklstring(L.s, C.int(narg), &length))
}

// luaL_checkoption
//
// BUG(everyone_involved): not implemented
func (L *State) CheckOption(narg int, def string, lst []string) int {
	//TODO: complication: lst conversion to const char* lst[] from string slice
	return 0
}

// luaL_checktype
func (L *State) CheckType(narg int, t LuaValType) {
	C.luaL_checktype(L.s, C.int(narg), C.int(t))
}

// luaL_checkudata
func (L *State) CheckUdata(narg int, tname string) unsafe.Pointer {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	return unsafe.Pointer(C.luaL_checkudata(L.s, C.int(narg), Ctname))
}

// Executes file, returns nil for no errors or the lua error string on failure
func (L *State) DoFile(filename string) error {
	if r := L.LoadFile(filename); r != 0 {
		return &LuaError{r, L.ToString(-1), L.StackTrace()}
	}
	return L.Call(0, LUA_MULTRET)
}

// Executes the string, returns nil for no errors or the lua error string on failure
func (L *State) DoString(str string) error {
	if r := L.LoadString(str); r != 0 {
		return &LuaError{r, L.ToString(-1), L.StackTrace()}
	}
	return L.Call(0, LUA_MULTRET)
}

// Like DoString but panics on error
func (L *State) MustDoString(str string) {
	if err := L.DoString(str); err != nil {
		panic(err)
	}
}

// luaL_getmetafield
func (L *State) GetMetaField(obj int, e string) bool {
	Ce := C.CString(e)
	defer C.free(unsafe.Pointer(Ce))
	return C.luaL_getmetafield(L.s, C.int(obj), Ce) != 0
}

// luaL_getmetatable
func (L *State) LGetMetaTable(tname string) {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	C.lua_getfield(L.s, LUA_REGISTRYINDEX, Ctname)
}

// luaL_gsub
func (L *State) GSub(s string, p string, r string) string {
	Cs := C.CString(s)
	Cp := C.CString(p)
	Cr := C.CString(r)
	defer func() {
		C.free(unsafe.Pointer(Cs))
		C.free(unsafe.Pointer(Cp))
		C.free(unsafe.Pointer(Cr))
	}()

	return C.GoString(C.luaL_gsub(L.s, Cs, Cp, Cr))
}

// luaL_loadfile
func (L *State) LoadFile(filename string) int {
	Cfilename := C.CString(filename)
	defer C.free(unsafe.Pointer(Cfilename))
	return int(C.luaL_loadfile(L.s, Cfilename))
}

// luaL_loadstring
func (L *State) LoadString(s string) int {
	Cs := C.CString(s)
	defer C.free(unsafe.Pointer(Cs))
	return int(C.luaL_loadstring(L.s, Cs))
}

// luaL_loadbuffer
func (L *State) LoadBuffer(buff string, size int, name string) int {
	Cbuff := C.CString(buff)
	Cname := C.CString(name)
	Csize := C.size_t(size)
	defer C.free(unsafe.Pointer(Cbuff))
	defer C.free(unsafe.Pointer(Cname))
	//defer C.free(unsafe.Pointer(Csize))
	return int(C.luaL_loadbuffer(L.s, Cbuff, Csize, Cname))
}

// luaL_newmetatable
func (L *State) NewMetaTable(tname string) bool {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	return C.luaL_newmetatable(L.s, Ctname) != 0
}

// luaL_newstate
func NewState() *State {
	ls := (C.luaL_newstate())
	L := newState(ls)
	return L
}

// luaL_openlibs
func (L *State) OpenLibs() {
	C.luaL_openlibs(L.s)
	//C.clua_hide_pcall(L.s)
}

// luaL_optinteger
func (L *State) OptInteger(narg int, d int) int {
	return int(C.luaL_optinteger(L.s, C.int(narg), C.lua_Integer(d)))
}

// luaL_optnumber
func (L *State) OptNumber(narg int, d float64) float64 {
	return float64(C.luaL_optnumber(L.s, C.int(narg), C.lua_Number(d)))
}

// luaL_optstring
func (L *State) OptString(narg int, d string) string {
	var length C.size_t
	Cd := C.CString(d)
	defer C.free(unsafe.Pointer(Cd))
	return C.GoString(C.luaL_optlstring(L.s, C.int(narg), Cd, &length))
}

// luaL_ref
func (L *State) Ref(t int) int {
	return int(C.luaL_ref(L.s, C.int(t)))
}

// luaL_typename
func (L *State) LTypename(index int) string {
	return C.GoString(C.lua_typename(L.s, C.lua_type(L.s, C.int(index))))
}

// luaL_unref
func (L *State) Unref(t int, ref int) {
	C.luaL_unref(L.s, C.int(t), C.int(ref))
}

// luaL_where
func (L *State) Where(lvl int) {
	C.luaL_where(L.s, C.int(lvl))
}

// clua_fdump
func (L *State) FDump() string {
	var sz *C.int
	defer C.free(unsafe.Pointer(sz))
	return C.GoStringN(C.clua_fdump(L.s, sz), *sz)
}
<|endoftext|>


<commit_before>package version

const Version = "2.0.0+git"
<commit_msg>release v2.1.0<commit_after>package version

const Version = "2.1.0"
<|endoftext|>


<commit_before>// Copyright 2017 Istio 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 version for fortio holds version information and build information.
package version // import "fortio.org/fortio/version"
import (
	"fmt"
	"runtime"

	"fortio.org/fortio/log"
)

const (
	major = 1
	minor = 3
	patch = 1

	debug = false // turn on to debug init()
)

var (
	// The following are set by Dockerfile during link time:
	tag       = "n/a"
	buildInfo = "unknown"
	// Number of lines in git status --porcelain; 0 means clean
	gitstatus = "0" // buildInfo default is unknown so no need to add -dirty
	// computed in init()
	version     = ""
	longVersion = ""
)

// Major returns the numerical major version number (first digit of version.Short()).
func Major() int {
	return major
}

// Minor returns the numerical minor version number (second digit of version.Short()).
func Minor() int {
	return minor
}

// Patch returns the numerical patch level (third digit of version.Short()).
func Patch() int {
	return patch
}

// Short returns the 3 digit short version string Major.Minor.Patch[-pre]
// version.Short() is the overall project version (used to version json
// output too). "-pre" is added when the version doesn't match exactly
// a git tag or the build isn't from a clean source tree. (only standard
// dockerfile based build of a clean, tagged source tree should print "X.Y.Z"
// as short version).
func Short() string {
	return version
}

// Long returns the full version and build information.
// Format is "X.Y.X[-pre] YYYY-MM-DD HH:MM SHA[-dirty]" date and time is
// the build date (UTC), sha is the git sha of the source tree.
func Long() string {
	return longVersion
}

// Carefully manually tested all the combinations in pair with Dockerfile
func init() {
	if debug {
		log.SetLogLevel(log.Debug)
	}
	version = fmt.Sprintf("%d.%d.%d", major, minor, patch)
	clean := (gitstatus == "0")
	// The docker build will pass the git tag to the build, if it is clean
	// from a tag it will look like v0.7.0
	if tag != "v"+version || !clean {
		log.Debugf("tag is %v, clean is %v marking as pre release", tag, clean)
		version += "-pre"
	}
	if !clean {
		buildInfo += "-dirty"
		log.Debugf("gitstatus is %q, marking buildinfo as dirty: %v", gitstatus, buildInfo)
	}
	longVersion = version + " " + buildInfo + " " + runtime.Version()
}
<commit_msg>version bump/preparation for next release<commit_after>// Copyright 2017 Istio 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 version for fortio holds version information and build information.
package version // import "fortio.org/fortio/version"
import (
	"fmt"
	"runtime"

	"fortio.org/fortio/log"
)

const (
	major = 1
	minor = 3
	patch = 2

	debug = false // turn on to debug init()
)

var (
	// The following are set by Dockerfile during link time:
	tag       = "n/a"
	buildInfo = "unknown"
	// Number of lines in git status --porcelain; 0 means clean
	gitstatus = "0" // buildInfo default is unknown so no need to add -dirty
	// computed in init()
	version     = ""
	longVersion = ""
)

// Major returns the numerical major version number (first digit of version.Short()).
func Major() int {
	return major
}

// Minor returns the numerical minor version number (second digit of version.Short()).
func Minor() int {
	return minor
}

// Patch returns the numerical patch level (third digit of version.Short()).
func Patch() int {
	return patch
}

// Short returns the 3 digit short version string Major.Minor.Patch[-pre]
// version.Short() is the overall project version (used to version json
// output too). "-pre" is added when the version doesn't match exactly
// a git tag or the build isn't from a clean source tree. (only standard
// dockerfile based build of a clean, tagged source tree should print "X.Y.Z"
// as short version).
func Short() string {
	return version
}

// Long returns the full version and build information.
// Format is "X.Y.X[-pre] YYYY-MM-DD HH:MM SHA[-dirty]" date and time is
// the build date (UTC), sha is the git sha of the source tree.
func Long() string {
	return longVersion
}

// Carefully manually tested all the combinations in pair with Dockerfile
func init() {
	if debug {
		log.SetLogLevel(log.Debug)
	}
	version = fmt.Sprintf("%d.%d.%d", major, minor, patch)
	clean := (gitstatus == "0")
	// The docker build will pass the git tag to the build, if it is clean
	// from a tag it will look like v0.7.0
	if tag != "v"+version || !clean {
		log.Debugf("tag is %v, clean is %v marking as pre release", tag, clean)
		version += "-pre"
	}
	if !clean {
		buildInfo += "-dirty"
		log.Debugf("gitstatus is %q, marking buildinfo as dirty: %v", gitstatus, buildInfo)
	}
	longVersion = version + " " + buildInfo + " " + runtime.Version()
}
<|endoftext|>


<commit_before>package version

// VERSION ...
const VERSION = "1.1.4"
<commit_msg>v1.1.5<commit_after>package version

// VERSION ...
const VERSION = "1.1.5"
<|endoftext|>


<commit_before>package land

import (
	"github.com/Nyarum/noterius/core"

	"io"
	"log"
	"net"
)

// Application struct for project and his variables
type Application struct {
	Config       core.Config
	Database     core.Database
	ErrorHandler func(c net.Conn)
}

// Run function for starting server
func (a *Application) Run() (err error) {
	listen, err := net.Listen("tcp", a.Config.Base.IP+":"+a.Config.Base.Port)
	if err != nil {
		return
	}

	for {
		client, err := listen.Accept()
		if err != nil {
			log.Println(err)
			continue
		}

		go func(c net.Conn, conf core.Config) {
			defer a.ErrorHandler(c)

			log.Println("Client is connected:", c.RemoteAddr())

			var (
				bytesAlloc      []byte      = make([]byte, conf.Option.LenBuffer)
				readBytesSocket chan string = make(chan string)
			)

			go ClientLive(c, readBytesSocket, conf)

			for {
				if _, err := c.Read(bytesAlloc); err == io.EOF {
					log.Printf("Client [%v] is disconnected\n", c.RemoteAddr())
					break
				} else {
					log.Printf("Client [%v] is error read packet, err - %v\n", c.RemoteAddr(), err)
				}

				readBytesSocket <- string(bytesAlloc)
			}
		}(client, a.Config)
	}
}
<commit_msg>Update error handler for connect<commit_after>package land

import (
	"github.com/Nyarum/noterius/core"

	"io"
	"log"
	"net"
)

// Application struct for project and his variables
type Application struct {
	Config       core.Config
	Database     core.Database
	ErrorHandler func(c net.Conn)
}

// Run function for starting server
func (a *Application) Run() (err error) {
	listen, err := net.Listen("tcp", a.Config.Base.IP+":"+a.Config.Base.Port)
	if err != nil {
		return
	}

	for {
		client, err := listen.Accept()
		if err != nil {
			log.Println(err)
			continue
		}

		go func(c net.Conn, conf core.Config) {
			defer a.ErrorHandler(c)

			log.Println("Client is connected:", c.RemoteAddr())

			var (
				bytesAlloc      []byte      = make([]byte, conf.Option.LenBuffer)
				readBytesSocket chan string = make(chan string)
			)

			go ClientLive(c, readBytesSocket, conf)

			for {
				if _, err := c.Read(bytesAlloc); err == io.EOF {
					log.Printf("Client [%v] is disconnected\n", c.RemoteAddr())
					break
				} else if err != nil {
					log.Printf("Client [%v] is error read packet, err - %v\n", c.RemoteAddr(), err)
				}

				readBytesSocket <- string(bytesAlloc)
			}
		}(client, a.Config)
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Matt Jibson <matt.jibson@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package goapp

import (
	"bytes"
	"compress/gzip"
	"encoding/base64"
	"io/ioutil"
	"net/url"
	"time"

	"appengine"
	"appengine/datastore"
	"appengine/taskqueue"
)

type User struct {
	_kind    string    `goon:"kind,U"`
	Id       string    `datastore:"-" goon:"id"`
	Email    string    `datastore:"e"`
	Messages []string  `datastore:"m,noindex"`
	Read     time.Time `datastore:"r,noindex"`
	Options  string    `datastore:"o,noindex"`
	Account  int       `datastore:"a,noindex"`
	Created  time.Time `datastore:"d,noindex"`
}

const (
	AFree = iota
	ADev
	APaid
)

func (u *User) String() string {
	return u.Email
}

// parent: User, key: "data"
type UserData struct {
	_kind  string         `goon:"kind,UD"`
	Id     string         `datastore:"-" goon:"id"`
	Parent *datastore.Key `datastore:"-" goon:"parent"`
	Opml   []byte         `datastore:"o,noindex"`
	Read   []byte         `datastore:"r,noindex"`
}

// parent: User, key: time.Now().UnixNano()
type UserOpml struct {
	_kind      string         `goon:"kind,UO"`
	Id         int64          `datastore:"-" goon:"id"`
	Parent     *datastore.Key `datastore:"-" goon:"parent"`
	Opml       []byte         `datastore:"o,noindex"`
	Compressed []byte         `datastore:"z,noindex"`
}

func (uo *UserOpml) opml() []byte {
	if len(uo.Compressed) > 0 {
		buf := bytes.NewReader(uo.Compressed)
		if gz, err := gzip.NewReader(buf); err == nil {
			defer gz.Close()
			if b, _ := ioutil.ReadAll(gz); err == nil {
				return b
			}
		}
	}
	return uo.Opml
}

type readStory struct {
	Feed, Story string
}

type Read map[readStory]bool

type Feed struct {
	_kind      string        `goon:"kind,F"`
	Url        string        `datastore:"-" goon:"id"`
	Title      string        `datastore:"t,noindex"`
	Updated    time.Time     `datastore:"u,noindex"`
	Date       time.Time     `datastore:"d,noindex"`
	Checked    time.Time     `datastore:"c,noindex"`
	NextUpdate time.Time     `datastore:"n"`
	Link       string        `datastore:"l,noindex"`
	Errors     int           `datastore:"e,noindex"`
	Image      string        `datastore:"i,noindex"`
	Subscribed time.Time     `datastore:"s,noindex"`
	Average    time.Duration `datastore:"a,noindex"`
	LastViewed time.Time     `datastore:"v,noindex"`
}

func (f Feed) Subscribe(c appengine.Context) {
	if !f.IsSubscribed() {
		t := taskqueue.NewPOSTTask(routeUrl("subscribe-feed"), url.Values{
			"feed": {f.Url},
		})
		if _, err := taskqueue.Add(c, t, "update-manual"); err != nil {
			c.Errorf("taskqueue error: %v", err.Error())
		} else {
			c.Warningf("subscribe feed: %v", f.Url)
		}
	}
}

func (f Feed) IsSubscribed() bool {
	return !ENABLE_PUBSUBHUBBUB || time.Now().Before(f.Subscribed)
}

func (f Feed) PubSubURL() string {
	b := base64.URLEncoding.EncodeToString([]byte(f.Url))
	ru, _ := router.Get("subscribe-callback").URL()
	ru.Scheme = "http"
	ru.Host = PUBSUBHUBBUB_HOST
	ru.RawQuery = url.Values{
		"feed": {b},
	}.Encode()
	return ru.String()
}

func (f Feed) NotViewed() bool {
	return time.Since(f.LastViewed) > notViewedDisabled
}

// parent: Feed, key: story ID
type Story struct {
	_kind        string         `goon:"kind,S"`
	Id           string         `datastore:"-" goon:"id"`
	Parent       *datastore.Key `datastore:"-" goon:"parent" json:"-"`
	Title        string         `datastore:"t,noindex"`
	Link         string         `datastore:"l,noindex"`
	Created      time.Time      `datastore:"c" json:"-"`
	Published    time.Time      `datastore:"p,noindex" json:"-"`
	Updated      time.Time      `datastore:"u,noindex" json:"-"`
	Date         int64          `datastore:"e,noindex"`
	Author       string         `datastore:"a,noindex" json:",omitempty"`
	Summary      string         `datastore:"s,noindex"`
	MediaContent string         `datastore:"m,noindex" json:",omitempty"`

	content string
}

const IDX_COL = "c"

// parent: Story, key: 1
type StoryContent struct {
	_kind      string         `goon:"kind,SC"`
	Id         int64          `datastore:"-" goon:"id"`
	Parent     *datastore.Key `datastore:"-" goon:"parent"`
	Content    string         `datastore:"c,noindex"`
	Compressed []byte         `datastore:"z,noindex"`
}

func (sc *StoryContent) content() string {
	if len(sc.Compressed) > 0 {
		buf := bytes.NewReader(sc.Compressed)
		if gz, err := gzip.NewReader(buf); err == nil {
			defer gz.Close()
			if b, _ := ioutil.ReadAll(gz); err == nil {
				return string(b)
			}
		}
	}
	return sc.Content
}

type OpmlOutline struct {
	Outline []*OpmlOutline `xml:"outline" json:",omitempty"`
	Title   string         `xml:"title,attr,omitempty" json:",omitempty"`
	XmlUrl  string         `xml:"xmlUrl,attr,omitempty" json:",omitempty"`
	Type    string         `xml:"type,attr,omitempty" json:",omitempty"`
	Text    string         `xml:"text,attr,omitempty" json:",omitempty"`
	HtmlUrl string         `xml:"htmlUrl,attr,omitempty" json:",omitempty"`
}

type Opml struct {
	XMLName string         `xml:"opml"`
	Version string         `xml:"version,attr"`
	Title   string         `xml:"head>title"`
	Outline []*OpmlOutline `xml:"body>outline"`
}

type DateFormat struct {
	Id    int64  `datastore:"-" goon:"id"`
	_kind string `goon:"kind,DF"`
	Value string `datastore:"v"`
	Feed  string `datastore:"f"`
}

type Image struct {
	Id   string            `datastore:"-" goon:"id"`
	Blob appengine.BlobKey `datastore:"b,noindex"`
	Url  string            `datastore:"u,noindex"`
}

type Stories []*Story

func (s Stories) Len() int           { return len(s) }
func (s Stories) Less(i, j int) bool { return s[i].Created.Before(s[j].Created) }
func (s Stories) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

type Log struct {
	_kind  string         `goon:"kind,L"`
	Id     int64          `datastore:"-" goon:"id"`
	Parent *datastore.Key `datastore:"-" goon:"parent"`
	Text   string         `datastore:"t,noindex"`
}
<commit_msg>Restore this field for now<commit_after>/*
 * Copyright (c) 2013 Matt Jibson <matt.jibson@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package goapp

import (
	"bytes"
	"compress/gzip"
	"encoding/base64"
	"io/ioutil"
	"net/url"
	"time"

	"appengine"
	"appengine/datastore"
	"appengine/taskqueue"
)

type User struct {
	_kind    string    `goon:"kind,U"`
	Id       string    `datastore:"-" goon:"id"`
	Email    string    `datastore:"e"`
	Messages []string  `datastore:"m,noindex"`
	Read     time.Time `datastore:"r,noindex"`
	Options  string    `datastore:"o,noindex"`
	Account  int       `datastore:"a,noindex"`
	Created  time.Time `datastore:"d,noindex"`
}

const (
	AFree = iota
	ADev
	APaid
)

func (u *User) String() string {
	return u.Email
}

// parent: User, key: "data"
type UserData struct {
	_kind  string         `goon:"kind,UD"`
	Id     string         `datastore:"-" goon:"id"`
	Parent *datastore.Key `datastore:"-" goon:"parent"`
	Opml   []byte         `datastore:"o,noindex"`
	Read   []byte         `datastore:"r,noindex"`
}

// parent: User, key: time.Now().UnixNano()
type UserOpml struct {
	_kind      string         `goon:"kind,UO"`
	Id         int64          `datastore:"-" goon:"id"`
	Parent     *datastore.Key `datastore:"-" goon:"parent"`
	Opml       []byte         `datastore:"o,noindex"`
	Compressed []byte         `datastore:"z,noindex"`
}

func (uo *UserOpml) opml() []byte {
	if len(uo.Compressed) > 0 {
		buf := bytes.NewReader(uo.Compressed)
		if gz, err := gzip.NewReader(buf); err == nil {
			defer gz.Close()
			if b, _ := ioutil.ReadAll(gz); err == nil {
				return b
			}
		}
	}
	return uo.Opml
}

type readStory struct {
	Feed, Story string
}

type Read map[readStory]bool

type Feed struct {
	_kind      string        `goon:"kind,F"`
	Url        string        `datastore:"-" goon:"id"`
	Title      string        `datastore:"t,noindex"`
	Updated    time.Time     `datastore:"u,noindex"`
	Date       time.Time     `datastore:"d,noindex"`
	Checked    time.Time     `datastore:"c,noindex"`
	NextUpdate time.Time     `datastore:"n"`
	Link       string        `datastore:"l,noindex"`
	Errors     int           `datastore:"e,noindex"`
	Image      string        `datastore:"i,noindex"`
	Subscribed time.Time     `datastore:"s,noindex"`
	Average    time.Duration `datastore:"a,noindex"`
	LastViewed time.Time     `datastore:"v,noindex"`
	NoAds      bool          `datastore:"o,noindex"`
}

func (f Feed) Subscribe(c appengine.Context) {
	if !f.IsSubscribed() {
		t := taskqueue.NewPOSTTask(routeUrl("subscribe-feed"), url.Values{
			"feed": {f.Url},
		})
		if _, err := taskqueue.Add(c, t, "update-manual"); err != nil {
			c.Errorf("taskqueue error: %v", err.Error())
		} else {
			c.Warningf("subscribe feed: %v", f.Url)
		}
	}
}

func (f Feed) IsSubscribed() bool {
	return !ENABLE_PUBSUBHUBBUB || time.Now().Before(f.Subscribed)
}

func (f Feed) PubSubURL() string {
	b := base64.URLEncoding.EncodeToString([]byte(f.Url))
	ru, _ := router.Get("subscribe-callback").URL()
	ru.Scheme = "http"
	ru.Host = PUBSUBHUBBUB_HOST
	ru.RawQuery = url.Values{
		"feed": {b},
	}.Encode()
	return ru.String()
}

func (f Feed) NotViewed() bool {
	return time.Since(f.LastViewed) > notViewedDisabled
}

// parent: Feed, key: story ID
type Story struct {
	_kind        string         `goon:"kind,S"`
	Id           string         `datastore:"-" goon:"id"`
	Parent       *datastore.Key `datastore:"-" goon:"parent" json:"-"`
	Title        string         `datastore:"t,noindex"`
	Link         string         `datastore:"l,noindex"`
	Created      time.Time      `datastore:"c" json:"-"`
	Published    time.Time      `datastore:"p,noindex" json:"-"`
	Updated      time.Time      `datastore:"u,noindex" json:"-"`
	Date         int64          `datastore:"e,noindex"`
	Author       string         `datastore:"a,noindex" json:",omitempty"`
	Summary      string         `datastore:"s,noindex"`
	MediaContent string         `datastore:"m,noindex" json:",omitempty"`

	content string
}

const IDX_COL = "c"

// parent: Story, key: 1
type StoryContent struct {
	_kind      string         `goon:"kind,SC"`
	Id         int64          `datastore:"-" goon:"id"`
	Parent     *datastore.Key `datastore:"-" goon:"parent"`
	Content    string         `datastore:"c,noindex"`
	Compressed []byte         `datastore:"z,noindex"`
}

func (sc *StoryContent) content() string {
	if len(sc.Compressed) > 0 {
		buf := bytes.NewReader(sc.Compressed)
		if gz, err := gzip.NewReader(buf); err == nil {
			defer gz.Close()
			if b, _ := ioutil.ReadAll(gz); err == nil {
				return string(b)
			}
		}
	}
	return sc.Content
}

type OpmlOutline struct {
	Outline []*OpmlOutline `xml:"outline" json:",omitempty"`
	Title   string         `xml:"title,attr,omitempty" json:",omitempty"`
	XmlUrl  string         `xml:"xmlUrl,attr,omitempty" json:",omitempty"`
	Type    string         `xml:"type,attr,omitempty" json:",omitempty"`
	Text    string         `xml:"text,attr,omitempty" json:",omitempty"`
	HtmlUrl string         `xml:"htmlUrl,attr,omitempty" json:",omitempty"`
}

type Opml struct {
	XMLName string         `xml:"opml"`
	Version string         `xml:"version,attr"`
	Title   string         `xml:"head>title"`
	Outline []*OpmlOutline `xml:"body>outline"`
}

type DateFormat struct {
	Id    int64  `datastore:"-" goon:"id"`
	_kind string `goon:"kind,DF"`
	Value string `datastore:"v"`
	Feed  string `datastore:"f"`
}

type Image struct {
	Id   string            `datastore:"-" goon:"id"`
	Blob appengine.BlobKey `datastore:"b,noindex"`
	Url  string            `datastore:"u,noindex"`
}

type Stories []*Story

func (s Stories) Len() int           { return len(s) }
func (s Stories) Less(i, j int) bool { return s[i].Created.Before(s[j].Created) }
func (s Stories) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

type Log struct {
	_kind  string         `goon:"kind,L"`
	Id     int64          `datastore:"-" goon:"id"`
	Parent *datastore.Key `datastore:"-" goon:"parent"`
	Text   string         `datastore:"t,noindex"`
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Matt Jibson <matt.jibson@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package goapp

import (
	"appengine"
	"appengine/user"
	"fmt"
	mpg "github.com/mjibson/MiniProfiler/go/miniprofiler_gae"
	"github.com/mjibson/goon"
	"html/template"
	"net/http"
)

func serveError(w http.ResponseWriter, err error) {
	http.Error(w, err.Error(), http.StatusInternalServerError)
}

type Includes struct {
	Angular      string
	BootstrapCss string
	BootstrapJs  string
	Jquery       string
	MiniProfiler template.HTML
	Site         string
	User         *User
}

var (
	Angular      string
	BootstrapCss string
	BootstrapJs  string
	Jquery       string
)

func init() {
	angular_ver := "1.0.5"
	bootstrap_ver := "2.3.1"
	jquery_ver := "1.9.1"

	if appengine.IsDevAppServer() {
		Angular = fmt.Sprintf("/static/js/angular-%v.js", angular_ver)
		BootstrapCss = fmt.Sprintf("/static/css/bootstrap-%v.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("/static/js/bootstrap-%v.js", bootstrap_ver)
		Jquery = fmt.Sprintf("/static/js/jquery-%v.js", jquery_ver)
	} else {
		Angular = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/angularjs/%v/angular.min.js", angular_ver)
		BootstrapCss = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/css/bootstrap-combined.min.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/js/bootstrap.min.js", bootstrap_ver)
		Jquery = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/jquery/%v/jquery.min.js", jquery_ver)
	}
}

func includes(c mpg.Context) *Includes {
	i := &Includes{
		Angular:      Angular,
		BootstrapCss: BootstrapCss,
		BootstrapJs:  BootstrapJs,
		Jquery:       Jquery,
		MiniProfiler: c.P.Includes(),
		Site:         "/static/js/site.js",
	}

	if u := user.Current(c); u != nil {
		gn := goon.FromContext(c)
		user := new(User)
		if _, err := gn.GetById(user, u.ID, 0, nil); err == nil {
			i.User = user
		}
	}

	return i
}
<commit_msg>Users must have entities<commit_after>/*
 * Copyright (c) 2013 Matt Jibson <matt.jibson@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package goapp

import (
	"appengine"
	"appengine/user"
	"fmt"
	mpg "github.com/mjibson/MiniProfiler/go/miniprofiler_gae"
	"github.com/mjibson/goon"
	"html/template"
	"net/http"
)

func serveError(w http.ResponseWriter, err error) {
	http.Error(w, err.Error(), http.StatusInternalServerError)
}

type Includes struct {
	Angular      string
	BootstrapCss string
	BootstrapJs  string
	Jquery       string
	MiniProfiler template.HTML
	Site         string
	User         *User
}

var (
	Angular      string
	BootstrapCss string
	BootstrapJs  string
	Jquery       string
)

func init() {
	angular_ver := "1.0.5"
	bootstrap_ver := "2.3.1"
	jquery_ver := "1.9.1"

	if appengine.IsDevAppServer() {
		Angular = fmt.Sprintf("/static/js/angular-%v.js", angular_ver)
		BootstrapCss = fmt.Sprintf("/static/css/bootstrap-%v.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("/static/js/bootstrap-%v.js", bootstrap_ver)
		Jquery = fmt.Sprintf("/static/js/jquery-%v.js", jquery_ver)
	} else {
		Angular = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/angularjs/%v/angular.min.js", angular_ver)
		BootstrapCss = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/css/bootstrap-combined.min.css", bootstrap_ver)
		BootstrapJs = fmt.Sprintf("//netdna.bootstrapcdn.com/twitter-bootstrap/%v/js/bootstrap.min.js", bootstrap_ver)
		Jquery = fmt.Sprintf("//ajax.googleapis.com/ajax/libs/jquery/%v/jquery.min.js", jquery_ver)
	}
}

func includes(c mpg.Context) *Includes {
	i := &Includes{
		Angular:      Angular,
		BootstrapCss: BootstrapCss,
		BootstrapJs:  BootstrapJs,
		Jquery:       Jquery,
		MiniProfiler: c.P.Includes(),
		Site:         "/static/js/site.js",
	}

	if u := user.Current(c); u != nil {
		gn := goon.FromContext(c)
		user := new(User)
		if e, err := gn.GetById(user, u.ID, 0, nil); err == nil && !e.NotFound {
			i.User = user
		}
	}

	return i
}
<|endoftext|>


<commit_before>package gode

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
)

// The Node version to install.
// Override this by setting client.Version.
const DefaultNodeVersion = "1.1.0"

// The NPM version to install.
// Override this by setting client.Version.
const DefaultNpmVersion = "2.4.1"

// Client is the interface between Node and Go.
// It also setups up the Node environment if needed.
type Client struct {
	RootPath    string
	NodeVersion string
	NpmVersion  string
	Registry    string
}

// NewClient creates a new Client at the specified rootPath
// The Node installation can then be setup here with client.Setup()
func NewClient(rootPath string) *Client {
	client := &Client{
		RootPath:    rootPath,
		NodeVersion: DefaultNodeVersion,
		NpmVersion:  DefaultNpmVersion,
	}

	return client
}

// NodeBase returns the directory name for the node install
func (c *Client) NodeBase() string {
	switch {
	case runtime.GOARCH == "arm":
		return "iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-armv7l"
	case runtime.GOARCH == "386":
		return "iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-x86"
	default:
		return "iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-x64"
	}
}

func (c *Client) nodeURL() string {
	switch {
	case runtime.GOOS == "windows":
		return "https://iojs.org/dist/v" + c.NodeVersion + "/win-x86/iojs.exe"
	case runtime.GOARCH == "386":
		return "https://iojs.org/dist/v" + c.NodeVersion + "/iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-x86.tar.gz"
	case runtime.GOARCH == "arm":
		return "https://iojs.org/dist/v" + c.NodeVersion + "/iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-armv7l.tar.gz"
	default:
		return "https://iojs.org/dist/v" + c.NodeVersion + "/" + c.NodeBase() + ".tar.gz"
	}
}

func (c *Client) nodePath() string {
	switch {
	case runtime.GOOS == "windows":
		return filepath.Join(c.RootPath, c.NodeBase(), "bin", "node.exe")
	default:
		return filepath.Join(c.RootPath, c.NodeBase(), "bin", "node")
	}
}

func (c *Client) npmURL() string {
	return "http://github.com/npm/npm/archive/v" + c.NpmVersion + ".zip"
}

func (c *Client) npmPath() string {
	return filepath.Join(c.RootPath, c.NodeBase(), "lib", "node_modules", "npm", "cli.js")
}

func (c *Client) tmpDir(prefix string) string {
	root := filepath.Join(c.RootPath, "tmp")
	err := os.MkdirAll(root, 0755)
	if err != nil {
		panic(err)
	}
	dir, err := ioutil.TempDir(root, prefix)
	if err != nil {
		panic(err)
	}
	return dir
}
<commit_msg>use https for npm download<commit_after>package gode

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
)

// The Node version to install.
// Override this by setting client.Version.
const DefaultNodeVersion = "1.1.0"

// The NPM version to install.
// Override this by setting client.Version.
const DefaultNpmVersion = "2.4.1"

// Client is the interface between Node and Go.
// It also setups up the Node environment if needed.
type Client struct {
	RootPath    string
	NodeVersion string
	NpmVersion  string
	Registry    string
}

// NewClient creates a new Client at the specified rootPath
// The Node installation can then be setup here with client.Setup()
func NewClient(rootPath string) *Client {
	client := &Client{
		RootPath:    rootPath,
		NodeVersion: DefaultNodeVersion,
		NpmVersion:  DefaultNpmVersion,
	}

	return client
}

// NodeBase returns the directory name for the node install
func (c *Client) NodeBase() string {
	switch {
	case runtime.GOARCH == "arm":
		return "iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-armv7l"
	case runtime.GOARCH == "386":
		return "iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-x86"
	default:
		return "iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-x64"
	}
}

func (c *Client) nodeURL() string {
	switch {
	case runtime.GOOS == "windows":
		return "https://iojs.org/dist/v" + c.NodeVersion + "/win-x86/iojs.exe"
	case runtime.GOARCH == "386":
		return "https://iojs.org/dist/v" + c.NodeVersion + "/iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-x86.tar.gz"
	case runtime.GOARCH == "arm":
		return "https://iojs.org/dist/v" + c.NodeVersion + "/iojs-v" + c.NodeVersion + "-" + runtime.GOOS + "-armv7l.tar.gz"
	default:
		return "https://iojs.org/dist/v" + c.NodeVersion + "/" + c.NodeBase() + ".tar.gz"
	}
}

func (c *Client) nodePath() string {
	switch {
	case runtime.GOOS == "windows":
		return filepath.Join(c.RootPath, c.NodeBase(), "bin", "node.exe")
	default:
		return filepath.Join(c.RootPath, c.NodeBase(), "bin", "node")
	}
}

func (c *Client) npmURL() string {
	return "https://github.com/npm/npm/archive/v" + c.NpmVersion + ".zip"
}

func (c *Client) npmPath() string {
	return filepath.Join(c.RootPath, c.NodeBase(), "lib", "node_modules", "npm", "cli.js")
}

func (c *Client) tmpDir(prefix string) string {
	root := filepath.Join(c.RootPath, "tmp")
	err := os.MkdirAll(root, 0755)
	if err != nil {
		panic(err)
	}
	dir, err := ioutil.TempDir(root, prefix)
	if err != nil {
		panic(err)
	}
	return dir
}
<|endoftext|>


<commit_before>package golisp

import "testing"

var testdata = []struct {
	expression []string
	result     []string
}{
	{[]string{"(+ 2 3)"}, []string{"5"}},
	{[]string{"(+ 1 6)"}, []string{"7"}},
	{[]string{"(oddp (+ 1 6))"}, []string{"t"}},
	{[]string{"(* 3 (+ 1 6))"}, []string{"21"}},
	{[]string{"(/ (* 2 11) (+ 1 6))"}, []string{"22/7"}},
	{[]string{"23"}, []string{"23"}},
	{[]string{"t"}, []string{"t"}},
	{[]string{"nil"}, []string{"nil"}},
	{[]string{"(equal (+ 7 5) (* 2 8))"}, []string{"nil"}},
	{[]string{"(/ (+ 6 8) 2.0)"}, []string{"7.0"}},
	{[]string{"(defun average (x y) (/ (+ x y) 2.0))", "(average 6 8)"}, []string{"nil", "7.0"}},
	{[]string{"(defun square (n) (* n n))", "(square 2)"}, []string{"nil", "4"}},
	{[]string{"(defun total-cost (quantity price handling-charge) (+ (* quantity price) handling-charge))", "(total-cost 2 3 4)"}, []string{"nil", "10"}},
	{[]string{"pi"}, []string{"3.14159"}},
	{[]string{"(equal 'kirk 'spock)"}, []string{"nil"}},
	{[]string{"(list 'james t 'kirk)"}, []string{"(james t kirk)"}},
	{[]string{"(defun riddle (x y) (list 'why 'is 'a x 'like 'a y))", "(riddle 'raven 'writing-desk)"}, []string{"nil", "(why is a raven like a writing-desk)"}},
	{[]string{"(first (list 1 2 3))"}, []string{"1"}},
	{[]string{"(first '(we hold these truths))"}, []string{"we"}},
	{[]string{"'(+ 1 2)"}, []string{"(+ 1 2)"}},
	{[]string{"(oddp (+ 1 2))"}, []string{"t"}},
	{[]string{"(list 'a 'b 'c)"}, []string{"(a b c)"}},
	{[]string{"(cons 'a '(b c))"}, []string{"(a b c)"}},
	{[]string{"(+ 10 (- 5 2))"}, []string{"13"}},
	{[]string{"(list 'buy '(* 27 34) 'bagels)"}, []string{"(buy (* 27 34) bagels)"}},
	{[]string{"(list 'buy (* 27 34) 'bagels)"}, []string{"(buy 918 bagels)"}},
	{[]string{"'(foo bar baz)"}, []string{"(foo bar baz)"}},
}

var baddata = []struct {
	expression []string
	fail       []bool
	message    []string
}{
	{[]string{"(1 2 3)"}, []bool{true}, []string{""}},
	{[]string{"(defun average (x y) (/ (+ x y) 2.0))", "(average 6 8 7)"}, []bool{false, true}, []string{"", ""}},
	{[]string{"(equal kirk spock)"}, []bool{true}, []string{""}},
	{[]string{"(list kirk 1 2)"}, []bool{true}, []string{""}},
	{[]string{"(first (we hold these truths))"}, []bool{true}, []string{"Error! 'we' undefined function"}},
	{[]string{"(first 1 2 3 4)"}, []bool{true}, []string{""}},
	{[]string{"(oddp '(+ 1 2))"}, []bool{false}, []string{"Error! Wrong type input to oddp"}},
	{[]string{"(cons 'a (b c))"}, []bool{false}, []string{"Error! 'b' undefined function"}},
	{[]string{"(cons a (b c))"}, []bool{false}, []string{""}},
	{[]string{"(+ 10 '(- 5 2))"}, []bool{false}, []string{"Error! Wrong type input to +"}},
	{[]string{"(- 10 '(- 5 2))"}, []bool{false}, []string{"Error! Wrong type input to -"}},
	{[]string{"('foo 'bar 'baz)"}, []bool{false}, []string{"Error! 'foo' undefined function"}},
}

func TestGolispBad(t *testing.T) {
	for _, test := range baddata {
		i := Init()
		for j := range test.expression {
			e := Parse(test.expression[j])
			p, err := i.Eval(e.(Primitive))
			if test.fail[j] && err == nil {
				t.Errorf("Executing %v has not failed and it should have done: %v -> %v", e.str(), p, p.str())
			}
			if err != nil && test.message[j] != "" {
				if test.message[j] != err.Error() {
					t.Errorf("Error messages don't match %v vs %v", test.message[j], err.Error())
				}
			}
		}
	}
}

func TestGolisp(t *testing.T) {
	for _, test := range testdata {
		i := Init()
		for j := range test.expression {
			e := Parse(test.expression[j])
			r, err := i.Eval(e.(Primitive))
			if err != nil {
				t.Errorf("Executing %v has failed for %v", e.str(), err)
			} else if r.str() != test.result[j] {
				t.Errorf("%v did not lead to %v, it lead to %v", test.expression[j], test.result[j], r.str())
			}
		}
	}
}
<commit_msg>Added test for number 34. This closes #59.<commit_after>package golisp

import "testing"

var testdata = []struct {
	expression []string
	result     []string
}{
	{[]string{"(+ 2 3)"}, []string{"5"}},
	{[]string{"(+ 1 6)"}, []string{"7"}},
	{[]string{"(oddp (+ 1 6))"}, []string{"t"}},
	{[]string{"(* 3 (+ 1 6))"}, []string{"21"}},
	{[]string{"(/ (* 2 11) (+ 1 6))"}, []string{"22/7"}},
	{[]string{"23"}, []string{"23"}},
	{[]string{"t"}, []string{"t"}},
	{[]string{"nil"}, []string{"nil"}},
	{[]string{"(equal (+ 7 5) (* 2 8))"}, []string{"nil"}},
	{[]string{"(/ (+ 6 8) 2.0)"}, []string{"7.0"}},
	{[]string{"(defun average (x y) (/ (+ x y) 2.0))", "(average 6 8)"}, []string{"nil", "7.0"}},
	{[]string{"(defun square (n) (* n n))", "(square 2)"}, []string{"nil", "4"}},
	{[]string{"(defun total-cost (quantity price handling-charge) (+ (* quantity price) handling-charge))", "(total-cost 2 3 4)"}, []string{"nil", "10"}},
	{[]string{"pi"}, []string{"3.14159"}},
	{[]string{"(equal 'kirk 'spock)"}, []string{"nil"}},
	{[]string{"(list 'james t 'kirk)"}, []string{"(james t kirk)"}},
	{[]string{"(defun riddle (x y) (list 'why 'is 'a x 'like 'a y))", "(riddle 'raven 'writing-desk)"}, []string{"nil", "(why is a raven like a writing-desk)"}},
	{[]string{"(first (list 1 2 3))"}, []string{"1"}},
	{[]string{"(first '(we hold these truths))"}, []string{"we"}},
	{[]string{"'(+ 1 2)"}, []string{"(+ 1 2)"}},
	{[]string{"(oddp (+ 1 2))"}, []string{"t"}},
	{[]string{"(list 'a 'b 'c)"}, []string{"(a b c)"}},
	{[]string{"(cons 'a '(b c))"}, []string{"(a b c)"}},
	{[]string{"(+ 10 (- 5 2))"}, []string{"13"}},
	{[]string{"(list 'buy '(* 27 34) 'bagels)"}, []string{"(buy (* 27 34) bagels)"}},
	{[]string{"(list 'buy (* 27 34) 'bagels)"}, []string{"(buy 918 bagels)"}},
	{[]string{"'(foo bar baz)"}, []string{"(foo bar baz)"}},
	{[]string{"(list 'foo 'bar 'baz)"}, []string{"(foo bar baz)"}},
}

var baddata = []struct {
	expression []string
	fail       []bool
	message    []string
}{
	{[]string{"(1 2 3)"}, []bool{true}, []string{""}},
	{[]string{"(defun average (x y) (/ (+ x y) 2.0))", "(average 6 8 7)"}, []bool{false, true}, []string{"", ""}},
	{[]string{"(equal kirk spock)"}, []bool{true}, []string{""}},
	{[]string{"(list kirk 1 2)"}, []bool{true}, []string{""}},
	{[]string{"(first (we hold these truths))"}, []bool{true}, []string{"Error! 'we' undefined function"}},
	{[]string{"(first 1 2 3 4)"}, []bool{true}, []string{""}},
	{[]string{"(oddp '(+ 1 2))"}, []bool{false}, []string{"Error! Wrong type input to oddp"}},
	{[]string{"(cons 'a (b c))"}, []bool{false}, []string{"Error! 'b' undefined function"}},
	{[]string{"(cons a (b c))"}, []bool{false}, []string{""}},
	{[]string{"(+ 10 '(- 5 2))"}, []bool{false}, []string{"Error! Wrong type input to +"}},
	{[]string{"(- 10 '(- 5 2))"}, []bool{false}, []string{"Error! Wrong type input to -"}},
	{[]string{"('foo 'bar 'baz)"}, []bool{false}, []string{"Error! 'foo' undefined function"}},
}

func TestGolispBad(t *testing.T) {
	for _, test := range baddata {
		i := Init()
		for j := range test.expression {
			e := Parse(test.expression[j])
			p, err := i.Eval(e.(Primitive))
			if test.fail[j] && err == nil {
				t.Errorf("Executing %v has not failed and it should have done: %v -> %v", e.str(), p, p.str())
			}
			if err != nil && test.message[j] != "" {
				if test.message[j] != err.Error() {
					t.Errorf("Error messages don't match %v vs %v", test.message[j], err.Error())
				}
			}
		}
	}
}

func TestGolisp(t *testing.T) {
	for _, test := range testdata {
		i := Init()
		for j := range test.expression {
			e := Parse(test.expression[j])
			r, err := i.Eval(e.(Primitive))
			if err != nil {
				t.Errorf("Executing %v has failed for %v", e.str(), err)
			} else if r.str() != test.result[j] {
				t.Errorf("%v did not lead to %v, it lead to %v", test.expression[j], test.result[j], r.str())
			}
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"de.fraxxor.gofrax/gomin/input/gofilereader"
	"de.fraxxor.gofrax/gomin/input/godirectoryreader"
)

func main() {
	fmt.Println("Hello World")
	var reader gofilereader.Gofilereader
	reader = new(gofilereader.GofilereaderFS)
	content, err := reader.ContentOf("D:/Programmierung/Go/rsrc/testfile.txt")
	if err != nil {
		fmt.Printf("Error on Read: %v", err)
	} else {
		fmt.Printf("Successfully read the following:\n%s\n", content)
	}
	dirReader := new(godirectoryreader.GodirectoryreaderFS)
	godir, err := dirReader.ReadDirectory("D:/Programmierung/Go/rsrc")
	if err != nil {
		fmt.Printf("Error on DirRead: %v", err)
	} else {
		fmt.Printf("Directory = \n%s\n", godir)
	}
}<commit_msg>Space removed<commit_after>package main

import (
	"fmt"
	"de.fraxxor.gofrax/gomin/input/gofilereader"
	"de.fraxxor.gofrax/gomin/input/godirectoryreader"
)

func main() {
	fmt.Println("Hello World")
	var reader gofilereader.Gofilereader
	reader = new(gofilereader.GofilereaderFS)
	content, err := reader.ContentOf("D:/Programmierung/Go/rsrc/testfile.txt")
	if err != nil {
		fmt.Printf("Error on Read: %v", err)
	} else {
		fmt.Printf("Successfully read the following:\n%s\n", content)
	}
	dirReader := new(godirectoryreader.GodirectoryreaderFS)
	godir, err := dirReader.ReadDirectory("D:/Programmierung/Go/rsrc")
	if err != nil {
		fmt.Printf("Error on DirRead: %v", err)
	} else {
		fmt.Printf("Directory = \n%s\n", godir)
	}
}
<|endoftext|>


<commit_before>package dragon

import (
	"bufio"
	"go/ast"
	"go/parser"
	"go/token"
	"os"
	"path/filepath"
	"strings"
)

func fetchGoImportsIgnore(src string) (map[string]struct{}, error) {
	dirs := make(map[string]struct{})
	f, err := os.Open(filepath.Join(src, ".goimportsignore"))
	if err != nil {
		return dirs, nil
	}
	scr := bufio.NewScanner(f)
	for scr.Scan() {
		dir := scr.Text()
		if !strings.HasPrefix(dir, "#") {
			dirs[filepath.Join(src, dir)] = struct{}{}
		}
	}
	return dirs, scr.Err()
}

func isSkipDir(fi fileInfo, ignoreDirs map[string]struct{}) bool {
	name := fi.Name()
	switch name {
	case "", "testdata", "vendor":
		return true
	}
	switch name[0] {
	case '.', '_':
		return true
	}
	_, ok := ignoreDirs[filepath.Join(fi.path, fi.Name())]
	return ok
}

func gopathLibs(libChan chan lib) error {
	for _, srcDir := range srcDirs() {
		ignoreDirs, err := fetchGoImportsIgnore(srcDir)
		if err != nil {
			return err
		}
		err = concurrentWalk(srcDir, func(info fileInfo) error {
			if info.isDir(false) {
				if isSkipDir(info, ignoreDirs) {
					return filepath.SkipDir
				}
				return nil
			}
			if strings.HasSuffix(info.Name(), "_test.go") {
				return nil
			}
			if !strings.HasSuffix(info.Name(), ".go") {
				return nil
			}

			path := info.path
			fset := token.NewFileSet()
			f, err := parser.ParseFile(fset, path, nil, 0)
			if err != nil {
				return nil
			}

			pkg := f.Name.Name
			if pkg == "main" {
				return nil
			}

			importPath, err := filepath.Rel(srcDir, filepath.Dir(path))
			if err != nil {
				return nil
			}

			for _, v := range f.Scope.Objects {
				if ast.IsExported(v.Name) {
					libChan <- lib{
						pkg:    pkg,
						object: v.Name,
						path:   importPath,
					}
				}
			}
			return nil
		})
		if err != nil {
			return err
		}
	}
	return nil
}
<commit_msg>trivial fix<commit_after>package dragon

import (
	"bufio"
	"go/ast"
	"go/parser"
	"go/token"
	"os"
	"path/filepath"
	"strings"
)

func fetchGoImportsIgnore(src string) (map[string]bool, error) {
	dirs := make(map[string]bool)
	f, err := os.Open(filepath.Join(src, ".goimportsignore"))
	if err != nil {
		return dirs, nil
	}
	scr := bufio.NewScanner(f)
	for scr.Scan() {
		dir := scr.Text()
		if !strings.HasPrefix(dir, "#") {
			dirs[filepath.Join(src, dir)] = true
		}
	}
	return dirs, scr.Err()
}

func isSkipDir(fi fileInfo, ignoreDirs map[string]bool) bool {
	name := fi.Name()
	switch name {
	case "", "testdata", "vendor":
		return true
	}
	switch name[0] {
	case '.', '_':
		return true
	}
	return ignoreDirs[filepath.Join(fi.path, fi.Name())]
}

func gopathLibs(libChan chan lib) error {
	for _, srcDir := range srcDirs() {
		ignoreDirs, err := fetchGoImportsIgnore(srcDir)
		if err != nil {
			return err
		}
		err = concurrentWalk(srcDir, func(info fileInfo) error {
			if info.isDir(false) {
				if isSkipDir(info, ignoreDirs) {
					return filepath.SkipDir
				}
				return nil
			}
			if strings.HasSuffix(info.Name(), "_test.go") {
				return nil
			}
			if !strings.HasSuffix(info.Name(), ".go") {
				return nil
			}

			path := info.path
			fset := token.NewFileSet()
			f, err := parser.ParseFile(fset, path, nil, 0)
			if err != nil {
				return nil
			}

			pkg := f.Name.Name
			if pkg == "main" {
				return nil
			}

			importPath, err := filepath.Rel(srcDir, filepath.Dir(path))
			if err != nil {
				return nil
			}

			for _, v := range f.Scope.Objects {
				if ast.IsExported(v.Name) {
					libChan <- lib{
						pkg:    pkg,
						object: v.Name,
						path:   importPath,
					}
				}
			}
			return nil
		})
		if err != nil {
			return err
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package log4go

import (
	"database/sql/driver"
	"fmt"
	"reflect"
	"regexp"
	"time"
	"unicode"
)

var sqlRegexp = regexp.MustCompile(`(\$\d+)|\?`)

type GormLogger struct {
}

func (this GormLogger) Print(values ...interface{}) {
	if len(values) > 1 {
		level := values[0]
		source := fmt.Sprintf("%v", values[1])
		writeHttpLoging(source)

		if level == "sql" {
			// duration

			messages := fmt.Sprintf("%s[ %.2fms] ", COLOR_OFF, float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0)
			// sql
			var sql string
			var formattedValues []string

			for _, value := range values[4].([]interface{}) {
				indirectValue := reflect.Indirect(reflect.ValueOf(value))
				if indirectValue.IsValid() {
					value = indirectValue.Interface()
					if t, ok := value.(time.Time); ok {
						formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format(time.RFC3339)))
					} else if b, ok := value.([]byte); ok {
						if str := string(b); isPrintable(str) {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
						} else {
							formattedValues = append(formattedValues, "'<binary>'")
						}
					} else if r, ok := value.(driver.Valuer); ok {
						if value, err := r.Value(); err == nil && value != nil {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
						} else {
							formattedValues = append(formattedValues, "NULL")
						}
					} else {
						formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
					}
				} else {
					formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
				}
			}

			var formattedValuesLength = len(formattedValues)
			for index, value := range sqlRegexp.Split(values[3].(string), -1) {
				sql += value
				if index < formattedValuesLength {
					sql += formattedValues[index]
				}
			}
			messages = messages + sql
			writeHttpLoging(messages)
		}
	}
}

func isPrintable(s string) bool {
	for _, r := range s {
		if !unicode.IsPrint(r) {
			return false
		}
	}
	return true
}
<commit_msg>Format source file gorm<commit_after>package log4go

import (
	"database/sql/driver"
	"fmt"
	"reflect"
	"regexp"
	"strings"
	"time"
	"unicode"
)

var sqlRegexp = regexp.MustCompile(`(\$\d+)|\?`)

type GormLogger struct {
}

func (this GormLogger) Print(values ...interface{}) {
	if len(values) > 1 {
		level := values[0]
		source := fmt.Sprintf("%v", values[1])
		lastIndex := strings.LastIndex(source, "/") + 1
		writeHttpLoging(source[lastIndex:])

		if level == "sql" {
			// duration

			messages := fmt.Sprintf("%s[ %.2fms] ", COLOR_OFF, float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0)
			// sql
			var sql string
			var formattedValues []string

			for _, value := range values[4].([]interface{}) {
				indirectValue := reflect.Indirect(reflect.ValueOf(value))
				if indirectValue.IsValid() {
					value = indirectValue.Interface()
					if t, ok := value.(time.Time); ok {
						formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format(time.RFC3339)))
					} else if b, ok := value.([]byte); ok {
						if str := string(b); isPrintable(str) {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
						} else {
							formattedValues = append(formattedValues, "'<binary>'")
						}
					} else if r, ok := value.(driver.Valuer); ok {
						if value, err := r.Value(); err == nil && value != nil {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
						} else {
							formattedValues = append(formattedValues, "NULL")
						}
					} else {
						formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
					}
				} else {
					formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
				}
			}

			var formattedValuesLength = len(formattedValues)
			for index, value := range sqlRegexp.Split(values[3].(string), -1) {
				sql += value
				if index < formattedValuesLength {
					sql += formattedValues[index]
				}
			}
			messages = messages + sql
			writeHttpLoging(messages)
		}
	}
}

func isPrintable(s string) bool {
	for _, r := range s {
		if !unicode.IsPrint(r) {
			return false
		}
	}
	return true
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/crunchydata/crunchy-postgresql-manager/collect"
	"github.com/crunchydata/crunchy-postgresql-manager/logit"
	"github.com/crunchydata/crunchy-postgresql-manager/swarmapi"
	"github.com/prometheus/client_golang/prometheus"
	"net/http"
	"os"
	"strconv"
	"time"
)

//var gauges = make([]prometheus.Gauge, 3)
var (
	HC_POLL_INT     int64
	SERVER_POLL_INT int64
	CONT_POLL_INT   int64
)

func main() {

	var err error
	var tempVal string

	tempVal = os.Getenv("HC_POLL_INT")
	if tempVal == "" {
		HC_POLL_INT = 3
	}

	tempVal = os.Getenv("SERVER_POLL_INT")
	if tempVal == "" {
		SERVER_POLL_INT = 3
	}
	tempVal = os.Getenv("SERVER_POLL_INT")
	if tempVal == "" {
		CONT_POLL_INT = 3
	}
	HC_POLL_INT, err = strconv.ParseInt(tempVal, 10, 64)
	if err != nil {
		logit.Error.Println(err.Error())
		return
	}
	SERVER_POLL_INT, err = strconv.ParseInt(tempVal, 10, 64)
	if err != nil {
		logit.Error.Println(err.Error())
		return
	}
	CONT_POLL_INT, err = strconv.ParseInt(tempVal, 10, 64)
	if err != nil {
		logit.Error.Println(err.Error())
		return
	}
	logit.Info.Printf("HealthCheck Polling Interval: %d\n", HC_POLL_INT)
	logit.Info.Printf("Server Polling Interval: %d\n", SERVER_POLL_INT)
	logit.Info.Printf("Container Polling Interval: %d\n", CONT_POLL_INT)

	go func() {
		//register a gauge vector
		gauge := prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Name: "cpm_server_cpu",
				Help: "CPU Utilization.",
			}, []string{
				"server",
			})
		prometheus.MustRegister(gauge)
		gaugeMem := prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Name: "cpm_server_mem",
				Help: "Memory Utilization.",
			}, []string{
				"server",
			})
		prometheus.MustRegister(gaugeMem)

		var serverinfo swarmapi.DockerInfoResponse
		serverinfo, err = swarmapi.DockerInfo()
		if err != nil {
			logit.Error.Println(err.Error())
		}
		logit.Info.Printf("got %d servers\n", len(serverinfo.Output))

		var metric collect.Metric

		for {
			//get metrics for each server
			for x := 0; x < len(serverinfo.Output); {
				//v := rand.Float64() * 100.00
				metric, err = collect.Collectcpu(serverinfo.Output[x])
				gauge.WithLabelValues(serverinfo.Output[x]).Set(metric.Value)
				logit.Info.Println("setting cpu metric for " + serverinfo.Output[x] + " to " + strconv.FormatFloat(metric.Value, 'f', -1, 64))
				metric, err = collect.Collectmem(serverinfo.Output[x])
				gaugeMem.WithLabelValues(serverinfo.Output[x]).Set(metric.Value)
				logit.Info.Println("setting mem metric for " + serverinfo.Output[x] + " to " + strconv.FormatFloat(metric.Value, 'f', -1, 64))
				x++
			}

			logit.Info.Println("sleeping in the server metrics ....")

			time.Sleep(time.Duration(SERVER_POLL_INT) * time.Minute)
		}
	}()

	go func() {
		for true {
			collect.Collecthc()
			time.Sleep(time.Duration(HC_POLL_INT) * time.Minute)
		}
	}()

	go func() {
		//register a gauge vector
		dbsizegauge := prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Name: "cpm_container_dbsize",
				Help: "Database Size.",
			}, []string{
				"containername",
				"databasename",
			})
		prometheus.MustRegister(dbsizegauge)

		for true {
			//dbsizegauge.WithLabelValues("node1", "db1").Set(v)
			logit.Info.Println("collecting dbsize")
			collect.CollectDBSize(dbsizegauge)
			time.Sleep(time.Duration(CONT_POLL_INT) * time.Minute)
		}
	}()

	http.Handle("/metrics", prometheus.Handler())
	http.ListenAndServe(":8080", nil)
}
<commit_msg>fix bug in cpu and mem collection<commit_after>package main

import (
	"github.com/crunchydata/crunchy-postgresql-manager/collect"
	"github.com/crunchydata/crunchy-postgresql-manager/logit"
	"github.com/crunchydata/crunchy-postgresql-manager/swarmapi"
	"github.com/prometheus/client_golang/prometheus"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

//var gauges = make([]prometheus.Gauge, 3)
var (
	HC_POLL_INT     int64
	SERVER_POLL_INT int64
	CONT_POLL_INT   int64
)

func main() {

	var err error
	var tempVal string

	tempVal = os.Getenv("HC_POLL_INT")
	if tempVal == "" {
		HC_POLL_INT = 3
	}

	tempVal = os.Getenv("SERVER_POLL_INT")
	if tempVal == "" {
		SERVER_POLL_INT = 3
	}
	tempVal = os.Getenv("SERVER_POLL_INT")
	if tempVal == "" {
		CONT_POLL_INT = 3
	}
	HC_POLL_INT, err = strconv.ParseInt(tempVal, 10, 64)
	if err != nil {
		logit.Error.Println(err.Error())
		return
	}
	SERVER_POLL_INT, err = strconv.ParseInt(tempVal, 10, 64)
	if err != nil {
		logit.Error.Println(err.Error())
		return
	}
	CONT_POLL_INT, err = strconv.ParseInt(tempVal, 10, 64)
	if err != nil {
		logit.Error.Println(err.Error())
		return
	}
	logit.Info.Printf("HealthCheck Polling Interval: %d\n", HC_POLL_INT)
	logit.Info.Printf("Server Polling Interval: %d\n", SERVER_POLL_INT)
	logit.Info.Printf("Container Polling Interval: %d\n", CONT_POLL_INT)

	go func() {
		//register a gauge vector
		gauge := prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Name: "cpm_server_cpu",
				Help: "CPU Utilization.",
			}, []string{
				"server",
			})
		prometheus.MustRegister(gauge)
		gaugeMem := prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Name: "cpm_server_mem",
				Help: "Memory Utilization.",
			}, []string{
				"server",
			})
		prometheus.MustRegister(gaugeMem)

		var serverinfo swarmapi.DockerInfoResponse
		serverinfo, err = swarmapi.DockerInfo()
		if err != nil {
			logit.Error.Println(err.Error())
		}
		logit.Info.Printf("got %d servers\n", len(serverinfo.Output))

		var metric collect.Metric

		for {
			//get metrics for each server
			for x := 0; x < len(serverinfo.Output); {
				//v := rand.Float64() * 100.00
				parts := strings.Split(serverinfo.Output[x], ":")
				ipaddress := parts[0]
				metric, err = collect.Collectcpu(ipaddress)
				gauge.WithLabelValues(ipaddress).Set(metric.Value)
				logit.Info.Println("setting cpu metric for " + ipaddress + " to " + strconv.FormatFloat(metric.Value, 'f', -1, 64))
				metric, err = collect.Collectmem(ipaddress)
				gaugeMem.WithLabelValues(ipaddress).Set(metric.Value)
				logit.Info.Println("setting mem metric for " + ipaddress + " to " + strconv.FormatFloat(metric.Value, 'f', -1, 64))
				x++
			}

			logit.Info.Println("sleeping in the server metrics ....")

			time.Sleep(time.Duration(SERVER_POLL_INT) * time.Minute)
		}
	}()

	go func() {
		for true {
			collect.Collecthc()
			time.Sleep(time.Duration(HC_POLL_INT) * time.Minute)
		}
	}()

	go func() {
		//register a gauge vector
		dbsizegauge := prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Name: "cpm_container_dbsize",
				Help: "Database Size.",
			}, []string{
				"containername",
				"databasename",
			})
		prometheus.MustRegister(dbsizegauge)

		for true {
			//dbsizegauge.WithLabelValues("node1", "db1").Set(v)
			logit.Info.Println("collecting dbsize")
			collect.CollectDBSize(dbsizegauge)
			time.Sleep(time.Duration(CONT_POLL_INT) * time.Minute)
		}
	}()

	http.Handle("/metrics", prometheus.Handler())
	http.ListenAndServe(":8080", nil)
}
<|endoftext|>


<commit_before>package db

import (
	"fmt"
)

var (
	// ErrAlreadyDefined hapens when the given entry already exists,
	// for example a container.
	ErrAlreadyDefined = fmt.Errorf("The record already exists")

	// ErrNoSuchObject is in the case of joins (and probably other) queries,
	// we don't get back sql.ErrNoRows when no rows are returned, even though we do
	// on selects without joins. Instead, you can use this error to
	// propagate up and generate proper 404s to the client when something
	// isn't found so we don't abuse sql.ErrNoRows any more than we
	// already do.
	ErrNoSuchObject = fmt.Errorf("No such object")
)
<commit_msg>lxd/db/errors: Adds ErrNoClusterMember var used to indicate no cluster member has been found for a resource<commit_after>package db

import (
	"fmt"
)

var (
	// ErrAlreadyDefined hapens when the given entry already exists,
	// for example a container.
	ErrAlreadyDefined = fmt.Errorf("The record already exists")

	// ErrNoSuchObject is in the case of joins (and probably other) queries,
	// we don't get back sql.ErrNoRows when no rows are returned, even though we do
	// on selects without joins. Instead, you can use this error to
	// propagate up and generate proper 404s to the client when something
	// isn't found so we don't abuse sql.ErrNoRows any more than we
	// already do.
	ErrNoSuchObject = fmt.Errorf("No such object")

	// ErrNoClusterMember is used to indicate no cluster member has been found for a resource.
	ErrNoClusterMember = fmt.Errorf("No cluster member found")
)
<|endoftext|>


<commit_before>package graph

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"time"
)

type Graph struct {
	Root string
}

func New(root string) (*Graph, error) {
	abspath, err := filepath.Abs(root)
	if err != nil {
		return nil, err
	}
	// Create the root directory if it doesn't exists
	if err := os.Mkdir(root, 0700); err != nil && !os.IsExist(err) {
		return nil, err
	}
	return &Graph{
		Root: abspath,
	}, nil
}

func (graph *Graph) Exists(id string) bool {
	if _, err := graph.Get(id); err != nil {
		return false
	}
	return true
}

func (graph *Graph) Get(id string) (*Image, error) {
	img, err := LoadImage(graph.imageRoot(id))
	if err != nil {
		return nil, err
	}
	if img.Id != id {
		return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.Id)
	}
	return img, nil
}

func (graph *Graph) Create(layerData Archive, parent, comment string) (*Image, error) {
	img := &Image{
		Id:      GenerateId(),
		Parent:  parent,
		Comment: comment,
		Created: time.Now(),
	}
	if err := graph.Register(layerData, img); err != nil {
		return nil, err
	}
	return img, nil
}

func (graph *Graph) Register(layerData Archive, img *Image) error {
	if err := ValidateId(img.Id); err != nil {
		return err
	}
	// (This is a convenience to save time. Race conditions are taken care of by os.Rename)
	if graph.Exists(img.Id) {
		return fmt.Errorf("Image %s already exists", img.Id)
	}
	tmp, err := graph.Mktemp(img.Id)
	defer os.RemoveAll(tmp)
	if err != nil {
		return fmt.Errorf("Mktemp failed: %s", err)
	}
	if err := StoreImage(img, layerData, tmp); err != nil {
		return err
	}
	// Commit
	if err := os.Rename(tmp, graph.imageRoot(img.Id)); err != nil {
		return err
	}
	img.graph = graph
	return nil
}

func (graph *Graph) Mktemp(id string) (string, error) {
	tmp, err := New(path.Join(graph.Root, ":tmp:"))
	if err != nil {
		return "", fmt.Errorf("Couldn't create temp: %s", err)
	}
	if tmp.Exists(id) {
		return "", fmt.Errorf("Image %d already exists", id)
	}
	return tmp.imageRoot(id), nil
}

func (graph *Graph) Garbage() (*Graph, error) {
	return New(path.Join(graph.Root, ":garbage:"))
}

func (graph *Graph) Delete(id string) error {
	garbage, err := graph.Garbage()
	if err != nil {
		return err
	}
	return os.Rename(graph.imageRoot(id), garbage.imageRoot(id))
}

func (graph *Graph) Undelete(id string) error {
	garbage, err := graph.Garbage()
	if err != nil {
		return err
	}
	return os.Rename(garbage.imageRoot(id), graph.imageRoot(id))
}

func (graph *Graph) GarbageCollect() error {
	garbage, err := graph.Garbage()
	if err != nil {
		return err
	}
	return os.RemoveAll(garbage.Root)
}

func (graph *Graph) All() ([]*Image, error) {
	files, err := ioutil.ReadDir(graph.Root)
	if err != nil {
		return nil, err
	}
	var images []*Image
	for _, st := range files {
		if img, err := graph.Get(st.Name()); err != nil {
			// Skip image
			continue
		} else {
			images = append(images, img)
		}
	}
	return images, nil
}

func (graph *Graph) imageRoot(id string) string {
	return path.Join(graph.Root, id)
}
<commit_msg>Fixed a bug in graph.Graph.Get()<commit_after>package graph

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"time"
)

type Graph struct {
	Root string
}

func New(root string) (*Graph, error) {
	abspath, err := filepath.Abs(root)
	if err != nil {
		return nil, err
	}
	// Create the root directory if it doesn't exists
	if err := os.Mkdir(root, 0700); err != nil && !os.IsExist(err) {
		return nil, err
	}
	return &Graph{
		Root: abspath,
	}, nil
}

func (graph *Graph) Exists(id string) bool {
	if _, err := graph.Get(id); err != nil {
		return false
	}
	return true
}

func (graph *Graph) Get(id string) (*Image, error) {
	img, err := LoadImage(graph.imageRoot(id))
	if err != nil {
		return nil, err
	}
	if img.Id != id {
		return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.Id)
	}
	img.graph = graph
	return img, nil
}

func (graph *Graph) Create(layerData Archive, parent, comment string) (*Image, error) {
	img := &Image{
		Id:      GenerateId(),
		Parent:  parent,
		Comment: comment,
		Created: time.Now(),
	}
	if err := graph.Register(layerData, img); err != nil {
		return nil, err
	}
	return img, nil
}

func (graph *Graph) Register(layerData Archive, img *Image) error {
	if err := ValidateId(img.Id); err != nil {
		return err
	}
	// (This is a convenience to save time. Race conditions are taken care of by os.Rename)
	if graph.Exists(img.Id) {
		return fmt.Errorf("Image %s already exists", img.Id)
	}
	tmp, err := graph.Mktemp(img.Id)
	defer os.RemoveAll(tmp)
	if err != nil {
		return fmt.Errorf("Mktemp failed: %s", err)
	}
	if err := StoreImage(img, layerData, tmp); err != nil {
		return err
	}
	// Commit
	if err := os.Rename(tmp, graph.imageRoot(img.Id)); err != nil {
		return err
	}
	img.graph = graph
	return nil
}

func (graph *Graph) Mktemp(id string) (string, error) {
	tmp, err := New(path.Join(graph.Root, ":tmp:"))
	if err != nil {
		return "", fmt.Errorf("Couldn't create temp: %s", err)
	}
	if tmp.Exists(id) {
		return "", fmt.Errorf("Image %d already exists", id)
	}
	return tmp.imageRoot(id), nil
}

func (graph *Graph) Garbage() (*Graph, error) {
	return New(path.Join(graph.Root, ":garbage:"))
}

func (graph *Graph) Delete(id string) error {
	garbage, err := graph.Garbage()
	if err != nil {
		return err
	}
	return os.Rename(graph.imageRoot(id), garbage.imageRoot(id))
}

func (graph *Graph) Undelete(id string) error {
	garbage, err := graph.Garbage()
	if err != nil {
		return err
	}
	return os.Rename(garbage.imageRoot(id), graph.imageRoot(id))
}

func (graph *Graph) GarbageCollect() error {
	garbage, err := graph.Garbage()
	if err != nil {
		return err
	}
	return os.RemoveAll(garbage.Root)
}

func (graph *Graph) All() ([]*Image, error) {
	files, err := ioutil.ReadDir(graph.Root)
	if err != nil {
		return nil, err
	}
	var images []*Image
	for _, st := range files {
		if img, err := graph.Get(st.Name()); err != nil {
			// Skip image
			continue
		} else {
			images = append(images, img)
		}
	}
	return images, nil
}

func (graph *Graph) imageRoot(id string) string {
	return path.Join(graph.Root, id)
}
<|endoftext|>