<commit_before>package reporting

import (
	"runtime"
	"strings"
)

type Report struct {
	File       string
	Line       int
	Failure    string
	Error      interface{}
	stackTrace string
}

func NewFailureReport(failure string) *Report {
	file, line := caller()
	stack := stackTrace()
	report := Report{file, line, failure, nil, stack}
	return &report
}
func NewErrorReport(err interface{}) *Report {
	file, line := caller()
	stack := fullStackTrace()
	report := Report{file, line, "", err, stack}
	return &report
}
func NewSuccessReport() *Report {
	file, line := caller()
	stack := stackTrace()
	report := Report{file, line, "", nil, stack}
	return &report
}

func caller() (file string, line int) {
	_, file, line, _ = runtime.Caller(3)
	return
}
func stackTrace() string {
	buffer := make([]byte, 1024*64)
	runtime.Stack(buffer, false)
	formatted := strings.Trim(string(buffer), string([]byte{0}))
	return removeInternalEntries(formatted)
}
func fullStackTrace() string {
	buffer := make([]byte, 1024*64)
	runtime.Stack(buffer, true)
	formatted := strings.Trim(string(buffer), string([]byte{0}))
	return removeInternalEntries(formatted)
}
func removeInternalEntries(stack string) string {
	lines := strings.Split(stack, newline)
	filtered := []string{}
	for _, line := range lines {
		if isExternal(line) {
			filtered = append(filtered, line)
		}
	}
	return strings.Join(filtered, newline)
}
func isExternal(line string) bool {
	if strings.Contains(line, "goconvey/convey") {
		return false
	} else if strings.Contains(line, "goconvey/execution") {
		return false
	} else if strings.Contains(line, "goconvey/gotest") {
		return false
	} else if strings.Contains(line, "goconvey/printing") {
		return false
	} else if strings.Contains(line, "goconvey/reporting") {
		return false
	}
	return true
}

const newline = "\n"

const (
	greenColor = "\033[32m"
	redColor   = "\033[31m"
	resetColor = "\033[0m"
)

const (
	success         = "✓"
	failure         = "✗"
	error_          = "🔥"
	dotSuccess      = "."
	dotFailure      = "x"
	dotError        = "E"
	errorTemplate   = "* %s \n* Line %d: - %v \n%s"
	failureTemplate = "* %s \n* Line %d: %s"
)
<commit_msg>Better spacing between errors and failures.<commit_after>package reporting

import (
	"runtime"
	"strings"
)

type Report struct {
	File       string
	Line       int
	Failure    string
	Error      interface{}
	stackTrace string
}

func NewFailureReport(failure string) *Report {
	file, line := caller()
	stack := stackTrace()
	report := Report{file, line, failure, nil, stack}
	return &report
}
func NewErrorReport(err interface{}) *Report {
	file, line := caller()
	stack := fullStackTrace()
	report := Report{file, line, "", err, stack}
	return &report
}
func NewSuccessReport() *Report {
	file, line := caller()
	stack := stackTrace()
	report := Report{file, line, "", nil, stack}
	return &report
}

func caller() (file string, line int) {
	_, file, line, _ = runtime.Caller(3)
	return
}
func stackTrace() string {
	buffer := make([]byte, 1024*64)
	runtime.Stack(buffer, false)
	formatted := strings.Trim(string(buffer), string([]byte{0}))
	return removeInternalEntries(formatted)
}
func fullStackTrace() string {
	buffer := make([]byte, 1024*64)
	runtime.Stack(buffer, true)
	formatted := strings.Trim(string(buffer), string([]byte{0}))
	return removeInternalEntries(formatted)
}
func removeInternalEntries(stack string) string {
	lines := strings.Split(stack, newline)
	filtered := []string{}
	for _, line := range lines {
		if isExternal(line) {
			filtered = append(filtered, line)
		}
	}
	return strings.Join(filtered, newline)
}
func isExternal(line string) bool {
	if strings.Contains(line, "goconvey/convey") {
		return false
	} else if strings.Contains(line, "goconvey/execution") {
		return false
	} else if strings.Contains(line, "goconvey/gotest") {
		return false
	} else if strings.Contains(line, "goconvey/printing") {
		return false
	} else if strings.Contains(line, "goconvey/reporting") {
		return false
	}
	return true
}

const newline = "\n"

const (
	greenColor = "\033[32m"
	redColor   = "\033[31m"
	resetColor = "\033[0m"
)

const (
	success         = "✓"
	failure         = "✗"
	error_          = "🔥"
	dotSuccess      = "."
	dotFailure      = "x"
	dotError        = "E"
	errorTemplate   = "* %s \n  Line %d: - %v \n%s\n"
	failureTemplate = "* %s \n  Line %d: %s\n"
)
<|endoftext|>


<commit_before>//
// Copyright 2017, Sander van Harmelen
//
// 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 gitlab

import (
	"bytes"
	"fmt"
	"net/url"
)

// RepositoryFilesService handles communication with the repository files
// related methods of the GitLab API.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html
type RepositoryFilesService struct {
	client *Client
}

// File represents a GitLab repository file.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html
type File struct {
	FileName string `json:"file_name"`
	FilePath string `json:"file_path"`
	Size     int    `json:"size"`
	Encoding string `json:"encoding"`
	Content  string `json:"content"`
	Ref      string `json:"ref"`
	BlobID   string `json:"blob_id"`
	CommitID string `json:"commit_id"`
}

func (r File) String() string {
	return Stringify(r)
}

// GetFileOptions represents the available GetFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-file-from-repository
type GetFileOptions struct {
	Ref *string `url:"ref,omitempty" json:"ref,omitempty"`
}

// GetFile allows you to receive information about a file in repository like
// name, size, content. Note that file content is Base64 encoded.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-file-from-repository
func (s *RepositoryFilesService) GetFile(pid interface{}, fileName string, opt *GetFileOptions, options ...OptionFunc) (*File, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.QueryEscape(fileName))

	req, err := s.client.NewRequest("GET", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	f := new(File)
	resp, err := s.client.Do(req, f)
	if err != nil {
		return nil, resp, err
	}

	return f, resp, err
}

// GetRawFileOptions represents the available GetRawFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-raw-file-from-repository
type GetRawFileOptions struct {
	Ref *string `url:"ref,omitempty" json:"ref,omitempty"`
}

// GetRawFile allows you to receive the raw file in repository.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-raw-file-from-repository
func (s *RepositoryFilesService) GetRawFile(pid interface{}, fileName string, opt *GetRawFileOptions, options ...OptionFunc) ([]byte, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s/raw", url.QueryEscape(project), url.QueryEscape(fileName))

	req, err := s.client.NewRequest("GET", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	var f bytes.Buffer
	resp, err := s.client.Do(req, &f)
	if err != nil {
		return nil, resp, err
	}

	return f.Bytes(), resp, err
}

// FileInfo represents file details of a GitLab repository file.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html
type FileInfo struct {
	FilePath string `json:"file_path"`
	Branch   string `json:"branch"`
}

func (r FileInfo) String() string {
	return Stringify(r)
}

// CreateFileOptions represents the available CreateFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#create-new-file-in-repository
type CreateFileOptions struct {
	Branch        *string `url:"branch,omitempty" json:"branch,omitempty"`
	Encoding      *string `url:"encoding,omitempty" json:"encoding,omitempty"`
	AuthorEmail   *string `url:"author_email,omitempty" json:"author_email,omitempty"`
	AuthorName    *string `url:"author_name,omitempty" json:"author_name,omitempty"`
	Content       *string `url:"content,omitempty" json:"content,omitempty"`
	CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"`
}

// CreateFile creates a new file in a repository.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#create-new-file-in-repository
func (s *RepositoryFilesService) CreateFile(pid interface{}, fileName string, opt *CreateFileOptions, options ...OptionFunc) (*FileInfo, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.QueryEscape(fileName))

	req, err := s.client.NewRequest("POST", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	f := new(FileInfo)
	resp, err := s.client.Do(req, f)
	if err != nil {
		return nil, resp, err
	}

	return f, resp, err
}

// UpdateFileOptions represents the available UpdateFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#update-existing-file-in-repository
type UpdateFileOptions struct {
	Branch        *string `url:"branch,omitempty" json:"branch,omitempty"`
	Encoding      *string `url:"encoding,omitempty" json:"encoding,omitempty"`
	AuthorEmail   *string `url:"author_email,omitempty" json:"author_email,omitempty"`
	AuthorName    *string `url:"author_name,omitempty" json:"author_name,omitempty"`
	Content       *string `url:"content,omitempty" json:"content,omitempty"`
	CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"`
	LastCommitID  *string `url:"last_commit_id,omitempty" json:"last_commit_id,omitempty"`
}

// UpdateFile updates an existing file in a repository
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#update-existing-file-in-repository
func (s *RepositoryFilesService) UpdateFile(pid interface{}, fileName string, opt *UpdateFileOptions, options ...OptionFunc) (*FileInfo, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.QueryEscape(fileName))

	req, err := s.client.NewRequest("PUT", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	f := new(FileInfo)
	resp, err := s.client.Do(req, f)
	if err != nil {
		return nil, resp, err
	}

	return f, resp, err
}

// DeleteFileOptions represents the available DeleteFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#delete-existing-file-in-repository
type DeleteFileOptions struct {
	Branch        *string `url:"branch,omitempty" json:"branch,omitempty"`
	AuthorEmail   *string `url:"author_email,omitempty" json:"author_email,omitempty"`
	AuthorName    *string `url:"author_name,omitempty" json:"author_name,omitempty"`
	CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"`
}

// DeleteFile deletes an existing file in a repository
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#delete-existing-file-in-repository
func (s *RepositoryFilesService) DeleteFile(pid interface{}, fileName string, opt *DeleteFileOptions, options ...OptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.QueryEscape(fileName))

	req, err := s.client.NewRequest("DELETE", u, opt, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}
<commit_msg>Query encoding should use url.PathEscape (#482)<commit_after>//
// Copyright 2017, Sander van Harmelen
//
// 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 gitlab

import (
	"bytes"
	"fmt"
	"net/url"
)

// RepositoryFilesService handles communication with the repository files
// related methods of the GitLab API.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html
type RepositoryFilesService struct {
	client *Client
}

// File represents a GitLab repository file.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html
type File struct {
	FileName string `json:"file_name"`
	FilePath string `json:"file_path"`
	Size     int    `json:"size"`
	Encoding string `json:"encoding"`
	Content  string `json:"content"`
	Ref      string `json:"ref"`
	BlobID   string `json:"blob_id"`
	CommitID string `json:"commit_id"`
}

func (r File) String() string {
	return Stringify(r)
}

// GetFileOptions represents the available GetFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-file-from-repository
type GetFileOptions struct {
	Ref *string `url:"ref,omitempty" json:"ref,omitempty"`
}

// GetFile allows you to receive information about a file in repository like
// name, size, content. Note that file content is Base64 encoded.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-file-from-repository
func (s *RepositoryFilesService) GetFile(pid interface{}, fileName string, opt *GetFileOptions, options ...OptionFunc) (*File, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.PathEscape(fileName))

	req, err := s.client.NewRequest("GET", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	f := new(File)
	resp, err := s.client.Do(req, f)
	if err != nil {
		return nil, resp, err
	}

	return f, resp, err
}

// GetRawFileOptions represents the available GetRawFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-raw-file-from-repository
type GetRawFileOptions struct {
	Ref *string `url:"ref,omitempty" json:"ref,omitempty"`
}

// GetRawFile allows you to receive the raw file in repository.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#get-raw-file-from-repository
func (s *RepositoryFilesService) GetRawFile(pid interface{}, fileName string, opt *GetRawFileOptions, options ...OptionFunc) ([]byte, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s/raw", url.QueryEscape(project), url.PathEscape(fileName))

	req, err := s.client.NewRequest("GET", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	var f bytes.Buffer
	resp, err := s.client.Do(req, &f)
	if err != nil {
		return nil, resp, err
	}

	return f.Bytes(), resp, err
}

// FileInfo represents file details of a GitLab repository file.
//
// GitLab API docs: https://docs.gitlab.com/ce/api/repository_files.html
type FileInfo struct {
	FilePath string `json:"file_path"`
	Branch   string `json:"branch"`
}

func (r FileInfo) String() string {
	return Stringify(r)
}

// CreateFileOptions represents the available CreateFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#create-new-file-in-repository
type CreateFileOptions struct {
	Branch        *string `url:"branch,omitempty" json:"branch,omitempty"`
	Encoding      *string `url:"encoding,omitempty" json:"encoding,omitempty"`
	AuthorEmail   *string `url:"author_email,omitempty" json:"author_email,omitempty"`
	AuthorName    *string `url:"author_name,omitempty" json:"author_name,omitempty"`
	Content       *string `url:"content,omitempty" json:"content,omitempty"`
	CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"`
}

// CreateFile creates a new file in a repository.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#create-new-file-in-repository
func (s *RepositoryFilesService) CreateFile(pid interface{}, fileName string, opt *CreateFileOptions, options ...OptionFunc) (*FileInfo, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.PathEscape(fileName))

	req, err := s.client.NewRequest("POST", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	f := new(FileInfo)
	resp, err := s.client.Do(req, f)
	if err != nil {
		return nil, resp, err
	}

	return f, resp, err
}

// UpdateFileOptions represents the available UpdateFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#update-existing-file-in-repository
type UpdateFileOptions struct {
	Branch        *string `url:"branch,omitempty" json:"branch,omitempty"`
	Encoding      *string `url:"encoding,omitempty" json:"encoding,omitempty"`
	AuthorEmail   *string `url:"author_email,omitempty" json:"author_email,omitempty"`
	AuthorName    *string `url:"author_name,omitempty" json:"author_name,omitempty"`
	Content       *string `url:"content,omitempty" json:"content,omitempty"`
	CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"`
	LastCommitID  *string `url:"last_commit_id,omitempty" json:"last_commit_id,omitempty"`
}

// UpdateFile updates an existing file in a repository
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#update-existing-file-in-repository
func (s *RepositoryFilesService) UpdateFile(pid interface{}, fileName string, opt *UpdateFileOptions, options ...OptionFunc) (*FileInfo, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.PathEscape(fileName))

	req, err := s.client.NewRequest("PUT", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	f := new(FileInfo)
	resp, err := s.client.Do(req, f)
	if err != nil {
		return nil, resp, err
	}

	return f, resp, err
}

// DeleteFileOptions represents the available DeleteFile() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#delete-existing-file-in-repository
type DeleteFileOptions struct {
	Branch        *string `url:"branch,omitempty" json:"branch,omitempty"`
	AuthorEmail   *string `url:"author_email,omitempty" json:"author_email,omitempty"`
	AuthorName    *string `url:"author_name,omitempty" json:"author_name,omitempty"`
	CommitMessage *string `url:"commit_message,omitempty" json:"commit_message,omitempty"`
}

// DeleteFile deletes an existing file in a repository
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/repository_files.html#delete-existing-file-in-repository
func (s *RepositoryFilesService) DeleteFile(pid interface{}, fileName string, opt *DeleteFileOptions, options ...OptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/repository/files/%s", url.QueryEscape(project), url.PathEscape(fileName))

	req, err := s.client.NewRequest("DELETE", u, opt, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}
<|endoftext|>


<commit_before>// Package log
package log

import (
	"io/ioutil"

	"github.com/Sirupsen/logrus"
)

// Singleton logrus logger object with custom format.
// Verbosity can be changed through SetLogLevel.
var Log *logrus.Entry
var Logger *logrus.Logger

var TimestampFormat = "2006/01/02 15:04:05.000000 -0700"

const (
	PanicLevel uint8 = iota
	FatalLevel
	ErrorLevel
	WarnLevel
	InfoLevel
	DebugLevel
)

func init() {
	Logger = logrus.New()
	customFormatter := new(logrus.TextFormatter)
	customFormatter.FullTimestamp = true
	customFormatter.TimestampFormat = TimestampFormat
	Logger.Formatter = customFormatter
	Logger.Level = logrus.DebugLevel
	Log = Logger.WithFields(logrus.Fields{
		"node": "not initialized",
	})
}

// Sets log level to one of (debug, info, warn, error, fatal, panic)
func SetLogLevel(l uint8) {
	switch l {
	case DebugLevel:
		Logger.Level = logrus.DebugLevel
	case InfoLevel:
		Logger.Level = logrus.InfoLevel
	case WarnLevel:
		Logger.Level = logrus.WarnLevel
	case ErrorLevel:
		Logger.Level = logrus.ErrorLevel
	case FatalLevel:
		Logger.Level = logrus.FatalLevel
	case PanicLevel:
		Logger.Level = logrus.PanicLevel

	default:
		Logger.Level = logrus.DebugLevel
	}
}

func GetLogLevel() uint8 {
	switch Logger.Level {
	case logrus.DebugLevel:
		return DebugLevel
	case logrus.InfoLevel:
		return InfoLevel
	case logrus.WarnLevel:
		return WarnLevel
	case logrus.ErrorLevel:
		return ErrorLevel
	case logrus.FatalLevel:
		return FatalLevel
	case logrus.PanicLevel:
		return PanicLevel

	default:
		return DebugLevel
	}
}

func LogLevelIs(l uint8) bool {
	return GetLogLevel() == l
}

func LogWithNode(node string) *logrus.Entry {
	return Logger.WithFields(logrus.Fields{
		"node": node,
	})
}

func LogDiscard() *logrus.Entry {
	Logger := logrus.New()
	Logger.Out = ioutil.Discard
	return Logger.WithFields(logrus.Fields{
		"node": "not initialized",
	})
}
<commit_msg>Sort logged fields<commit_after>// Package log
package log

import (
	"io/ioutil"

	"github.com/Sirupsen/logrus"
)

// Singleton logrus logger object with custom format.
// Verbosity can be changed through SetLogLevel.
var Log *logrus.Entry
var Logger *logrus.Logger

var TimestampFormat = "2006/01/02 15:04:05.000000 -0700"

const (
	PanicLevel uint8 = iota
	FatalLevel
	ErrorLevel
	WarnLevel
	InfoLevel
	DebugLevel
)

func init() {
	Logger = logrus.New()
	customFormatter := &logrus.TextFormatter{DisableSorting: false}
	customFormatter.FullTimestamp = true
	customFormatter.TimestampFormat = TimestampFormat
	Logger.Formatter = customFormatter
	Logger.Level = logrus.DebugLevel
	Log = Logger.WithFields(logrus.Fields{
		"node": "not initialized",
	})
}

// Sets log level to one of (debug, info, warn, error, fatal, panic)
func SetLogLevel(l uint8) {
	switch l {
	case DebugLevel:
		Logger.Level = logrus.DebugLevel
	case InfoLevel:
		Logger.Level = logrus.InfoLevel
	case WarnLevel:
		Logger.Level = logrus.WarnLevel
	case ErrorLevel:
		Logger.Level = logrus.ErrorLevel
	case FatalLevel:
		Logger.Level = logrus.FatalLevel
	case PanicLevel:
		Logger.Level = logrus.PanicLevel

	default:
		Logger.Level = logrus.DebugLevel
	}
}

func GetLogLevel() uint8 {
	switch Logger.Level {
	case logrus.DebugLevel:
		return DebugLevel
	case logrus.InfoLevel:
		return InfoLevel
	case logrus.WarnLevel:
		return WarnLevel
	case logrus.ErrorLevel:
		return ErrorLevel
	case logrus.FatalLevel:
		return FatalLevel
	case logrus.PanicLevel:
		return PanicLevel

	default:
		return DebugLevel
	}
}

func LogLevelIs(l uint8) bool {
	return GetLogLevel() == l
}

func LogWithNode(node string) *logrus.Entry {
	return Logger.WithFields(logrus.Fields{
		"node": node,
		"type": "system",
	})
}

func LogDiscard() *logrus.Entry {
	Logger := logrus.New()
	Logger.Out = ioutil.Discard
	return Logger.WithFields(logrus.Fields{
		"node": "not initialized",
	})
}
<|endoftext|>


<commit_before>package log

import (
    "io"
    "os"
    "log"
    "fmt"
    "errors"
    "sync"
    "runtime"
)

const (
    DisableError = 1
    DisableWarning = 2
    DisableMessage = 4
    DisableDebug = 8
    LogAll = 0xF
    LogNone = 0
    LogError = LogAll ^ DisableWarning ^ DisableMessage ^ DisableDebug
    LogWarning = LogAll ^ DisableMessage ^ DisableDebug ^ DisableError
    LogMessage = LogAll ^ DisableDebug ^ DisableError ^ DisableWarning
    LogDebug = LogAll ^ DisableError ^ DisableWarning ^ DisableMessage
)

const (
    TypeDebug = iota
    TypeMessage
    TypeWarning
    TypeError
)

type Logger struct {
    *log.Logger
    flag int
    logChan chan *logRecord
    mutex sync.Mutex
}

type logRecord struct {
    Type uint8
    Message []interface{}
}

func New(w io.Writer, flag, bufsize int) (l *Logger, err error) {
    l = &Logger{Logger:log.New(w, "", log.LstdFlags), flag:flag}
    l.logChan = make(chan *logRecord, bufsize)
    go func() {
        l.mutex.Lock()
        defer l.mutex.Unlock()
        var t string
        for record := range l.logChan {
            switch record.Type {
                case TypeDebug:
                    t = "[DBG] %s"
                case TypeMessage:
                    t = "[MSG] %s"
                case TypeWarning:
                    t = "[WRN] %s"
                case TypeError:
                    t = "[ERR] %s"
            }
            l.Printf(t, record.Message ... )
        }
    } ()
    return l, err
}

func NewLog(file string, flag, bufsize int) (l *Logger, err error){
    var f *os.File
    if file != "" {
        f, err = os.OpenFile(file, os.O_CREATE | os.O_APPEND | os.O_RDWR, 0600)
        if err != nil {
            f = os.Stdout
        }
    }
    if l == nil {
        f = os.Stdout
    }
    return New(f, flag, bufsize)
}

func (l *Logger) Errorf(format string, msg ... interface{}) {
    l.Error(errors.New(fmt.Sprintf(format, msg ...)))
}

func (l *Logger) Error(err error) {
    if l.flag & DisableError == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeError, Message: []interface{}{err}}
}

func (l *Logger) Warning(msg ... interface{}) {
    if l.flag & DisableWarning == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeWarning, Message: msg}
}

func (l *Logger) Warningf(format string, msg ... interface{}) {
    l.Warning(fmt.Sprintf(format, msg ...))
}

func (l *Logger) Message(msg ... interface{}) {
    if l.flag & DisableMessage == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeMessage, Message: msg}
}

func (l *Logger) Messagef(format string, msg ... interface{}) {
    l.Message(fmt.Sprintf(format, msg ...))
}

func (l *Logger) Debug(msg ... interface{}) {
    if l.flag & DisableDebug == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeDebug, Message: msg}
}

func (l *Logger) Debugf(format string, msg ... interface{}) {
    l.Debug(fmt.Sprintf(format, msg ...))
}

func (l *Logger) Close() {
    close(l.logChan)
}

// Close the logger and waiting all messages was printed
func (l *Logger) WaitClosing() {
    defer l.mutex.Unlock()
    l.Close()
    l.mutex.Lock()
}

var (
    DefaultLogger *Logger
    DefaultBufSize = 32
)

func init() {
    DefaultLogger, _ = NewLog("", LogAll, DefaultBufSize)
}

func Init(file string, flag int) (err error) {
    DefaultLogger, err = NewLog(file, flag, DefaultBufSize)
    return
}

func Error(err error) {
    DefaultLogger.Error(err)
}

func Errorf(format string, msg ... interface{}) {
    DefaultLogger.Errorf(format, msg ... )
}

func Warning(msg ... interface{}) {
    DefaultLogger.Warning(msg ... )
}

func Warningf(format string, msg ... interface{}) {
    DefaultLogger.Warningf(format, msg ... )
}

func Message(msg ... interface{}) {
    DefaultLogger.Message(msg ... )
}

func Messagef(format string, msg ... interface{}) {
    DefaultLogger.Messagef(format, msg ... )
}

func Debug(msg ... interface{}) {
    DefaultLogger.Debug(msg ... )
}

func Debugf(format string, msg ... interface{}) {
    DefaultLogger.Debugf(format, msg ... )
}

func Close() {
    DefaultLogger.Close()
}

func WaitClosing() {
    DefaultLogger.WaitClosing()
}

func Exit(code int) {
    runtime.Gosched()
    os.Exit(code)
}
<commit_msg>an other condition issue<commit_after>package log

import (
    "io"
    "os"
    "log"
    "fmt"
    "errors"
    "sync"
    "runtime"
)

const (
    DisableError = 1
    DisableWarning = 2
    DisableMessage = 4
    DisableDebug = 8
    LogAll = 0xF
    LogNone = 0
    LogError = LogAll ^ DisableWarning ^ DisableMessage ^ DisableDebug
    LogWarning = LogAll ^ DisableMessage ^ DisableDebug ^ DisableError
    LogMessage = LogAll ^ DisableDebug ^ DisableError ^ DisableWarning
    LogDebug = LogAll ^ DisableError ^ DisableWarning ^ DisableMessage
)

const (
    TypeDebug = iota
    TypeMessage
    TypeWarning
    TypeError
)

type Logger struct {
    *log.Logger
    flag int
    logChan chan *logRecord
    mutex sync.Mutex
}

type logRecord struct {
    Type uint8
    Message []interface{}
}

func New(w io.Writer, flag, bufsize int) (l *Logger, err error) {
    l = &Logger{Logger:log.New(w, "", log.LstdFlags), flag:flag}
    l.logChan = make(chan *logRecord, bufsize)
    go func() {
        l.mutex.Lock()
        defer l.mutex.Unlock()
        var t string
        for record := range l.logChan {
            switch record.Type {
                case TypeDebug:
                    t = "[DBG] %s"
                case TypeMessage:
                    t = "[MSG] %s"
                case TypeWarning:
                    t = "[WRN] %s"
                case TypeError:
                    t = "[ERR] %s"
            }
            l.Printf(t, record.Message ... )
        }
    } ()
    return l, err
}

func NewLog(file string, flag, bufsize int) (l *Logger, err error){
    var f *os.File
    if file != "" {
        f, err = os.OpenFile(file, os.O_CREATE | os.O_APPEND | os.O_RDWR, 0600)
        if err != nil {
            f = os.Stdout
        }
    }
    if f == nil {
        f = os.Stdout
    }
    return New(f, flag, bufsize)
}

func (l *Logger) Errorf(format string, msg ... interface{}) {
    l.Error(errors.New(fmt.Sprintf(format, msg ...)))
}

func (l *Logger) Error(err error) {
    if l.flag & DisableError == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeError, Message: []interface{}{err}}
}

func (l *Logger) Warning(msg ... interface{}) {
    if l.flag & DisableWarning == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeWarning, Message: msg}
}

func (l *Logger) Warningf(format string, msg ... interface{}) {
    l.Warning(fmt.Sprintf(format, msg ...))
}

func (l *Logger) Message(msg ... interface{}) {
    if l.flag & DisableMessage == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeMessage, Message: msg}
}

func (l *Logger) Messagef(format string, msg ... interface{}) {
    l.Message(fmt.Sprintf(format, msg ...))
}

func (l *Logger) Debug(msg ... interface{}) {
    if l.flag & DisableDebug == 0 {
        return
    }
    l.logChan <- &logRecord{Type:TypeDebug, Message: msg}
}

func (l *Logger) Debugf(format string, msg ... interface{}) {
    l.Debug(fmt.Sprintf(format, msg ...))
}

func (l *Logger) Close() {
    close(l.logChan)
}

// Close the logger and waiting all messages was printed
func (l *Logger) WaitClosing() {
    defer l.mutex.Unlock()
    l.Close()
    l.mutex.Lock()
}

var (
    DefaultLogger *Logger
    DefaultBufSize = 32
)

func init() {
    DefaultLogger, _ = NewLog("", LogAll, DefaultBufSize)
}

func Init(file string, flag int) (err error) {
    DefaultLogger, err = NewLog(file, flag, DefaultBufSize)
    return
}

func Error(err error) {
    DefaultLogger.Error(err)
}

func Errorf(format string, msg ... interface{}) {
    DefaultLogger.Errorf(format, msg ... )
}

func Warning(msg ... interface{}) {
    DefaultLogger.Warning(msg ... )
}

func Warningf(format string, msg ... interface{}) {
    DefaultLogger.Warningf(format, msg ... )
}

func Message(msg ... interface{}) {
    DefaultLogger.Message(msg ... )
}

func Messagef(format string, msg ... interface{}) {
    DefaultLogger.Messagef(format, msg ... )
}

func Debug(msg ... interface{}) {
    DefaultLogger.Debug(msg ... )
}

func Debugf(format string, msg ... interface{}) {
    DefaultLogger.Debugf(format, msg ... )
}

func Close() {
    DefaultLogger.Close()
}

func WaitClosing() {
    DefaultLogger.WaitClosing()
}

func Exit(code int) {
    runtime.Gosched()
    os.Exit(code)
}
<|endoftext|>


<commit_before>package log

import (
	"fmt"
	"os"

	"github.com/getsentry/sentry-go"
	log "github.com/sirupsen/logrus"
)

// SetupLog init logger
func SetupLog(l string) error {
	level, err := log.ParseLevel(l)
	if err != nil {
		return err
	}
	log.SetLevel(level)

	formatter := &log.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
		FullTimestamp:   true,
	}
	log.SetFormatter(formatter)
	log.SetOutput(os.Stdout)
	return nil
}

// Fields is identical to logrus.Fields
type Fields log.Fields

// WithField .
func (f Fields) WithField(key string, value interface{}) Fields {
	f[key] = value
	return f
}

// Errorf sends sentry message
func (f Fields) Errorf(format string, args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprintf(format, args...))
	log.WithFields(log.Fields(f)).Errorf(format, args...)
}

// Err is a decorator returning the argument
func (f Fields) Err(err error) error {
	if err != nil {
		sentry.CaptureMessage(fmt.Sprintf("%+v", err))
		log.WithFields(log.Fields(f)).Errorf("%+v", err)
	}
	return err
}

// WithField add kv into log entry
func WithField(key string, value interface{}) Fields {
	return Fields{key: value}
}

// Error forwards to sentry
func Error(args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprint(args...))
	log.Error(args...)
}

// Errorf forwards to sentry
func Errorf(format string, args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprintf(format, args...))
	log.Errorf(format, args...)
}

// Fatalf forwards to sentry
func Fatalf(format string, args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprintf(format, args...))
	log.Fatalf(format, args...)
}

// Warn is Warn
func Warn(args ...interface{}) {
	log.Warn(args...)
}

// Warnf is Warnf
func Warnf(format string, args ...interface{}) {
	log.Warnf(format, args...)
}

// Info is Info
func Info(args ...interface{}) {
	log.Info(args...)
}

// Infof is Infof
func Infof(format string, args ...interface{}) {
	log.Infof(format, args...)
}

// Debug is Debug
func Debug(args ...interface{}) {
	log.Debug(args...)
}

// Debugf is Debugf
func Debugf(format string, args ...interface{}) {
	log.Debugf(format, args...)
}
<commit_msg>force logging with color<commit_after>package log

import (
	"fmt"
	"os"

	"github.com/getsentry/sentry-go"
	log "github.com/sirupsen/logrus"
)

// SetupLog init logger
func SetupLog(l string) error {
	level, err := log.ParseLevel(l)
	if err != nil {
		return err
	}
	log.SetLevel(level)

	formatter := &log.TextFormatter{
		ForceColors:     true,
		TimestampFormat: "2006-01-02 15:04:05",
		FullTimestamp:   true,
	}
	log.SetFormatter(formatter)
	log.SetOutput(os.Stdout)
	return nil
}

// Fields is identical to logrus.Fields
type Fields log.Fields

// WithField .
func (f Fields) WithField(key string, value interface{}) Fields {
	f[key] = value
	return f
}

// Errorf sends sentry message
func (f Fields) Errorf(format string, args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprintf(format, args...))
	log.WithFields(log.Fields(f)).Errorf(format, args...)
}

// Err is a decorator returning the argument
func (f Fields) Err(err error) error {
	if err != nil {
		sentry.CaptureMessage(fmt.Sprintf("%+v", err))
		log.WithFields(log.Fields(f)).Errorf("%+v", err)
	}
	return err
}

// WithField add kv into log entry
func WithField(key string, value interface{}) Fields {
	return Fields{key: value}
}

// Error forwards to sentry
func Error(args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprint(args...))
	log.Error(args...)
}

// Errorf forwards to sentry
func Errorf(format string, args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprintf(format, args...))
	log.Errorf(format, args...)
}

// Fatalf forwards to sentry
func Fatalf(format string, args ...interface{}) {
	sentry.CaptureMessage(fmt.Sprintf(format, args...))
	log.Fatalf(format, args...)
}

// Warn is Warn
func Warn(args ...interface{}) {
	log.Warn(args...)
}

// Warnf is Warnf
func Warnf(format string, args ...interface{}) {
	log.Warnf(format, args...)
}

// Info is Info
func Info(args ...interface{}) {
	log.Info(args...)
}

// Infof is Infof
func Infof(format string, args ...interface{}) {
	log.Infof(format, args...)
}

// Debug is Debug
func Debug(args ...interface{}) {
	log.Debug(args...)
}

// Debugf is Debugf
func Debugf(format string, args ...interface{}) {
	log.Debugf(format, args...)
}
<|endoftext|>


<commit_before>// Package log provides basic interfaces for structured logging.
//
// The fundamental interface is Logger. Loggers create log events from
// key/value data.
package log

// Logger is the fundamental interface for all log operations.
//
// Log creates a log event from keyvals, a variadic sequence of alternating
// keys and values.
//
// Logger implementations must be safe for concurrent use by multiple
// goroutines.
type Logger interface {
	Log(keyvals ...interface{}) error
}

// With returns a new Logger that includes keyvals in all log events.
//
// If logger implements the Wither interface, the result of
// logger.With(keyvals...) is returned.
func With(logger Logger, keyvals ...interface{}) Logger {
	if w, ok := logger.(Wither); ok {
		return w.With(keyvals...)
	}
	// Limiting the capacity of the stored keyvals ensures that a new
	// backing array is created if the slice must grow in Log or With.
	// Using the extra capacity without copying risks a data race that
	// would violate the Logger interface contract.
	n := len(keyvals)
	return &withLogger{
		logger:  logger,
		keyvals: keyvals[:n:n],
	}
}

type withLogger struct {
	logger  Logger
	keyvals []interface{}
}

func (l *withLogger) Log(kvs ...interface{}) error {
	return l.logger.Log(append(l.keyvals, kvs...)...)
}

func (l *withLogger) With(keyvals ...interface{}) Logger {
	n := len(l.keyvals) + len(keyvals)
	return &withLogger{
		logger:  l.logger,
		keyvals: append(l.keyvals, keyvals...)[:n:n],
	}
}

// LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If
// f is a function with the appropriate signature, LoggerFunc(f) is a Logger
// object that calls f.
type LoggerFunc func(...interface{}) error

// Log implements Logger by calling f(keyvals...).
func (f LoggerFunc) Log(keyvals ...interface{}) error {
	return f(keyvals...)
}

// A Wither creates Loggers that include keyvals in all log events.
//
// The With function uses Wither if available.
type Wither interface {
	With(keyvals ...interface{}) Logger
}

// NewDiscardLogger returns a logger that does not log anything.
func NewDiscardLogger() Logger {
	return LoggerFunc(func(...interface{}) error {
		return nil
	})
}
<commit_msg>Use consistent parameter names.<commit_after>// Package log provides basic interfaces for structured logging.
//
// The fundamental interface is Logger. Loggers create log events from
// key/value data.
package log

// Logger is the fundamental interface for all log operations.
//
// Log creates a log event from keyvals, a variadic sequence of alternating
// keys and values.
//
// Logger implementations must be safe for concurrent use by multiple
// goroutines.
type Logger interface {
	Log(keyvals ...interface{}) error
}

// With returns a new Logger that includes keyvals in all log events.
//
// If logger implements the Wither interface, the result of
// logger.With(keyvals...) is returned.
func With(logger Logger, keyvals ...interface{}) Logger {
	if w, ok := logger.(Wither); ok {
		return w.With(keyvals...)
	}
	// Limiting the capacity of the stored keyvals ensures that a new
	// backing array is created if the slice must grow in Log or With.
	// Using the extra capacity without copying risks a data race that
	// would violate the Logger interface contract.
	n := len(keyvals)
	return &withLogger{
		logger:  logger,
		keyvals: keyvals[:n:n],
	}
}

type withLogger struct {
	logger  Logger
	keyvals []interface{}
}

func (l *withLogger) Log(keyvals ...interface{}) error {
	return l.logger.Log(append(l.keyvals, keyvals...)...)
}

func (l *withLogger) With(keyvals ...interface{}) Logger {
	n := len(l.keyvals) + len(keyvals)
	return &withLogger{
		logger:  l.logger,
		keyvals: append(l.keyvals, keyvals...)[:n:n],
	}
}

// LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If
// f is a function with the appropriate signature, LoggerFunc(f) is a Logger
// object that calls f.
type LoggerFunc func(...interface{}) error

// Log implements Logger by calling f(keyvals...).
func (f LoggerFunc) Log(keyvals ...interface{}) error {
	return f(keyvals...)
}

// A Wither creates Loggers that include keyvals in all log events.
//
// The With function uses Wither if available.
type Wither interface {
	With(keyvals ...interface{}) Logger
}

// NewDiscardLogger returns a logger that does not log anything.
func NewDiscardLogger() Logger {
	return LoggerFunc(func(...interface{}) error {
		return nil
	})
}
<|endoftext|>


<commit_before>// Package loghttp provides automatic logging functionalities to http.Client.
package loghttp

import (
	"log"
	"net/http"
	"time"
)

type RoundTripper func(*http.Request) (*http.Response, error)

// Transport implements http.RoundTripper. When set as Transport of http.Client, it executes HTTP requests with logging.
// No field is mandatory.
type Transport struct {
	Transport http.RoundTripper
	DoAround  func(req *http.Request, roundtrip RoundTripper) (*http.Response, error)
}

// THe default logging transport that wraps http.DefaultTransport.
var DefaultTransport = &Transport{
	Transport: http.DefaultTransport,
}

// Used if transport.LogRequest is not set.
var DefaultLogRequest = func(req *http.Request) {
}

// Used if transport.LogResponse is not set.
var DefaultLogResponse = func(resp *http.Response) {
}

var DefaultDoAround = func(req *http.Request, roundtrip RoundTripper) (*http.Response, error) {
	start := time.Now()
	log.Printf("---> %s %s", req.Method, req.URL)
	resp, err := roundtrip(req)
	if err != nil {
		return resp, err
	}
	log.Printf("<--- %d %s (%s)", resp.StatusCode, resp.Request.URL, time.Since(start))
	return resp, err
}

// RoundTrip is the core part of this module and implements http.RoundTripper.
// Executes HTTP request with request/response logging.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	return t.doAround(req, func(r *http.Request) (*http.Response, error) {
		return t.transport().RoundTrip(r)
	})
}

func (t *Transport) doAround(req *http.Request, roundtrip RoundTripper) (*http.Response, error) {
	if t.DoAround != nil {
		return t.DoAround(req, roundtrip)
	} else {
		return DefaultDoAround(req, roundtrip)
	}
}

func (t *Transport) transport() http.RoundTripper {
	if t.Transport != nil {
		return t.Transport
	}

	return http.DefaultTransport
}
<commit_msg>remove unused struct.<commit_after>// Package loghttp provides automatic logging functionalities to http.Client.
package loghttp

import (
	"log"
	"net/http"
	"time"
)

type RoundTripper func(*http.Request) (*http.Response, error)

// Transport implements http.RoundTripper. When set as Transport of http.Client, it executes HTTP requests with logging.
// No field is mandatory.
type Transport struct {
	Transport http.RoundTripper
	DoAround  func(req *http.Request, roundtrip RoundTripper) (*http.Response, error)
}

// THe default logging transport that wraps http.DefaultTransport.
var DefaultTransport = &Transport{
	Transport: http.DefaultTransport,
}

var DefaultDoAround = func(req *http.Request, roundtrip RoundTripper) (*http.Response, error) {
	start := time.Now()
	log.Printf("---> %s %s", req.Method, req.URL)
	resp, err := roundtrip(req)
	if err != nil {
		return resp, err
	}
	log.Printf("<--- %d %s (%s)", resp.StatusCode, resp.Request.URL, time.Since(start))
	return resp, err
}

// RoundTrip is the core part of this module and implements http.RoundTripper.
// Executes HTTP request with request/response logging.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	return t.doAround(req, func(r *http.Request) (*http.Response, error) {
		return t.transport().RoundTrip(r)
	})
}

func (t *Transport) doAround(req *http.Request, roundtrip RoundTripper) (*http.Response, error) {
	if t.DoAround != nil {
		return t.DoAround(req, roundtrip)
	} else {
		return DefaultDoAround(req, roundtrip)
	}
}

func (t *Transport) transport() http.RoundTripper {
	if t.Transport != nil {
		return t.Transport
	}

	return http.DefaultTransport
}
<|endoftext|>


<commit_before>// ls -- list files and directories
// Part of goutils (https://github.com/trevorparker/goutils)
//
// Copyright (c) 2014 Trevor Parker <trevor@trevorparker.com>
// All rights reserved
//
// Distributed under the terms of the Modified BSD License (see LICENSE)

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

type arg struct {
	file            []string
	almost_all      bool
	comma_separated bool
	one_per_line    bool
}

const (
	usage_message string = "usage: ls [OPTION ...] [FILE ...]"
	help_message  string = `List files and directories, and information about them.

  -A, --almost-all     include entries beginning with a dot, except
                       implied . and ..
  -m                   print a comma-separated list of entries
  -1                   print one entry per line
  -h, --help           print this help message and exit
`
)

func usage(error string) {
	fmt.Fprintf(os.Stderr, "ls: %s\n%s\n", error, usage_message)
	os.Exit(1)
}

func help() {
	fmt.Printf("%s\n%s", usage_message, help_message)
	os.Exit(0)
}

func ls(file string, args arg) {
	entries := make([]os.FileInfo, 0)

	// Determine if this is a file or directory, then call out
	// to ReadDir if it's a directory. Otherwise, we're can just
	// pass the file info on.
	fi, err := os.Stat(file)
	if err != nil {
		panic(err)
	} else if fi.IsDir() {
		e, err := ioutil.ReadDir(file)
		if err != nil {
			panic(err)
		}
		entries = e
	} else {
		entries = append(entries, fi)
	}
	printEntries(&entries, &args)
}

func printEntries(entries *[]os.FileInfo, args *arg) {
	var out bytes.Buffer

	filtered_entries := filterEntries(entries, args)

	if args.one_per_line {
		for _, e := range filtered_entries {
			out.WriteString(fmt.Sprintf("%s\n", e.Name()))
		}
		fmt.Print(out.String())
	} else if args.comma_separated {
		for i, e := range filtered_entries {
			out.WriteString(e.Name())
			if i < len(filtered_entries)-1 {
				out.WriteString(", ")
			}
		}
		fmt.Println(out.String())
	} else {
		longest_entry := 0
		for _, e := range filtered_entries {
			length := len(e.Name())
			if length > longest_entry {
				longest_entry = length + 1
			}
		}

		columns := int(78 / longest_entry)
		formatted_string := fmt.Sprintf("%%-%ds", longest_entry)
		for i, e := range filtered_entries {
			out.WriteString(fmt.Sprintf(formatted_string, e.Name()))
			if i%columns == columns-1 {
				out.WriteString("\n")
			}
		}
		fmt.Println(out.String())
	}
}

func filterEntries(entries *[]os.FileInfo, args *arg) []os.FileInfo {
	filtered_entries := make([]os.FileInfo, 0)
	for _, e := range *entries {
		if !args.almost_all && strings.HasPrefix(e.Name(), ".") {
			continue
		}
		filtered_entries = append(filtered_entries, e)
	}

	return filtered_entries
}

func main() {
	args := arg{}
	reached_files := false

	for i := 1; i < len(os.Args); i++ {
		if reached_files == false {
			if os.Args[i] == "-h" || os.Args[i] == "--help" {
				help()
			}
			if os.Args[i] == "-A" {
				args.almost_all = true
				continue
			}
			if os.Args[i] == "-m" {
				args.comma_separated = true
				continue
			}
			if os.Args[i] == "-1" {
				args.one_per_line = true
				continue
			}
			if os.Args[i] == "--" {
				reached_files = true
				continue
			}
			if os.Args[i] == "-" {
				reached_files = true
			}
		}
		reached_files = true
		arg_v := os.Args[i]
		args.file = append(args.file, arg_v)
	}

	if len(args.file) == 0 {
		ls("./", args)
	} else {
		for i := range args.file {
			ls(args.file[i], args)
		}
	}
}
<commit_msg>Fix divide by zero when no entries are found<commit_after>// ls -- list files and directories
// Part of goutils (https://github.com/trevorparker/goutils)
//
// Copyright (c) 2014 Trevor Parker <trevor@trevorparker.com>
// All rights reserved
//
// Distributed under the terms of the Modified BSD License (see LICENSE)

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

type arg struct {
	file            []string
	almost_all      bool
	comma_separated bool
	one_per_line    bool
}

const (
	usage_message string = "usage: ls [OPTION ...] [FILE ...]"
	help_message  string = `List files and directories, and information about them.

  -A, --almost-all     include entries beginning with a dot, except
                       implied . and ..
  -m                   print a comma-separated list of entries
  -1                   print one entry per line
  -h, --help           print this help message and exit
`
)

func usage(error string) {
	fmt.Fprintf(os.Stderr, "ls: %s\n%s\n", error, usage_message)
	os.Exit(1)
}

func help() {
	fmt.Printf("%s\n%s", usage_message, help_message)
	os.Exit(0)
}

func ls(file string, args arg) {
	entries := make([]os.FileInfo, 0)

	// Determine if this is a file or directory, then call out
	// to ReadDir if it's a directory. Otherwise, we're can just
	// pass the file info on.
	fi, err := os.Stat(file)
	if err != nil {
		panic(err)
	} else if fi.IsDir() {
		e, err := ioutil.ReadDir(file)
		if err != nil {
			panic(err)
		}
		entries = e
	} else {
		entries = append(entries, fi)
	}
	printEntries(&entries, &args)
}

func printEntries(entries *[]os.FileInfo, args *arg) {
	var out bytes.Buffer

	filtered_entries := filterEntries(entries, args)

	if args.one_per_line {
		for _, e := range filtered_entries {
			out.WriteString(fmt.Sprintf("%s\n", e.Name()))
		}
		fmt.Print(out.String())
	} else if args.comma_separated {
		for i, e := range filtered_entries {
			out.WriteString(e.Name())
			if i < len(filtered_entries)-1 {
				out.WriteString(", ")
			}
		}
		fmt.Println(out.String())
	} else {
		longest_entry := 1
		for _, e := range filtered_entries {
			length := len(e.Name())
			if length > longest_entry {
				longest_entry = length + 1
			}
		}

		columns := int(78 / longest_entry)
		formatted_string := fmt.Sprintf("%%-%ds", longest_entry)
		for i, e := range filtered_entries {
			out.WriteString(fmt.Sprintf(formatted_string, e.Name()))
			if i%columns == columns-1 {
				out.WriteString("\n")
			}
		}
		fmt.Println(out.String())
	}
}

func filterEntries(entries *[]os.FileInfo, args *arg) []os.FileInfo {
	filtered_entries := make([]os.FileInfo, 0)
	for _, e := range *entries {
		if !args.almost_all && strings.HasPrefix(e.Name(), ".") {
			continue
		}
		filtered_entries = append(filtered_entries, e)
	}

	return filtered_entries
}

func main() {
	args := arg{}
	reached_files := false

	for i := 1; i < len(os.Args); i++ {
		if reached_files == false {
			if os.Args[i] == "-h" || os.Args[i] == "--help" {
				help()
			}
			if os.Args[i] == "-A" {
				args.almost_all = true
				continue
			}
			if os.Args[i] == "-m" {
				args.comma_separated = true
				continue
			}
			if os.Args[i] == "-1" {
				args.one_per_line = true
				continue
			}
			if os.Args[i] == "--" {
				reached_files = true
				continue
			}
			if os.Args[i] == "-" {
				reached_files = true
			}
		}
		reached_files = true
		arg_v := os.Args[i]
		args.file = append(args.file, arg_v)
	}

	if len(args.file) == 0 {
		ls("./", args)
	} else {
		for i := range args.file {
			ls(args.file[i], args)
		}
	}
}
<|endoftext|>


<commit_before>// ls -- list files and directories
// Part of goutils (https://github.com/trevorparker/goutils)
//
// Copyright (c) 2014 Trevor Parker <trevor@trevorparker.com>
// All rights reserved
//
// Distributed under the terms of the Modified BSD License (see LICENSE)

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

type arg struct {
	file         []string
	one_per_line bool
}

const (
	usage_message string = "usage: ls [OPTION ...] [FILE ...]"
	help_message  string = `List files and directories, and information about them.

  -1             print one entry per line
  -h, --help     print this help message and exit
`
)

func usage(error string) {
	fmt.Fprintf(os.Stderr, "ls: %s\n%s\n", error, usage_message)
	os.Exit(1)
}

func help() {
	fmt.Printf("%s\n%s", usage_message, help_message)
	os.Exit(0)
}

func ls(file string, args arg) {
	entries, err := ioutil.ReadDir(file)
	if err != nil {
		panic(err)
	}

	printEntries(&entries, &args)
}

func printEntries(entries *[]os.FileInfo, args *arg) {
	var out bytes.Buffer

	if args.one_per_line {
		for _, e := range *entries {
			out.WriteString(fmt.Sprintf("%s\n", e.Name()))
		}
		fmt.Print(out.String())
	} else {
		longest_entry := 0
		for _, e := range *entries {
			length := len(e.Name())
			if length > longest_entry {
				longest_entry = length + 1
			}
		}

		columns := int(78 / longest_entry)
		formatted_string := fmt.Sprintf("%%-%ds", longest_entry)
		for i, e := range *entries {
			out.WriteString(fmt.Sprintf(formatted_string, e.Name()))
			if i%columns == columns-1 {
				out.WriteString("\n")
			}
		}
		fmt.Println(out.String())
	}
}

func main() {
	args := arg{}
	reached_files := false

	for i := 1; i < len(os.Args); i++ {
		if reached_files == false {
			if os.Args[i] == "-h" || os.Args[i] == "--help" {
				help()
			}
			if os.Args[i] == "-1" {
				args.one_per_line = true
				continue
			}
			if os.Args[i] == "--" {
				reached_files = true
				continue
			}
			if os.Args[i] == "-" {
				reached_files = true
			}
		}
		reached_files = true
		arg_v := os.Args[i]
		args.file = append(args.file, arg_v)
	}

	if len(args.file) == 0 {
		ls("./", args)
	} else {
		for i := range args.file {
			ls(args.file[i], args)
		}
	}
}
<commit_msg>Support calling `ls` directly on files<commit_after>// ls -- list files and directories
// Part of goutils (https://github.com/trevorparker/goutils)
//
// Copyright (c) 2014 Trevor Parker <trevor@trevorparker.com>
// All rights reserved
//
// Distributed under the terms of the Modified BSD License (see LICENSE)

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

type arg struct {
	file         []string
	one_per_line bool
}

const (
	usage_message string = "usage: ls [OPTION ...] [FILE ...]"
	help_message  string = `List files and directories, and information about them.

  -1             print one entry per line
  -h, --help     print this help message and exit
`
)

func usage(error string) {
	fmt.Fprintf(os.Stderr, "ls: %s\n%s\n", error, usage_message)
	os.Exit(1)
}

func help() {
	fmt.Printf("%s\n%s", usage_message, help_message)
	os.Exit(0)
}

func ls(file string, args arg) {
	entries := make([]os.FileInfo, 0)

	// Determine if this is a file or directory, then call out
	// to ReadDir if it's a directory. Otherwise, we're can just
	// pass the file info on.
	fi, err := os.Stat(file)
	if err != nil {
		panic(err)
	} else if fi.IsDir() {
		e, err := ioutil.ReadDir(file)
		if err != nil {
			panic(err)
		}
		entries = e
	} else {
		entries = append(entries, fi)
	}
	printEntries(&entries, &args)
}

func printEntries(entries *[]os.FileInfo, args *arg) {
	var out bytes.Buffer

	if args.one_per_line {
		for _, e := range *entries {
			out.WriteString(fmt.Sprintf("%s\n", e.Name()))
		}
		fmt.Print(out.String())
	} else {
		longest_entry := 0
		for _, e := range *entries {
			length := len(e.Name())
			if length > longest_entry {
				longest_entry = length + 1
			}
		}

		columns := int(78 / longest_entry)
		formatted_string := fmt.Sprintf("%%-%ds", longest_entry)
		for i, e := range *entries {
			out.WriteString(fmt.Sprintf(formatted_string, e.Name()))
			if i%columns == columns-1 {
				out.WriteString("\n")
			}
		}
		fmt.Println(out.String())
	}
}

func main() {
	args := arg{}
	reached_files := false

	for i := 1; i < len(os.Args); i++ {
		if reached_files == false {
			if os.Args[i] == "-h" || os.Args[i] == "--help" {
				help()
			}
			if os.Args[i] == "-1" {
				args.one_per_line = true
				continue
			}
			if os.Args[i] == "--" {
				reached_files = true
				continue
			}
			if os.Args[i] == "-" {
				reached_files = true
			}
		}
		reached_files = true
		arg_v := os.Args[i]
		args.file = append(args.file, arg_v)
	}

	if len(args.file) == 0 {
		ls("./", args)
	} else {
		for i := range args.file {
			ls(args.file[i], args)
		}
	}
}
<|endoftext|>


<commit_before>package lua

import (
	"errors"
	"fmt"
	"syscall"
	"unsafe"
)

var luaDLL = syscall.NewLazyDLL("lua53")

type Integer int64

const LUAINT_PER_UINTPTR = unsafe.Sizeof(Integer(0)) / unsafe.Sizeof(uintptr(0))

func (value Integer) Expand(list []uintptr) []uintptr {
	for i := uintptr(0); i < LUAINT_PER_UINTPTR; i++ {
		list = append(list, uintptr(value))
		value >>= (8 * unsafe.Sizeof(uintptr(1)))
	}
	return list
}

func CGoBytes(p, length uintptr) []byte {
	if length <= 0 || p == 0 {
		return []byte{}
	}
	buffer := make([]byte, length)
	for i := uintptr(0); i < length; i++ {
		buffer[i] = *(*byte)(unsafe.Pointer(p))
		p++
	}
	return buffer
}

func CGoStringN(p, length uintptr) string {
	if length <= 0 || p == 0 {
		return ""
	}
	return string(CGoBytes(p, length))
}

type Lua uintptr

var luaL_newstate = luaDLL.NewProc("luaL_newstate")

func New() Lua {
	lua, _, _ := luaL_newstate.Call()
	return Lua(lua)
}

func (this Lua) State() uintptr {
	return uintptr(this)
}

var luaL_openlibs = luaDLL.NewProc("luaL_openlibs")

func (this Lua) OpenLibs() {
	luaL_openlibs.Call(this.State())
}

var lua_close = luaDLL.NewProc("lua_close")

func (this Lua) Close() {
	lua_close.Call(this.State())
}

func (this Lua) Source(fname string) error {
	if err := this.Load(fname); err != nil {
		return err
	}
	return this.Call(0, 0)
}

var lua_settable = luaDLL.NewProc("lua_settable")

func (this Lua) SetTable(index int) {
	lua_settable.Call(this.State(), uintptr(index))
}

var lua_gettable = luaDLL.NewProc("lua_gettable")

func (this Lua) GetTable(index int) {
	lua_gettable.Call(this.State(), uintptr(index))
}

var lua_setmetatable = luaDLL.NewProc("lua_setmetatable")

func (this Lua) SetMetaTable(index int) {
	lua_setmetatable.Call(this.State(), uintptr(index))
}

var lua_gettop = luaDLL.NewProc("lua_gettop")

func (this Lua) GetTop() int {
	rv, _, _ := lua_gettop.Call(this.State())
	return int(rv)
}

var lua_settop = luaDLL.NewProc("lua_settop")

func (this Lua) SetTop(index int) {
	lua_settop.Call(this.State(), uintptr(index))
}

func (this Lua) Pop(n uint) {
	this.SetTop(-int(n) - 1)
}

var lua_newuserdata = luaDLL.NewProc("lua_newuserdata")

func (this Lua) NewUserData(size uintptr) unsafe.Pointer {
	area, _, _ := lua_newuserdata.Call(this.State(), size)
	return unsafe.Pointer(area)
}

var lua_rawseti = luaDLL.NewProc("lua_rawseti")

func (this Lua) RawSetI(index int, at Integer) {
	params := make([]uintptr, 0, 4)
	params = append(params, this.State(), uintptr(index))
	params = at.Expand(params)
	lua_rawseti.Call(params...)
}

var lua_rawgeti = luaDLL.NewProc("lua_rawgeti")

func (this Lua) RawGetI(index int, at Integer) {
	params := make([]uintptr, 0, 4)
	params = append(params, this.State(), uintptr(index))
	params = at.Expand(params)
	lua_rawgeti.Call(params...)
}

// 5.2
// var lua_remove = luaDLL.NewProc("lua_remove")
// 5.3
var lua_rotate = luaDLL.NewProc("lua_rotate")

func lua_remove_Call(state uintptr, index int) {
	lua_rotate.Call(state, uintptr(index), ^uintptr(0))
	lua_settop.Call(state, ^uintptr(1)) // ^1 == -2
}

func (this Lua) Remove(index int) {
	// 5.2
	// lua_remove.Call(this.State(), uintptr(index))
	// 5.3
	lua_remove_Call(this.State(), index)
}

var lua_replace = luaDLL.NewProc("lua_replace")

func (this Lua) Replace(index int) {
	lua_replace.Call(this.State(), uintptr(index))
}

var lua_setglobal = luaDLL.NewProc("lua_setglobal")

func (this Lua) SetGlobal(str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_setglobal.Call(this.State(), uintptr(unsafe.Pointer(cstr)))
}

var lua_setfield = luaDLL.NewProc("lua_setfield")

func (this Lua) SetField(index int, str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_setfield.Call(this.State(), uintptr(index), uintptr(unsafe.Pointer(cstr)))
}

var lua_getfield = luaDLL.NewProc("lua_getfield")

func (this Lua) GetField(index int, str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_getfield.Call(this.State(), uintptr(index), uintptr(unsafe.Pointer(cstr)))
}

var lua_getglobal = luaDLL.NewProc("lua_getglobal")

func (this Lua) GetGlobal(str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_getglobal.Call(this.State(), uintptr(unsafe.Pointer(cstr)))
}

var lua_createtable = luaDLL.NewProc("lua_createtable")

func (this Lua) NewTable() {
	lua_createtable.Call(this.State(), 0, 0)
}

var luaL_loadfilex = luaDLL.NewProc("luaL_loadfilex")

func (this Lua) Load(fname string) error {
	cfname, err := syscall.BytePtrFromString(fname)
	if err != nil {
		return err
	}
	rc, _, _ := luaL_loadfilex.Call(this.State(),
		uintptr(unsafe.Pointer(cfname)),
		uintptr(0))
	if rc == 0 {
		return nil
	}
	defer this.Pop(1)
	msg, err := this.ToString(-1)
	if err == nil {
		return fmt.Errorf("%s: %s..", fname, msg)
	} else {
		return err
	}
}

var luaL_loadstring = luaDLL.NewProc("luaL_loadstring")

func (this Lua) LoadString(code string) error {
	codePtr, err := syscall.BytePtrFromString(code)
	if err != nil {
		return err
	}
	rc, _, _ := luaL_loadstring.Call(this.State(), uintptr(unsafe.Pointer(codePtr)))
	if rc == 0 {
		return nil
	}
	defer this.Pop(1)
	msg, err := this.ToString(-1)
	if err == nil {
		return errors.New(msg)
	} else {
		return err
	}
}

var lua_pcallk = luaDLL.NewProc("lua_pcallk")

func (this Lua) Call(nargs, nresult int) error {
	rc, _, _ := lua_pcallk.Call(
		this.State(),
		uintptr(nargs),
		uintptr(nresult),
		0,
		0,
		0)
	if rc == 0 {
		return nil
	}
	defer this.Pop(1)
	if this.IsString(-1) {
		msg, err := this.ToString(-1)
		if err == nil {
			return errors.New(msg)
		} else {
			return err
		}
	} else {
		return errors.New("<Lua Error>")
	}
}

var lua_len = luaDLL.NewProc("lua_len")

func (this Lua) Len(index int) {
	lua_len.Call(this.State(), uintptr(index))
}
<commit_msg>Added method: lua.NewThread()<commit_after>package lua

import (
	"errors"
	"fmt"
	"syscall"
	"unsafe"
)

var luaDLL = syscall.NewLazyDLL("lua53")

type Integer int64

const LUAINT_PER_UINTPTR = unsafe.Sizeof(Integer(0)) / unsafe.Sizeof(uintptr(0))

func (value Integer) Expand(list []uintptr) []uintptr {
	for i := uintptr(0); i < LUAINT_PER_UINTPTR; i++ {
		list = append(list, uintptr(value))
		value >>= (8 * unsafe.Sizeof(uintptr(1)))
	}
	return list
}

func CGoBytes(p, length uintptr) []byte {
	if length <= 0 || p == 0 {
		return []byte{}
	}
	buffer := make([]byte, length)
	for i := uintptr(0); i < length; i++ {
		buffer[i] = *(*byte)(unsafe.Pointer(p))
		p++
	}
	return buffer
}

func CGoStringN(p, length uintptr) string {
	if length <= 0 || p == 0 {
		return ""
	}
	return string(CGoBytes(p, length))
}

type Lua uintptr

var luaL_newstate = luaDLL.NewProc("luaL_newstate")

func New() Lua {
	lua, _, _ := luaL_newstate.Call()
	return Lua(lua)
}

func (this Lua) State() uintptr {
	return uintptr(this)
}

var luaL_openlibs = luaDLL.NewProc("luaL_openlibs")

func (this Lua) OpenLibs() {
	luaL_openlibs.Call(this.State())
}

var lua_close = luaDLL.NewProc("lua_close")

func (this Lua) Close() {
	lua_close.Call(this.State())
}

func (this Lua) Source(fname string) error {
	if err := this.Load(fname); err != nil {
		return err
	}
	return this.Call(0, 0)
}

var lua_settable = luaDLL.NewProc("lua_settable")

func (this Lua) SetTable(index int) {
	lua_settable.Call(this.State(), uintptr(index))
}

var lua_gettable = luaDLL.NewProc("lua_gettable")

func (this Lua) GetTable(index int) {
	lua_gettable.Call(this.State(), uintptr(index))
}

var lua_setmetatable = luaDLL.NewProc("lua_setmetatable")

func (this Lua) SetMetaTable(index int) {
	lua_setmetatable.Call(this.State(), uintptr(index))
}

var lua_gettop = luaDLL.NewProc("lua_gettop")

func (this Lua) GetTop() int {
	rv, _, _ := lua_gettop.Call(this.State())
	return int(rv)
}

var lua_settop = luaDLL.NewProc("lua_settop")

func (this Lua) SetTop(index int) {
	lua_settop.Call(this.State(), uintptr(index))
}

func (this Lua) Pop(n uint) {
	this.SetTop(-int(n) - 1)
}

var lua_newuserdata = luaDLL.NewProc("lua_newuserdata")

func (this Lua) NewUserData(size uintptr) unsafe.Pointer {
	area, _, _ := lua_newuserdata.Call(this.State(), size)
	return unsafe.Pointer(area)
}

var lua_rawseti = luaDLL.NewProc("lua_rawseti")

func (this Lua) RawSetI(index int, at Integer) {
	params := make([]uintptr, 0, 4)
	params = append(params, this.State(), uintptr(index))
	params = at.Expand(params)
	lua_rawseti.Call(params...)
}

var lua_rawgeti = luaDLL.NewProc("lua_rawgeti")

func (this Lua) RawGetI(index int, at Integer) {
	params := make([]uintptr, 0, 4)
	params = append(params, this.State(), uintptr(index))
	params = at.Expand(params)
	lua_rawgeti.Call(params...)
}

// 5.2
// var lua_remove = luaDLL.NewProc("lua_remove")
// 5.3
var lua_rotate = luaDLL.NewProc("lua_rotate")

func lua_remove_Call(state uintptr, index int) {
	lua_rotate.Call(state, uintptr(index), ^uintptr(0))
	lua_settop.Call(state, ^uintptr(1)) // ^1 == -2
}

func (this Lua) Remove(index int) {
	// 5.2
	// lua_remove.Call(this.State(), uintptr(index))
	// 5.3
	lua_remove_Call(this.State(), index)
}

var lua_replace = luaDLL.NewProc("lua_replace")

func (this Lua) Replace(index int) {
	lua_replace.Call(this.State(), uintptr(index))
}

var lua_setglobal = luaDLL.NewProc("lua_setglobal")

func (this Lua) SetGlobal(str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_setglobal.Call(this.State(), uintptr(unsafe.Pointer(cstr)))
}

var lua_setfield = luaDLL.NewProc("lua_setfield")

func (this Lua) SetField(index int, str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_setfield.Call(this.State(), uintptr(index), uintptr(unsafe.Pointer(cstr)))
}

var lua_getfield = luaDLL.NewProc("lua_getfield")

func (this Lua) GetField(index int, str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_getfield.Call(this.State(), uintptr(index), uintptr(unsafe.Pointer(cstr)))
}

var lua_getglobal = luaDLL.NewProc("lua_getglobal")

func (this Lua) GetGlobal(str string) {
	cstr, err := syscall.BytePtrFromString(str)
	if err != nil {
		panic(err.Error())
	}
	lua_getglobal.Call(this.State(), uintptr(unsafe.Pointer(cstr)))
}

var lua_createtable = luaDLL.NewProc("lua_createtable")

func (this Lua) NewTable() {
	lua_createtable.Call(this.State(), 0, 0)
}

var luaL_loadfilex = luaDLL.NewProc("luaL_loadfilex")

func (this Lua) Load(fname string) error {
	cfname, err := syscall.BytePtrFromString(fname)
	if err != nil {
		return err
	}
	rc, _, _ := luaL_loadfilex.Call(this.State(),
		uintptr(unsafe.Pointer(cfname)),
		uintptr(0))
	if rc == 0 {
		return nil
	}
	defer this.Pop(1)
	msg, err := this.ToString(-1)
	if err == nil {
		return fmt.Errorf("%s: %s..", fname, msg)
	} else {
		return err
	}
}

var luaL_loadstring = luaDLL.NewProc("luaL_loadstring")

func (this Lua) LoadString(code string) error {
	codePtr, err := syscall.BytePtrFromString(code)
	if err != nil {
		return err
	}
	rc, _, _ := luaL_loadstring.Call(this.State(), uintptr(unsafe.Pointer(codePtr)))
	if rc == 0 {
		return nil
	}
	defer this.Pop(1)
	msg, err := this.ToString(-1)
	if err == nil {
		return errors.New(msg)
	} else {
		return err
	}
}

var lua_pcallk = luaDLL.NewProc("lua_pcallk")

func (this Lua) Call(nargs, nresult int) error {
	rc, _, _ := lua_pcallk.Call(
		this.State(),
		uintptr(nargs),
		uintptr(nresult),
		0,
		0,
		0)
	if rc == 0 {
		return nil
	}
	defer this.Pop(1)
	if this.IsString(-1) {
		msg, err := this.ToString(-1)
		if err == nil {
			return errors.New(msg)
		} else {
			return err
		}
	} else {
		return errors.New("<Lua Error>")
	}
}

var lua_len = luaDLL.NewProc("lua_len")

func (this Lua) Len(index int) {
	lua_len.Call(this.State(), uintptr(index))
}

var lua_newthread = luaDLL.NewProc("lua_newthread")

func (this Lua) NewThread() Lua {
	newthread, _, _ := lua_newthread.Call(this.State())
	return Lua(newthread)
}
<|endoftext|>


<commit_before>package vault

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/jhunt/ansi"
	"github.com/jhunt/tree"
)

// A Vault represents a means for interacting with a remote Vault
// instance (unsealed and pre-authenticated) to read and write secrets.
type Vault struct {
	URL    string
	Token  string
	Client *http.Client
}

// NewVault creates a new Vault object.  If an empty token is specified,
// the current user's token is read from ~/.vault-token.
func NewVault(url, token string) (*Vault, error) {
	if token == "" {
		b, err := ioutil.ReadFile(fmt.Sprintf("%s/.vault-token", os.Getenv("HOME")))
		if err != nil {
			return nil, err
		}
		token = string(b)
	}

	if token == "" {
		return nil, fmt.Errorf("no vault token specified; are you authenticated?")
	}

	return &Vault{
		URL:   url,
		Token: token,
		Client: &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: os.Getenv("VAULT_SKIP_VERIFY") != "",
				},
			},
			CheckRedirect: func(req *http.Request, via []*http.Request) error {
				if len(via) > 10 {
					return fmt.Errorf("stopped after 10 redirects")
				}
				req.Header.Add("X-Vault-Token", token)
				return nil
			},
		},
	}, nil
}

func (v *Vault) url(f string, args ...interface{}) string {
	return v.URL + fmt.Sprintf(f, args...)
}

func (v *Vault) request(req *http.Request) (*http.Response, error) {
	req.Header.Add("X-Vault-Token", v.Token)
	return v.Client.Do(req)
}

// Read checks the Vault for a Secret at the specified path, and returns it.
// If there is nothing at that path, a nil *Secret will be returned, with no
// error.
func (v *Vault) Read(path string) (secret *Secret, err error) {
	secret = NewSecret()
	req, err := http.NewRequest("GET", v.url("/v1/%s", path), nil)
	if err != nil {
		return
	}
	res, err := v.request(req)
	if err != nil {
		return
	}

	switch res.StatusCode {
	case 200:
		break
	case 404:
		err = NotFound
		return
	default:
		err = fmt.Errorf("API %s", res.Status)
		return
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}

	var raw map[string]interface{}
	if err = json.Unmarshal(b, &raw); err != nil {
		return
	}

	if rawdata, ok := raw["data"]; ok {
		if data, ok := rawdata.(map[string]interface{}); ok {
			for k, v := range data {
				if s, ok := v.(string); ok {
					secret.data[k] = s
				} else {
					b, err = json.Marshal(v)
					if err != nil {
						return
					}
					secret.data[k] = string(b)
				}
			}

			return
		}
	}
	err = fmt.Errorf("malformed response from vault")
	return
}

// List returns the set of (relative) paths that are directly underneath
// the given path.  Intermediate path nodes are suffixed with a single "/",
// whereas leaf nodes (the secrets themselves) are not.
func (v *Vault) List(path string) (paths []string, err error) {
	req, err := http.NewRequest("GET", v.url("/v1/%s?list=1", path), nil)
	if err != nil {
		return
	}
	res, err := v.request(req)
	if err != nil {
		return
	}

	switch res.StatusCode {
	case 200:
		break
	case 404:
		err = NotFound
		return
	default:
		err = fmt.Errorf("API %s", res.Status)
		return
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}

	var r struct{ Data struct{ Keys []string } }
	if err = json.Unmarshal(b, &r); err != nil {
		return
	}
	return r.Data.Keys, nil
}

type Node struct {
	Path     string
	Children []Node
}

// Tree returns a tree that represents the hierarhcy of paths contained
// below the given path, inside of the Vault.
func (v *Vault) Tree(path string, ansify bool) (tree.Node, error) {
	name := path
	if ansify {
		name = ansi.Sprintf("@C{%s}", path)
	}
	t := tree.New(name)

	l, err := v.List(path)
	if err != nil {
		return t, err
	}

	var kid tree.Node
	for _, p := range l {
		if p[len(p)-1:len(p)] == "/" {
			kid, err = v.Tree(path+"/"+p[0:len(p)-1], ansify)
			if ansify {
				name = ansi.Sprintf("@B{%s}", p)
			} else {
				name = p[0 : len(p)-1]
			}
		} else {
			kid, err = v.Tree(path+"/"+p, ansify)
			if ansify {
				name = ansi.Sprintf("@G{%s}", p)
			} else {
				name = p
			}
		}
		if err != nil {
			return t, err
		}
		kid.Name = name
		t.Append(kid)
	}
	return t, nil
}

// Write takes a Secret and writes it to the Vault at the specified path.
func (v *Vault) Write(path string, s *Secret) error {
	raw := s.JSON()
	if raw == "" {
		return fmt.Errorf("nothing to write")
	}

	req, err := http.NewRequest("POST", v.url("/v1/%s", path), strings.NewReader(raw))
	if err != nil {
		return err
	}
	res, err := v.request(req)
	if err != nil {
		return err
	}

	switch res.StatusCode {
	case 200:
		break
	case 204:
		break
	default:
		return fmt.Errorf("API %s", res.Status)
	}

	return nil
}

// Delete removes the secret stored at the specified path.
func (v *Vault) Delete(path string) error {
	req, err := http.NewRequest("DELETE", v.url("/v1/%s", path), nil)
	if err != nil {
		return err
	}
	res, err := v.request(req)
	if err != nil {
		return err
	}

	switch res.StatusCode {
	case 200:
		break
	case 204:
		break
	default:
		return fmt.Errorf("API %s", res.Status)
	}

	return nil
}

// Copy copies secrets from one path to another.
func (v *Vault) Copy(oldpath, newpath string) error {
	secret, err := v.Read(oldpath)
	if err != nil {
		return err
	}
	return v.Write(newpath, secret)
}

// Move moves secrets from one path to another.
func (v *Vault) Move(oldpath, newpath string) error {
	err := v.Copy(oldpath, newpath)
	if err != nil {
		return err
	}
	err = v.Delete(oldpath)
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>Suppress tree duplication for path/component duality<commit_after>package vault

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/jhunt/ansi"
	"github.com/jhunt/tree"
)

// A Vault represents a means for interacting with a remote Vault
// instance (unsealed and pre-authenticated) to read and write secrets.
type Vault struct {
	URL    string
	Token  string
	Client *http.Client
}

// NewVault creates a new Vault object.  If an empty token is specified,
// the current user's token is read from ~/.vault-token.
func NewVault(url, token string) (*Vault, error) {
	if token == "" {
		b, err := ioutil.ReadFile(fmt.Sprintf("%s/.vault-token", os.Getenv("HOME")))
		if err != nil {
			return nil, err
		}
		token = string(b)
	}

	if token == "" {
		return nil, fmt.Errorf("no vault token specified; are you authenticated?")
	}

	return &Vault{
		URL:   url,
		Token: token,
		Client: &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: os.Getenv("VAULT_SKIP_VERIFY") != "",
				},
			},
			CheckRedirect: func(req *http.Request, via []*http.Request) error {
				if len(via) > 10 {
					return fmt.Errorf("stopped after 10 redirects")
				}
				req.Header.Add("X-Vault-Token", token)
				return nil
			},
		},
	}, nil
}

func (v *Vault) url(f string, args ...interface{}) string {
	return v.URL + fmt.Sprintf(f, args...)
}

func (v *Vault) request(req *http.Request) (*http.Response, error) {
	req.Header.Add("X-Vault-Token", v.Token)
	return v.Client.Do(req)
}

// Read checks the Vault for a Secret at the specified path, and returns it.
// If there is nothing at that path, a nil *Secret will be returned, with no
// error.
func (v *Vault) Read(path string) (secret *Secret, err error) {
	secret = NewSecret()
	req, err := http.NewRequest("GET", v.url("/v1/%s", path), nil)
	if err != nil {
		return
	}
	res, err := v.request(req)
	if err != nil {
		return
	}

	switch res.StatusCode {
	case 200:
		break
	case 404:
		err = NotFound
		return
	default:
		err = fmt.Errorf("API %s", res.Status)
		return
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}

	var raw map[string]interface{}
	if err = json.Unmarshal(b, &raw); err != nil {
		return
	}

	if rawdata, ok := raw["data"]; ok {
		if data, ok := rawdata.(map[string]interface{}); ok {
			for k, v := range data {
				if s, ok := v.(string); ok {
					secret.data[k] = s
				} else {
					b, err = json.Marshal(v)
					if err != nil {
						return
					}
					secret.data[k] = string(b)
				}
			}

			return
		}
	}
	err = fmt.Errorf("malformed response from vault")
	return
}

// List returns the set of (relative) paths that are directly underneath
// the given path.  Intermediate path nodes are suffixed with a single "/",
// whereas leaf nodes (the secrets themselves) are not.
func (v *Vault) List(path string) (paths []string, err error) {
	req, err := http.NewRequest("GET", v.url("/v1/%s?list=1", path), nil)
	if err != nil {
		return
	}
	res, err := v.request(req)
	if err != nil {
		return
	}

	switch res.StatusCode {
	case 200:
		break
	case 404:
		err = NotFound
		return
	default:
		err = fmt.Errorf("API %s", res.Status)
		return
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}

	var r struct{ Data struct{ Keys []string } }
	if err = json.Unmarshal(b, &r); err != nil {
		return
	}
	return r.Data.Keys, nil
}

type Node struct {
	Path     string
	Children []Node
}

// Tree returns a tree that represents the hierarhcy of paths contained
// below the given path, inside of the Vault.
func (v *Vault) Tree(path string, ansify bool) (tree.Node, error) {
	name := path
	if ansify {
		name = ansi.Sprintf("@C{%s}", path)
	}
	t := tree.New(name)

	l, err := v.List(path)
	if err != nil {
		return t, err
	}

	seen := make(map[string]bool)
	var kid tree.Node
	for _, p := range l {
		if p[len(p)-1:len(p)] == "/" {
			if _, ok := seen[p[0:len(p)-1]]; ok {
				continue
			}
			kid, err = v.Tree(path+"/"+p[0:len(p)-1], ansify)
			if ansify {
				name = ansi.Sprintf("@B{%s}", p)
			} else {
				name = p[0 : len(p)-1]
			}
		} else {
			seen[p] = true
			kid, err = v.Tree(path+"/"+p, ansify)
			if ansify {
				name = ansi.Sprintf("@G{%s}", p)
			} else {
				name = p
			}
		}
		if err != nil {
			return t, err
		}
		kid.Name = name
		t.Append(kid)
	}
	return t, nil
}

// Write takes a Secret and writes it to the Vault at the specified path.
func (v *Vault) Write(path string, s *Secret) error {
	raw := s.JSON()
	if raw == "" {
		return fmt.Errorf("nothing to write")
	}

	req, err := http.NewRequest("POST", v.url("/v1/%s", path), strings.NewReader(raw))
	if err != nil {
		return err
	}
	res, err := v.request(req)
	if err != nil {
		return err
	}

	switch res.StatusCode {
	case 200:
		break
	case 204:
		break
	default:
		return fmt.Errorf("API %s", res.Status)
	}

	return nil
}

// Delete removes the secret stored at the specified path.
func (v *Vault) Delete(path string) error {
	req, err := http.NewRequest("DELETE", v.url("/v1/%s", path), nil)
	if err != nil {
		return err
	}
	res, err := v.request(req)
	if err != nil {
		return err
	}

	switch res.StatusCode {
	case 200:
		break
	case 204:
		break
	default:
		return fmt.Errorf("API %s", res.Status)
	}

	return nil
}

// Copy copies secrets from one path to another.
func (v *Vault) Copy(oldpath, newpath string) error {
	secret, err := v.Read(oldpath)
	if err != nil {
		return err
	}
	return v.Write(newpath, secret)
}

// Move moves secrets from one path to another.
func (v *Vault) Move(oldpath, newpath string) error {
	err := v.Copy(oldpath, newpath)
	if err != nil {
		return err
	}
	err = v.Delete(oldpath)
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package vend

type Config struct {
	Id                             *string     `json:"id,omitempty"`
	RetailerId                     *string     `json:"retailer_id,omitempty"`
	RetailerName                   *string     `json:"retailer_name,omitempty"`
	AccountState                   *string     `json:"account_state,omitempty"`
	DomainPrefix                   *string     `json:"domain_prefix,omitempty"`
	DisplayRetailPriceTaxInclusive *string     `json:"display_retail_price_tax_inclusive,omitempty"`
	UserId                         *string     `json:"user_id,omitempty"`
	UserName                       *string     `json:"user_name,omitempty"`
	UserHash                       *string     `json:"user_hash,omitempty"`
	UserDisplayName                *string     `json:"user_display_name,omitempty"`
	NotifyUserOfNumpad             *string     `json:"notify_useer_of_numpad,omitempty"`
	AccountType                    *string     `json:"account_type,omitempty"`
	OutletName                     *string     `json:"outlet_name,omitempty"`
	OutletId                       *string     `json:"outlet_id,omitempty"`
	Version                        *string     `json:"version,omitempty"`
	Migrations                     *Migrations `json:"migrate_sql,omitempty"`
	LastSync                       *string     `json:"last_sync,omitempty"`
	CurrencyName                   *string     `json:"currency_name,omitempty"`
	Currency                       *string     `json:"currency,omitempty"`
	Culture                        *string     `json:"culture,omitempty"`
	DefaultCustomerGroupId         *string     `json:"default_customer_group_id,omitempty"`
	DefaultCustomerId              *string     `json:"default_customer_id,omitempty"`
	DiscountProductId              *string     `json:"discount_product_id,omitempty"`
	CashierDiscount                *bool       `json:"cashier_discount,omitempty"`
	EnableLoyalty                  *int        `json:"enable_loyalty,omitempty"`
	Callbacks                      *Callbacks  `json:"callbacks,omitempty"`
}
<commit_msg>Removes Id from Config struct<commit_after>package vend

type Config struct {
	RetailerId                     *string     `json:"retailer_id,omitempty"`
	RetailerName                   *string     `json:"retailer_name,omitempty"`
	AccountState                   *string     `json:"account_state,omitempty"`
	DomainPrefix                   *string     `json:"domain_prefix,omitempty"`
	DisplayRetailPriceTaxInclusive *string     `json:"display_retail_price_tax_inclusive,omitempty"`
	UserId                         *string     `json:"user_id,omitempty"`
	UserName                       *string     `json:"user_name,omitempty"`
	UserHash                       *string     `json:"user_hash,omitempty"`
	UserDisplayName                *string     `json:"user_display_name,omitempty"`
	NotifyUserOfNumpad             *string     `json:"notify_useer_of_numpad,omitempty"`
	AccountType                    *string     `json:"account_type,omitempty"`
	OutletName                     *string     `json:"outlet_name,omitempty"`
	OutletId                       *string     `json:"outlet_id,omitempty"`
	Version                        *string     `json:"version,omitempty"`
	Migrations                     *Migrations `json:"migrate_sql,omitempty"`
	LastSync                       *string     `json:"last_sync,omitempty"`
	CurrencyName                   *string     `json:"currency_name,omitempty"`
	Currency                       *string     `json:"currency,omitempty"`
	Culture                        *string     `json:"culture,omitempty"`
	DefaultCustomerGroupId         *string     `json:"default_customer_group_id,omitempty"`
	DefaultCustomerId              *string     `json:"default_customer_id,omitempty"`
	DiscountProductId              *string     `json:"discount_product_id,omitempty"`
	CashierDiscount                *bool       `json:"cashier_discount,omitempty"`
	EnableLoyalty                  *int        `json:"enable_loyalty,omitempty"`
	Callbacks                      *Callbacks  `json:"callbacks,omitempty"`
}
<|endoftext|>


<commit_before>package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "regexp"
    "time"
)

func main() {
    fmt.Println("Verifying URLs..")

    readmeFile, err := ioutil.ReadFile("README.md")
    if err != nil {
        fmt.Println("Could not find README!")
        os.Exit(1)
    }

    fileContent := string(readmeFile)
    urlElementRegex := regexp.MustCompile(`(?m)\[.+?]\(((http|https)://.+?)\)`)

    httpClient := http.Client{Timeout: 20 * time.Second}

    var brokenUrls []string
    for _, urlElement := range urlElementRegex.FindAllStringSubmatch(fileContent, -1) {
        var url = urlElement[1]

        fmt.Printf("Checking %s: ", url)

        resp, err := httpClient.Get(url)
        if err != nil || resp.StatusCode != 200 {
            brokenUrls = append(brokenUrls, url)
            fmt.Println("FAILED - ", err)
        } else {
            fmt.Println("OK")
        }
    }

    if len(brokenUrls) != 0 {
        fmt.Println("Broken URLs were found:")
        for _, brokenUrl := range brokenUrls {
            fmt.Println(brokenUrl)
        }

        os.Exit(1)
    }

    fmt.Println("No broken URLs found!")
    os.Exit(0)
}
<commit_msg>adjustments so the script works with all urls - replaced depreciated ioutil.ReadFile() with os.ReadFile() - added support for http/2 - added a user agent - if there is no errormessage, show the http status text<commit_after>package main

import (
	"crypto/tls"
	"errors"
	"fmt"
	"net/http"
	"os"
	"regexp"
	"time"
)

func main() {
	fmt.Println("Verifying URLs..")

	readmeFile, err := os.ReadFile("README.md")
	if err != nil {
		fmt.Println("Could not find README!")
		os.Exit(1)
	}

	fileContent := string(readmeFile)
	urlElementRegex := regexp.MustCompile(`(?m)\[.+?]\(((http|https)://.+?)\)`)

	httpClient := http.Client{
		Timeout: 20 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{},
		},
	}

	var brokenUrls []string
	for _, urlElement := range urlElementRegex.FindAllStringSubmatch(fileContent, -1) {
		var url = urlElement[1]

		fmt.Printf("Checking %s: ", url)

		req, err := http.NewRequest("GET", url, nil)
		req.Header.Add("User-Agent", "URL status code verification for the Flyeralarm onboarding resources; https://github.com/flyeralarm/onboarding")
		resp, err := httpClient.Do(req)

		errormessage := err
		if errormessage == nil {
			errormessage = errors.New(http.StatusText(resp.StatusCode))
		}

		if err != nil || resp.StatusCode != 200 {
			brokenUrls = append(brokenUrls, url)
			fmt.Println("FAILED - ", errormessage)
		} else {
			fmt.Println("OK")
		}
	}

	if len(brokenUrls) != 0 {
		fmt.Println("Broken URLs were found:")
		for _, brokenUrl := range brokenUrls {
			fmt.Println(brokenUrl)
		}

		os.Exit(1)
	}

	fmt.Println("No broken URLs found!")
	os.Exit(0)
}
<|endoftext|>