<commit_before>// Copyright 2017 Corey Scott http://www.sage42.org/
//
// 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 generator

import (
	"bufio"
	"fmt"
	"go/parser"
	"go/token"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/corsc/go-commons/iocloser"
	"github.com/corsc/go-tools/package-coverage/utils"
)

const coverageFilename = "profile.cov"

var fakeTestFilename = "fake_test.go"
var fakeCodeFilename = "fake_code.go"

func processAllDirs(basePath string, exclusionsMatcher *regexp.Regexp, logTag string, actionFunc func(string)) {
	paths, err := utils.FindAllGoDirs(basePath)
	if err != nil {
		return
	}

	for _, path := range paths {
		if exclusionsMatcher.FindString(path) != "" {
			utils.LogWhenVerbose("[%s] path '%s' skipped due to skipDir regex '%s'",
				logTag, path, exclusionsMatcher.String())
			continue
		}

		utils.LogWhenVerbose("[%s] processing path '%s'", logTag, path)
		actionFunc(path)
	}
}

// this function will generate the test coverage for the supplied directory
func generateCoverage(path string, exclusions *regexp.Regexp, quietMode, race bool, tags string) {
	err := execCoverage(path, quietMode, race, tags)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error generating coverage %s", err)
	}

	err = filterCoverage(filepath.Join(path, coverageFilename), exclusions)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error filtering files: %s", err)
	}
}

func addFakes(path, packageName string) {
	testFilename := createTestFilename(path)
	createTestFile(packageName, testFilename)

	codeFilename := createCodeFilename(path)
	createCodeFile(packageName, codeFilename)
}

func removeFakes(path string) {
	testFilename := createTestFilename(path)
	utils.LogWhenVerbose("[coverage] remove fake test @ %s", testFilename)
	err := os.Remove(testFilename)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while removing fake test @ %s, err: %s", testFilename, err)
	}

	codeFilename := createCodeFilename(path)
	utils.LogWhenVerbose("[coverage] remove fake code @ %s", codeFilename)
	err = os.Remove(codeFilename)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while removing fake code @ %s, err: %s", codeFilename, err)
	}
}

func createTestFilename(path string) string {
	return path + fakeTestFilename
}

func createCodeFilename(path string) string {
	return path + fakeCodeFilename
}

// find the package name by using the go AST
func findPackageName(path string) string {
	fileSet := token.NewFileSet()
	pkgs, err := parser.ParseDir(fileSet, path, nil, 0)
	if err != nil {
		utils.LogWhenVerbose("[coverage] err while parsing the '%s' into Go AST Err: '%s", path, err)
		return UnknownPackage
	}

	for pkgName := range pkgs {
		return pkgName
	}

	return UnknownPackage
}

// create a fake test so that all directories are guaranteed to contain tests (and therefore coverage will be generated)
func createTestFile(packageName string, testFilename string) {
	utils.LogWhenVerbose("[coverage] created test for package %s file @ %s", packageName, testFilename)

	if _, err := os.Stat(testFilename); err == nil {
		utils.LogWhenVerbose("[coverage] file already exists @ %s cowardly refusing to overwrite", testFilename)
		return
	}

	file, err := os.OpenFile(testFilename, os.O_RDWR|os.O_CREATE, 0600)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while creating test file %s", err)
		return
	}

	_, err = file.WriteString(`package ` + packageName + `

import "testing"

func TestThisTestDoesntReallyTestAnything(t *testing.T) {}
`)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while writing test file %s", err)
		return
	}

	err = file.Close()
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while closing file '%s", err)
	}
}

// create a fake function so that all directories are guaranteed to contain code (and therefore coverage will be generated)
func createCodeFile(packageName string, codeFilename string) {
	utils.LogWhenVerbose("[coverage] created code for package %s file @ %s", packageName, codeFilename)

	if _, err := os.Stat(codeFilename); err == nil {
		utils.LogWhenVerbose("[coverage] file already exists @ %s cowardly refusing to overwrite", codeFilename)
		return
	}

	file, err := os.OpenFile(codeFilename, os.O_RDWR|os.O_CREATE, 0600)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while creating code file %s", err)
		return
	}

	_, err = file.WriteString(`package ` + packageName + `

func ThisCodeDoesntReallyDoAnything() {}
`)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while writing code file %s", err)
		return
	}

	err = file.Close()
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while closing file '%s", err)
	}
}

// essentially call `go test` to generate the coverage
func execCoverage(dir string, quiet, race bool, tags string) error {
	arguments := []string{
		"test",
		"-coverprofile=" + coverageFilename,
	}

	if race {
		arguments = append(arguments, `--race`)
	}

	if len(tags) > 0 {
		arguments = append(arguments, `-tags="`+tags+`"`)
	}

	cmd := exec.Command("go", arguments...)
	cmd.Dir = dir

	if !quiet {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}

	payload, err := cmd.CombinedOutput()
	if err != nil {
		utils.LogAlways("failed to get test command output. dir: %s err: %s", dir, err)
	}

	if err != nil {
		utils.LogAlways("[coverage] test output %s:\n%s", dir, payload)

		if err.Error() == "exit status 1" {
			utils.LogAlways("WARNING: tests for %s are broken. err: %s", dir, err)
		} else {
			utils.LogAlways("[coverage] error while running go test %s. err: %s", dir, err)
		}

		return err
	} else {
		utils.LogWhenVerbose("[coverage] test output %s:\n%s", dir, payload)
	}

	utils.LogWhenVerbose("[coverage] created coverage file @ %s%s", dir, coverageFilename)
	return nil
}

func filterCoverage(coverageFilename string, exclusionsMatcher *regexp.Regexp) error {
	coverageTempFilename := coverageFilename + "~"

	coverageTempFile, err := os.OpenFile(coverageTempFilename, os.O_RDWR|os.O_CREATE, 0600)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while opening file %s, err: %s", coverageTempFilename, err)
		return err
	}

	defer iocloser.Close(coverageTempFile)

	coverageFile, err := os.OpenFile(coverageFilename, os.O_RDWR, 0)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while opening file %s, err: %s", coverageFilename, err)
		return err
	}

	defer func() {
		if err := coverageFile.Close(); err != nil {
			utils.LogWhenVerbose("[coverage] Cannot close coverage file %s: %s", coverageFilename, err)
		}
	}()

	if err := filterCoverageContents(exclusionsMatcher, coverageFile, coverageTempFile); err != nil {
		utils.LogWhenVerbose("[coverage] error while filtering coverage file %s: %s", coverageFilename, err)
		return err
	}

	if err := os.Remove(coverageFilename); err != nil {
		utils.LogWhenVerbose("[coverage] cannot remove old coverage file %s: %s", coverageFilename, err)
	}

	if err := os.Rename(coverageTempFilename, coverageFilename); err != nil {
		utils.LogWhenVerbose("[coverage] cannot rename filtered coverage file %s: %s", coverageTempFilename, err)
	}

	return nil
}

func filterCoverageContents(exclusionsMatcher *regexp.Regexp, in io.Reader, out io.Writer) error {
	coverageFileScanner := bufio.NewScanner(in)
	for coverageFileScanner.Scan() {
		line := coverageFileScanner.Text()

		fileNameEndIndex := strings.LastIndex(line, ":")
		if fileNameEndIndex == -1 {
			utils.LogWhenVerbose("[coverage] error in line '%s'", line)
			continue
		}

		fileName := line[:fileNameEndIndex]

		if exclusionsMatcher.MatchString(fileName) {
			utils.LogWhenVerbose("[coverage] skipped file %s", fileName)
			continue
		}

		if _, err := fmt.Fprintln(out, line); err != nil {
			return err
		}
	}

	return nil
}
<commit_msg>[PackageCoverage] Address issue with _test package usage<commit_after>// Copyright 2017 Corey Scott http://www.sage42.org/
//
// 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 generator

import (
	"bufio"
	"fmt"
	"go/parser"
	"go/token"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/corsc/go-commons/iocloser"
	"github.com/corsc/go-tools/package-coverage/utils"
)

const coverageFilename = "profile.cov"

var fakeTestFilename = "fake_test.go"
var fakeCodeFilename = "fake_code.go"

func processAllDirs(basePath string, exclusionsMatcher *regexp.Regexp, logTag string, actionFunc func(string)) {
	paths, err := utils.FindAllGoDirs(basePath)
	if err != nil {
		return
	}

	for _, path := range paths {
		if exclusionsMatcher.FindString(path) != "" {
			utils.LogWhenVerbose("[%s] path '%s' skipped due to skipDir regex '%s'",
				logTag, path, exclusionsMatcher.String())
			continue
		}

		utils.LogWhenVerbose("[%s] processing path '%s'", logTag, path)
		actionFunc(path)
	}
}

// this function will generate the test coverage for the supplied directory
func generateCoverage(path string, exclusions *regexp.Regexp, quietMode, race bool, tags string) {
	err := execCoverage(path, quietMode, race, tags)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error generating coverage %s", err)
	}

	err = filterCoverage(filepath.Join(path, coverageFilename), exclusions)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error filtering files: %s", err)
	}
}

func addFakes(path, packageName string) {
	testFilename := createTestFilename(path)
	createTestFile(packageName, testFilename)

	codeFilename := createCodeFilename(path)
	createCodeFile(packageName, codeFilename)
}

func removeFakes(path string) {
	testFilename := createTestFilename(path)
	utils.LogWhenVerbose("[coverage] remove fake test @ %s", testFilename)
	err := os.Remove(testFilename)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while removing fake test @ %s, err: %s", testFilename, err)
	}

	codeFilename := createCodeFilename(path)
	utils.LogWhenVerbose("[coverage] remove fake code @ %s", codeFilename)
	err = os.Remove(codeFilename)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while removing fake code @ %s, err: %s", codeFilename, err)
	}
}

func createTestFilename(path string) string {
	return path + fakeTestFilename
}

func createCodeFilename(path string) string {
	return path + fakeCodeFilename
}

// find the package name by using the go AST
func findPackageName(path string) string {
	fileSet := token.NewFileSet()
	pkgs, err := parser.ParseDir(fileSet, path, nil, 0)
	if err != nil {
		utils.LogWhenVerbose("[coverage] err while parsing the '%s' into Go AST Err: '%s", path, err)
		return UnknownPackage
	}

	if len(pkgs) == 0 {
		return UnknownPackage
	}

	var out string

	for pkgName := range pkgs {
		out = pkgName

		// attempt to skip any _test packages
		if !strings.HasSuffix(pkgName, "_test") {
			return pkgName
		}
	}

	// use the only value
	return out
}

// create a fake test so that all directories are guaranteed to contain tests (and therefore coverage will be generated)
func createTestFile(packageName string, testFilename string) {
	utils.LogWhenVerbose("[coverage] created test for package %s file @ %s", packageName, testFilename)

	if _, err := os.Stat(testFilename); err == nil {
		utils.LogWhenVerbose("[coverage] file already exists @ %s cowardly refusing to overwrite", testFilename)
		return
	}

	file, err := os.OpenFile(testFilename, os.O_RDWR|os.O_CREATE, 0600)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while creating test file %s", err)
		return
	}

	_, err = file.WriteString(`package ` + packageName + `

import "testing"

func TestThisTestDoesntReallyTestAnything(t *testing.T) {}
`)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while writing test file %s", err)
		return
	}

	err = file.Close()
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while closing file '%s", err)
	}
}

// create a fake function so that all directories are guaranteed to contain code (and therefore coverage will be generated)
func createCodeFile(packageName string, codeFilename string) {
	utils.LogWhenVerbose("[coverage] created code for package %s file @ %s", packageName, codeFilename)

	if _, err := os.Stat(codeFilename); err == nil {
		utils.LogWhenVerbose("[coverage] file already exists @ %s cowardly refusing to overwrite", codeFilename)
		return
	}

	file, err := os.OpenFile(codeFilename, os.O_RDWR|os.O_CREATE, 0600)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while creating code file %s", err)
		return
	}

	_, err = file.WriteString(`package ` + packageName + `

func ThisCodeDoesntReallyDoAnything() {}
`)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while writing code file %s", err)
		return
	}

	err = file.Close()
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while closing file '%s", err)
	}
}

// essentially call `go test` to generate the coverage
func execCoverage(dir string, quiet, race bool, tags string) error {
	arguments := []string{
		"test",
		"-coverprofile=" + coverageFilename,
	}

	if race {
		arguments = append(arguments, `--race`)
	}

	if len(tags) > 0 {
		arguments = append(arguments, `-tags="`+tags+`"`)
	}

	cmd := exec.Command("go", arguments...)
	cmd.Dir = dir

	if !quiet {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}

	payload, err := cmd.CombinedOutput()
	if err != nil {
		utils.LogAlways("failed to get test command output. dir: %s err: %s", dir, err)
	}

	if err != nil {
		utils.LogAlways("[coverage] test output %s:\n%s", dir, payload)

		if err.Error() == "exit status 1" {
			utils.LogAlways("WARNING: tests for %s are broken. err: %s", dir, err)
		} else {
			utils.LogAlways("[coverage] error while running go test %s. err: %s", dir, err)
		}

		return err
	} else {
		utils.LogWhenVerbose("[coverage] test output %s:\n%s", dir, payload)
	}

	utils.LogWhenVerbose("[coverage] created coverage file @ %s%s", dir, coverageFilename)
	return nil
}

func filterCoverage(coverageFilename string, exclusionsMatcher *regexp.Regexp) error {
	coverageTempFilename := coverageFilename + "~"

	coverageTempFile, err := os.OpenFile(coverageTempFilename, os.O_RDWR|os.O_CREATE, 0600)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while opening file %s, err: %s", coverageTempFilename, err)
		return err
	}

	defer iocloser.Close(coverageTempFile)

	coverageFile, err := os.OpenFile(coverageFilename, os.O_RDWR, 0)
	if err != nil {
		utils.LogWhenVerbose("[coverage] error while opening file %s, err: %s", coverageFilename, err)
		return err
	}

	defer func() {
		if err := coverageFile.Close(); err != nil {
			utils.LogWhenVerbose("[coverage] Cannot close coverage file %s: %s", coverageFilename, err)
		}
	}()

	if err := filterCoverageContents(exclusionsMatcher, coverageFile, coverageTempFile); err != nil {
		utils.LogWhenVerbose("[coverage] error while filtering coverage file %s: %s", coverageFilename, err)
		return err
	}

	if err := os.Remove(coverageFilename); err != nil {
		utils.LogWhenVerbose("[coverage] cannot remove old coverage file %s: %s", coverageFilename, err)
	}

	if err := os.Rename(coverageTempFilename, coverageFilename); err != nil {
		utils.LogWhenVerbose("[coverage] cannot rename filtered coverage file %s: %s", coverageTempFilename, err)
	}

	return nil
}

func filterCoverageContents(exclusionsMatcher *regexp.Regexp, in io.Reader, out io.Writer) error {
	coverageFileScanner := bufio.NewScanner(in)
	for coverageFileScanner.Scan() {
		line := coverageFileScanner.Text()

		fileNameEndIndex := strings.LastIndex(line, ":")
		if fileNameEndIndex == -1 {
			utils.LogWhenVerbose("[coverage] error in line '%s'", line)
			continue
		}

		fileName := line[:fileNameEndIndex]

		if exclusionsMatcher.MatchString(fileName) {
			utils.LogWhenVerbose("[coverage] skipped file %s", fileName)
			continue
		}

		if _, err := fmt.Fprintln(out, line); err != nil {
			return err
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"

	"github.com/lxc/lxd/lxc/config"
	"github.com/lxc/lxd/lxc/utils"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	cli "github.com/lxc/lxd/shared/cmd"
	"github.com/lxc/lxd/shared/i18n"
)

// Start
type cmdStart struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdStart) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("start")
	cmd.Use = i18n.G("start [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Start instances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Start instances`))

	return cmd
}

// Pause
type cmdPause struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdPause) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("pause")
	cmd.Use = i18n.G("pause [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Pause instances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Pause instances`))
	cmd.Hidden = true

	return cmd
}

// Restart
type cmdRestart struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdRestart) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("restart")
	cmd.Use = i18n.G("restart [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Restart insances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Restart instances

The opposite of "lxc pause" is "lxc start".`))

	return cmd
}

// Stop
type cmdStop struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdStop) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("stop")
	cmd.Use = i18n.G("stop [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Stop instances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Stop instances`))

	return cmd
}

type cmdAction struct {
	global *cmdGlobal

	flagAll       bool
	flagForce     bool
	flagStateful  bool
	flagStateless bool
	flagTimeout   int
}

func (c *cmdAction) Command(action string) *cobra.Command {
	cmd := &cobra.Command{}
	cmd.RunE = c.Run

	cmd.Flags().BoolVar(&c.flagAll, "all", false, i18n.G("Run against all instances"))

	if action == "stop" {
		cmd.Flags().BoolVar(&c.flagStateful, "stateful", false, i18n.G("Store the instance state"))
	} else if action == "start" {
		cmd.Flags().BoolVar(&c.flagStateless, "stateless", false, i18n.G("Ignore the instance state"))
	}

	if shared.StringInSlice(action, []string{"restart", "stop"}) {
		cmd.Flags().BoolVarP(&c.flagForce, "force", "f", false, i18n.G("Force the instance to shutdown"))
		cmd.Flags().IntVar(&c.flagTimeout, "timeout", -1, i18n.G("Time to wait for the instance before killing it")+"``")
	}

	return cmd
}

func (c *cmdAction) doAction(action string, conf *config.Config, nameArg string) error {
	state := false

	// Pause is called freeze
	if action == "pause" {
		action = "freeze"
	}

	// Only store state if asked to
	if action == "stop" && c.flagStateful {
		state = true
	}

	remote, name, err := conf.ParseRemote(nameArg)
	if err != nil {
		return err
	}

	d, err := conf.GetInstanceServer(remote)
	if err != nil {
		return err
	}

	if name == "" {
		return fmt.Errorf(i18n.G("Must supply instance name for: ")+"\"%s\"", nameArg)
	}

	if action == "start" {
		current, _, err := d.GetInstance(name)
		if err != nil {
			return err
		}

		// "start" for a frozen instance means "unfreeze"
		if current.StatusCode == api.Frozen {
			action = "unfreeze"
		}

		// Always restore state (if present) unless asked not to
		if action == "start" && current.Stateful && !c.flagStateless {
			state = true
		}
	}

	req := api.InstanceStatePut{
		Action:   action,
		Timeout:  c.flagTimeout,
		Force:    c.flagForce,
		Stateful: state,
	}

	op, err := d.UpdateInstanceState(name, req, "")
	if err != nil {
		return err
	}

	progress := utils.ProgressRenderer{
		Quiet: c.global.flagQuiet,
	}
	_, err = op.AddHandler(progress.UpdateOp)
	if err != nil {
		progress.Done("")
		return err
	}

	// Wait for operation to finish
	err = utils.CancelableWait(op, &progress)
	if err != nil {
		progress.Done("")
		return fmt.Errorf("%s\n"+i18n.G("Try `lxc info --show-log %s` for more info"), err, nameArg)
	}

	progress.Done("")

	return nil
}

func (c *cmdAction) Run(cmd *cobra.Command, args []string) error {
	conf := c.global.conf

	var names []string
	if len(args) == 0 {
		if !c.flagAll {
			cmd.Help()
			return nil
		}

		d, err := conf.GetInstanceServer(conf.DefaultRemote)
		if err != nil {
			return err
		}

		ctslist, err := d.GetInstances(api.InstanceTypeAny)
		if err != nil {
			return err
		}

		for _, ct := range ctslist {
			switch cmd.Name() {
			case "start":
				if ct.StatusCode == api.Running {
					continue
				}
			case "stop":
				if ct.StatusCode == api.Stopped {
					continue
				}
			}
			names = append(names, ct.Name)
		}
	} else {
		if c.flagAll {
			return fmt.Errorf(i18n.G("Both --all and instance name given"))
		}
		names = args
	}

	// Run the action for every listed instance
	results := runBatch(names, func(name string) error { return c.doAction(cmd.Name(), conf, name) })

	// Single instance is easy
	if len(results) == 1 {
		return results[0].err
	}

	// Do fancier rendering for batches
	success := true

	for _, result := range results {
		if result.err == nil {
			continue
		}

		success = false
		msg := fmt.Sprintf(i18n.G("error: %v"), result.err)
		for _, line := range strings.Split(msg, "\n") {
			fmt.Fprintln(os.Stderr, fmt.Sprintf("%s: %s", result.name, line))
		}
	}

	if !success {
		fmt.Fprintln(os.Stderr, "")
		return fmt.Errorf(i18n.G("Some instances failed to %s"), cmd.Name())
	}

	return nil
}
<commit_msg>lxc/action: Fix typo in help message<commit_after>package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"

	"github.com/lxc/lxd/lxc/config"
	"github.com/lxc/lxd/lxc/utils"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	cli "github.com/lxc/lxd/shared/cmd"
	"github.com/lxc/lxd/shared/i18n"
)

// Start
type cmdStart struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdStart) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("start")
	cmd.Use = i18n.G("start [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Start instances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Start instances`))

	return cmd
}

// Pause
type cmdPause struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdPause) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("pause")
	cmd.Use = i18n.G("pause [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Pause instances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Pause instances`))
	cmd.Hidden = true

	return cmd
}

// Restart
type cmdRestart struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdRestart) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("restart")
	cmd.Use = i18n.G("restart [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Restart instances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Restart instances

The opposite of "lxc pause" is "lxc start".`))

	return cmd
}

// Stop
type cmdStop struct {
	global *cmdGlobal
	action *cmdAction
}

func (c *cmdStop) Command() *cobra.Command {
	cmdAction := cmdAction{global: c.global}
	c.action = &cmdAction

	cmd := c.action.Command("stop")
	cmd.Use = i18n.G("stop [<remote>:]<instance> [[<remote>:]<instance>...]")
	cmd.Short = i18n.G("Stop instances")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Stop instances`))

	return cmd
}

type cmdAction struct {
	global *cmdGlobal

	flagAll       bool
	flagForce     bool
	flagStateful  bool
	flagStateless bool
	flagTimeout   int
}

func (c *cmdAction) Command(action string) *cobra.Command {
	cmd := &cobra.Command{}
	cmd.RunE = c.Run

	cmd.Flags().BoolVar(&c.flagAll, "all", false, i18n.G("Run against all instances"))

	if action == "stop" {
		cmd.Flags().BoolVar(&c.flagStateful, "stateful", false, i18n.G("Store the instance state"))
	} else if action == "start" {
		cmd.Flags().BoolVar(&c.flagStateless, "stateless", false, i18n.G("Ignore the instance state"))
	}

	if shared.StringInSlice(action, []string{"restart", "stop"}) {
		cmd.Flags().BoolVarP(&c.flagForce, "force", "f", false, i18n.G("Force the instance to shutdown"))
		cmd.Flags().IntVar(&c.flagTimeout, "timeout", -1, i18n.G("Time to wait for the instance before killing it")+"``")
	}

	return cmd
}

func (c *cmdAction) doAction(action string, conf *config.Config, nameArg string) error {
	state := false

	// Pause is called freeze
	if action == "pause" {
		action = "freeze"
	}

	// Only store state if asked to
	if action == "stop" && c.flagStateful {
		state = true
	}

	remote, name, err := conf.ParseRemote(nameArg)
	if err != nil {
		return err
	}

	d, err := conf.GetInstanceServer(remote)
	if err != nil {
		return err
	}

	if name == "" {
		return fmt.Errorf(i18n.G("Must supply instance name for: ")+"\"%s\"", nameArg)
	}

	if action == "start" {
		current, _, err := d.GetInstance(name)
		if err != nil {
			return err
		}

		// "start" for a frozen instance means "unfreeze"
		if current.StatusCode == api.Frozen {
			action = "unfreeze"
		}

		// Always restore state (if present) unless asked not to
		if action == "start" && current.Stateful && !c.flagStateless {
			state = true
		}
	}

	req := api.InstanceStatePut{
		Action:   action,
		Timeout:  c.flagTimeout,
		Force:    c.flagForce,
		Stateful: state,
	}

	op, err := d.UpdateInstanceState(name, req, "")
	if err != nil {
		return err
	}

	progress := utils.ProgressRenderer{
		Quiet: c.global.flagQuiet,
	}
	_, err = op.AddHandler(progress.UpdateOp)
	if err != nil {
		progress.Done("")
		return err
	}

	// Wait for operation to finish
	err = utils.CancelableWait(op, &progress)
	if err != nil {
		progress.Done("")
		return fmt.Errorf("%s\n"+i18n.G("Try `lxc info --show-log %s` for more info"), err, nameArg)
	}

	progress.Done("")

	return nil
}

func (c *cmdAction) Run(cmd *cobra.Command, args []string) error {
	conf := c.global.conf

	var names []string
	if len(args) == 0 {
		if !c.flagAll {
			cmd.Help()
			return nil
		}

		d, err := conf.GetInstanceServer(conf.DefaultRemote)
		if err != nil {
			return err
		}

		ctslist, err := d.GetInstances(api.InstanceTypeAny)
		if err != nil {
			return err
		}

		for _, ct := range ctslist {
			switch cmd.Name() {
			case "start":
				if ct.StatusCode == api.Running {
					continue
				}
			case "stop":
				if ct.StatusCode == api.Stopped {
					continue
				}
			}
			names = append(names, ct.Name)
		}
	} else {
		if c.flagAll {
			return fmt.Errorf(i18n.G("Both --all and instance name given"))
		}
		names = args
	}

	// Run the action for every listed instance
	results := runBatch(names, func(name string) error { return c.doAction(cmd.Name(), conf, name) })

	// Single instance is easy
	if len(results) == 1 {
		return results[0].err
	}

	// Do fancier rendering for batches
	success := true

	for _, result := range results {
		if result.err == nil {
			continue
		}

		success = false
		msg := fmt.Sprintf(i18n.G("error: %v"), result.err)
		for _, line := range strings.Split(msg, "\n") {
			fmt.Fprintln(os.Stderr, fmt.Sprintf("%s: %s", result.name, line))
		}
	}

	if !success {
		fmt.Fprintln(os.Stderr, "")
		return fmt.Errorf(i18n.G("Some instances failed to %s"), cmd.Name())
	}

	return nil
}
<|endoftext|>


<commit_before>/*
Package primesum calcualtes prime numbers using a Sieve of Eratosthenes below
a limit, and returns their sum.
21 November 2014

Problem:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Solution:

This was remarkably similar to Problem 7, so I decided to reimplement how I answered
the question.

I based my initial solution on a concurrent prime number sieve that Rob Pike mentioned
during a talk on Go Concurrency Patterns at Google I/O 2012. It daisy-chains prime
numbers such that every number emitted from the chain is prime, and it then becomes a
filter. The solution worked, but unfortunately was too slow (~15 minutes) because the
base emitter had no knowledge of discovered primes.

Thus, I rewrote the search algorithm to use a Sieve of Eratosthenes. This algorithm’s
speed surprised me - it calculated the sum of all primes below 2,000,000 in 250ms. The
primary data structure is a slice of booleans.
*/
package primesieve

// Calculate finds the prime numbers below the limit, exclusive, and returns the sum
func Calculate(lim int) (sum int64) {
	// False means prime at output
	sieve := make([]bool, lim)

	// Not a prime
	sieve[0] = true
	sieve[1] = true

	prime := 2
	for {
		sum += int64(prime)
		// Get rid of multiples of prime
		for i := prime; i < lim; i = i + prime {
			if i%prime == 0 {
				sieve[i] = true
			}
		}

		// Find next prime
		for {
			prime++
			if prime == lim {
				return
			}
			if !sieve[prime] {
				// found next prime
				break
			}
		}
	}
}
<commit_msg>fix package naming<commit_after>/*
Package primesieve calcualtes prime numbers using a Sieve of Eratosthenes below
a limit, and returns their sum.
21 November 2014

Problem:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Solution:

This was remarkably similar to Problem 7, so I decided to reimplement how I answered
the question.

I based my initial solution on a concurrent prime number sieve that Rob Pike mentioned
during a talk on Go Concurrency Patterns at Google I/O 2012. It daisy-chains prime
numbers such that every number emitted from the chain is prime, and it then becomes a
filter. The solution worked, but unfortunately was too slow (~15 minutes) because the
base emitter had no knowledge of discovered primes.

Thus, I rewrote the search algorithm to use a Sieve of Eratosthenes. This algorithm’s
speed surprised me - it calculated the sum of all primes below 2,000,000 in 250ms. The
primary data structure is a slice of booleans.
*/
package primesieve

// Calculate finds the prime numbers below the limit, exclusive, and returns the sum
func Calculate(lim int) (sum int64) {
	// False means prime at output
	sieve := make([]bool, lim)

	// Not a prime
	sieve[0] = true
	sieve[1] = true

	prime := 2
	for {
		sum += int64(prime)
		// Get rid of multiples of prime
		for i := prime; i < lim; i = i + prime {
			if i%prime == 0 {
				sieve[i] = true
			}
		}

		// Find next prime
		for {
			prime++
			if prime == lim {
				return
			}
			if !sieve[prime] {
				// found next prime
				break
			}
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	log "github.com/sirupsen/logrus"
	"github.com/yuin/gopher-lua"
)

func exportBasicSystemFunctions(L *lua.LState) {

	// Return the version string
	L.SetGlobal("version", L.NewFunction(func(L *lua.LState) int {
		L.Push(lua.LString(versionString))
		return 1 // number of results
	}))

	// Log text with the "Info" log type
	L.SetGlobal("log", L.NewFunction(func(L *lua.LState) int {
		buf := arguments2buffer(L, false)
		// Log the combined text
		log.Info(buf.String())
		return 0 // number of results
	}))

	// Log text with the "Warn" log type
	L.SetGlobal("warn", L.NewFunction(func(L *lua.LState) int {
		buf := arguments2buffer(L, false)
		// Log the combined text
		log.Warn(buf.String())
		return 0 // number of results
	}))

	// Log text with the "Error" log type
	L.SetGlobal("err", L.NewFunction(func(L *lua.LState) int {
		buf := arguments2buffer(L, false)
		// Log the combined text
		log.Error(buf.String())
		return 0 // number of results
	}))

	// Sleep for the given number of seconds (can be a float)
	L.SetGlobal("sleep", L.NewFunction(func(L *lua.LState) int {
		// Extract the correct number of nanoseconds
		duration := time.Duration(float64(L.ToNumber(1)) * 1000000000.0)
		// Wait and block the current thread of execution.
		time.Sleep(duration)
		return 0
	}))

}

// Make functions related to HTTP requests and responses available to Lua scripts.
// Filename can be an empty string.
// realW is only used for flushing the buffer in debug mode, and is the underlying ResponseWriter.
func exportBasicWeb(w http.ResponseWriter, req *http.Request, L *lua.LState, filename string, flushFunc func()) {

	// Print text to the webpage that is being served. Add a newline.
	L.SetGlobal("print", L.NewFunction(func(L *lua.LState) int {
		var buf bytes.Buffer
		top := L.GetTop()
		for i := 1; i <= top; i++ {
			buf.WriteString(L.Get(i).String())
			if i != top {
				buf.WriteString("\t")
			}
		}
		// Final newline
		buf.WriteString("\n")

		// Write the combined text to the http.ResponseWriter
		w.Write(buf.Bytes())

		return 0 // number of results
	}))

	// Flush the ResponseWriter.
	// Needed in debug mode, where ResponseWriter is buffered.
	L.SetGlobal("flush", L.NewFunction(func(L *lua.LState) int {
		if flushFunc != nil {
			flushFunc()
		}
		return 0 // number of results
	}))

	// Set the Content-Type for the page
	L.SetGlobal("content", L.NewFunction(func(L *lua.LState) int {
		lv := L.ToString(1)
		w.Header().Add("Content-Type", lv)
		return 0 // number of results
	}))

	// Return the current URL Path
	L.SetGlobal("urlpath", L.NewFunction(func(L *lua.LState) int {
		L.Push(lua.LString(req.URL.Path))
		return 1 // number of results
	}))

	// Return the current HTTP method (GET, POST etc)
	L.SetGlobal("method", L.NewFunction(func(L *lua.LState) int {
		L.Push(lua.LString(req.Method))
		return 1 // number of results
	}))

	// Return the HTTP headers as a table
	L.SetGlobal("headers", L.NewFunction(func(L *lua.LState) int {
		luaTable := L.NewTable()
		for key := range req.Header {
			L.RawSet(luaTable, lua.LString(key), lua.LString(req.Header.Get(key)))
		}
		L.Push(luaTable)
		return 1 // number of results
	}))

	// Return the HTTP header in the request, for a given key/string
	L.SetGlobal("header", L.NewFunction(func(L *lua.LState) int {
		key := L.ToString(1)
		value := req.Header.Get(key)
		L.Push(lua.LString(value))
		return 1 // number of results
	}))

	// Set the HTTP header in the request, for a given key and value
	L.SetGlobal("setheader", L.NewFunction(func(L *lua.LState) int {
		key := L.ToString(1)
		value := L.ToString(2)
		w.Header().Set(key, value)
		return 0 // number of results
	}))

	// Return the HTTP body in the request
	L.SetGlobal("body", L.NewFunction(func(L *lua.LState) int {
		body, err := ioutil.ReadAll(req.Body)
		var result lua.LString
		if err != nil {
			result = lua.LString("")
		} else {
			result = lua.LString(string(body))
		}
		L.Push(result)
		return 1 // number of results
	}))

	// Set the HTTP status code (must come before print)
	L.SetGlobal("status", L.NewFunction(func(L *lua.LState) int {
		code := int(L.ToNumber(1))
		w.WriteHeader(code)
		return 0 // number of results
	}))

	// Set a HTTP status code and print a message (optional)
	L.SetGlobal("error", L.NewFunction(func(L *lua.LState) int {
		code := int(L.ToNumber(1))
		w.WriteHeader(code)
		if L.GetTop() == 2 {
			message := L.ToString(2)
			fmt.Fprint(w, message)
		}
		return 0 // number of results
	}))

	// Get the full filename of a given file that is in the directory
	// of the script that is about to be run. If no filename is given,
	// the directory of the script is returned.
	L.SetGlobal("scriptdir", L.NewFunction(func(L *lua.LState) int {
		scriptpath, err := filepath.Abs(filename)
		if err != nil {
			scriptpath = filename
		}
		scriptdir := filepath.Dir(scriptpath)
		scriptpath = scriptdir
		top := L.GetTop()
		if top == 1 {
			// Also include a separator and a filename
			fn := L.ToString(1)
			scriptpath = filepath.Join(scriptdir, fn)
		}
		// Now have the correct absolute scriptpath
		L.Push(lua.LString(scriptpath))
		return 1 // number of results
	}))

	// Given a filename, return the URL path
	L.SetGlobal("file2url", L.NewFunction(func(L *lua.LState) int {
		fn := L.ToString(1)
		targetpath := filepath.Join(filepath.Dir(filename), fn)
		if strings.HasPrefix(targetpath, serverDir) {
			targetpath = targetpath[len(serverDir):]
		}
		if pathsep != "/" {
			// For operating systems that use another path separator for files than for URLs
			targetpath = strings.Replace(targetpath, pathsep, "/", everyInstance)
		}
		withSlashPrefix := path.Join("/", targetpath)
		L.Push(lua.LString(withSlashPrefix))
		return 1 // number of results
	}))

	// Get the full filename of a given file that is in the directory
	// where the server is running (root directory for the server).
	// If no filename is given, the directory where the server is
	// currently running is returned.
	L.SetGlobal("serverdir", L.NewFunction(func(L *lua.LState) int {
		serverdir, err := os.Getwd()
		if err != nil {
			// Could not retrieve a directory
			serverdir = ""
		} else if L.GetTop() == 1 {
			// Also include a separator and a filename
			fn := L.ToString(1)
			serverdir = filepath.Join(serverdir, fn)
		}
		L.Push(lua.LString(serverdir))
		return 1 // number of results
	}))

	// Retrieve a table with keys and values from the form in the request
	L.SetGlobal("formdata", L.NewFunction(func(L *lua.LState) int {
		// Place the form data in a map
		m := make(map[string]string)
		req.ParseForm()
		for k, v := range req.Form {
			m[k] = v[0]
		}
		// Convert the map to a table and return it
		L.Push(map2table(L, m))
		return 1 // number of results
	}))

	// Redirect a request
	L.SetGlobal("redirect", L.NewFunction(func(L *lua.LState) int {
		newurl := L.ToString(1)
		http.Redirect(w, req, newurl, http.StatusMovedPermanently)
		return 0 // number of results
	}))

}
<commit_msg>Add two functions, unixnano and markdown<commit_after>package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"github.com/russross/blackfriday"
	log "github.com/sirupsen/logrus"
	"github.com/yuin/gopher-lua"
)

func exportBasicSystemFunctions(L *lua.LState) {

	// Return the version string
	L.SetGlobal("version", L.NewFunction(func(L *lua.LState) int {
		L.Push(lua.LString(versionString))
		return 1 // number of results
	}))

	// Log text with the "Info" log type
	L.SetGlobal("log", L.NewFunction(func(L *lua.LState) int {
		buf := arguments2buffer(L, false)
		// Log the combined text
		log.Info(buf.String())
		return 0 // number of results
	}))

	// Log text with the "Warn" log type
	L.SetGlobal("warn", L.NewFunction(func(L *lua.LState) int {
		buf := arguments2buffer(L, false)
		// Log the combined text
		log.Warn(buf.String())
		return 0 // number of results
	}))

	// Log text with the "Error" log type
	L.SetGlobal("err", L.NewFunction(func(L *lua.LState) int {
		buf := arguments2buffer(L, false)
		// Log the combined text
		log.Error(buf.String())
		return 0 // number of results
	}))

	// Sleep for the given number of seconds (can be a float)
	L.SetGlobal("sleep", L.NewFunction(func(L *lua.LState) int {
		// Extract the correct number of nanoseconds
		duration := time.Duration(float64(L.ToNumber(1)) * 1000000000.0)
		// Wait and block the current thread of execution.
		time.Sleep(duration)
		return 0
	}))

	// Convert Markdown to HTML
	L.SetGlobal("markdown", L.NewFunction(func(L *lua.LState) int {
		// Retrieve all the function arguments as a bytes.Buffer
		buf := arguments2buffer(L, true)
		// Convert the buffer to markdown and output the translated string
		html := strings.TrimSpace(string(blackfriday.MarkdownCommon([]byte(buf.String()))))
		L.Push(lua.LString(html))
		return 1 // number of results
	}))

	// Return the current unixtime, with an attempt at nanosecond resolution
	L.SetGlobal("unixnano", L.NewFunction(func(L *lua.LState) int {
		// Extract the correct number of nanoseconds
		L.Push(lua.LNumber(time.Now().UnixNano()))
		return 1 // number of results
	}))

}

// Make functions related to HTTP requests and responses available to Lua scripts.
// Filename can be an empty string.
// realW is only used for flushing the buffer in debug mode, and is the underlying ResponseWriter.
func exportBasicWeb(w http.ResponseWriter, req *http.Request, L *lua.LState, filename string, flushFunc func()) {

	// Print text to the webpage that is being served. Add a newline.
	L.SetGlobal("print", L.NewFunction(func(L *lua.LState) int {
		var buf bytes.Buffer
		top := L.GetTop()
		for i := 1; i <= top; i++ {
			buf.WriteString(L.Get(i).String())
			if i != top {
				buf.WriteString("\t")
			}
		}
		// Final newline
		buf.WriteString("\n")

		// Write the combined text to the http.ResponseWriter
		w.Write(buf.Bytes())

		return 0 // number of results
	}))

	// Flush the ResponseWriter.
	// Needed in debug mode, where ResponseWriter is buffered.
	L.SetGlobal("flush", L.NewFunction(func(L *lua.LState) int {
		if flushFunc != nil {
			flushFunc()
		}
		return 0 // number of results
	}))

	// Set the Content-Type for the page
	L.SetGlobal("content", L.NewFunction(func(L *lua.LState) int {
		lv := L.ToString(1)
		w.Header().Add("Content-Type", lv)
		return 0 // number of results
	}))

	// Return the current URL Path
	L.SetGlobal("urlpath", L.NewFunction(func(L *lua.LState) int {
		L.Push(lua.LString(req.URL.Path))
		return 1 // number of results
	}))

	// Return the current HTTP method (GET, POST etc)
	L.SetGlobal("method", L.NewFunction(func(L *lua.LState) int {
		L.Push(lua.LString(req.Method))
		return 1 // number of results
	}))

	// Return the HTTP headers as a table
	L.SetGlobal("headers", L.NewFunction(func(L *lua.LState) int {
		luaTable := L.NewTable()
		for key := range req.Header {
			L.RawSet(luaTable, lua.LString(key), lua.LString(req.Header.Get(key)))
		}
		L.Push(luaTable)
		return 1 // number of results
	}))

	// Return the HTTP header in the request, for a given key/string
	L.SetGlobal("header", L.NewFunction(func(L *lua.LState) int {
		key := L.ToString(1)
		value := req.Header.Get(key)
		L.Push(lua.LString(value))
		return 1 // number of results
	}))

	// Set the HTTP header in the request, for a given key and value
	L.SetGlobal("setheader", L.NewFunction(func(L *lua.LState) int {
		key := L.ToString(1)
		value := L.ToString(2)
		w.Header().Set(key, value)
		return 0 // number of results
	}))

	// Return the HTTP body in the request
	L.SetGlobal("body", L.NewFunction(func(L *lua.LState) int {
		body, err := ioutil.ReadAll(req.Body)
		var result lua.LString
		if err != nil {
			result = lua.LString("")
		} else {
			result = lua.LString(string(body))
		}
		L.Push(result)
		return 1 // number of results
	}))

	// Set the HTTP status code (must come before print)
	L.SetGlobal("status", L.NewFunction(func(L *lua.LState) int {
		code := int(L.ToNumber(1))
		w.WriteHeader(code)
		return 0 // number of results
	}))

	// Set a HTTP status code and print a message (optional)
	L.SetGlobal("error", L.NewFunction(func(L *lua.LState) int {
		code := int(L.ToNumber(1))
		w.WriteHeader(code)
		if L.GetTop() == 2 {
			message := L.ToString(2)
			fmt.Fprint(w, message)
		}
		return 0 // number of results
	}))

	// Get the full filename of a given file that is in the directory
	// of the script that is about to be run. If no filename is given,
	// the directory of the script is returned.
	L.SetGlobal("scriptdir", L.NewFunction(func(L *lua.LState) int {
		scriptpath, err := filepath.Abs(filename)
		if err != nil {
			scriptpath = filename
		}
		scriptdir := filepath.Dir(scriptpath)
		scriptpath = scriptdir
		top := L.GetTop()
		if top == 1 {
			// Also include a separator and a filename
			fn := L.ToString(1)
			scriptpath = filepath.Join(scriptdir, fn)
		}
		// Now have the correct absolute scriptpath
		L.Push(lua.LString(scriptpath))
		return 1 // number of results
	}))

	// Given a filename, return the URL path
	L.SetGlobal("file2url", L.NewFunction(func(L *lua.LState) int {
		fn := L.ToString(1)
		targetpath := filepath.Join(filepath.Dir(filename), fn)
		if strings.HasPrefix(targetpath, serverDir) {
			targetpath = targetpath[len(serverDir):]
		}
		if pathsep != "/" {
			// For operating systems that use another path separator for files than for URLs
			targetpath = strings.Replace(targetpath, pathsep, "/", everyInstance)
		}
		withSlashPrefix := path.Join("/", targetpath)
		L.Push(lua.LString(withSlashPrefix))
		return 1 // number of results
	}))

	// Get the full filename of a given file that is in the directory
	// where the server is running (root directory for the server).
	// If no filename is given, the directory where the server is
	// currently running is returned.
	L.SetGlobal("serverdir", L.NewFunction(func(L *lua.LState) int {
		serverdir, err := os.Getwd()
		if err != nil {
			// Could not retrieve a directory
			serverdir = ""
		} else if L.GetTop() == 1 {
			// Also include a separator and a filename
			fn := L.ToString(1)
			serverdir = filepath.Join(serverdir, fn)
		}
		L.Push(lua.LString(serverdir))
		return 1 // number of results
	}))

	// Retrieve a table with keys and values from the form in the request
	L.SetGlobal("formdata", L.NewFunction(func(L *lua.LState) int {
		// Place the form data in a map
		m := make(map[string]string)
		req.ParseForm()
		for k, v := range req.Form {
			m[k] = v[0]
		}
		// Convert the map to a table and return it
		L.Push(map2table(L, m))
		return 1 // number of results
	}))

	// Redirect a request
	L.SetGlobal("redirect", L.NewFunction(func(L *lua.LState) int {
		newurl := L.ToString(1)
		http.Redirect(w, req, newurl, http.StatusMovedPermanently)
		return 0 // number of results
	}))

}
<|endoftext|>


<commit_before>package render

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

//const from https://github.com/unrolled/render/blob/v1/render.go
const (
	// ContentBinary header value for binary data.
	ContentBinary = "application/octet-stream"
	// ContentHTML header value for HTML data.
	ContentHTML = "text/html"
	// ContentJSON header value for JSON data.
	ContentJSON = "application/json"
	// ContentJSONP header value for JSONP data.
	ContentJSONP = "application/javascript"
	// ContentLength header constant.
	ContentLength = "Content-Length"
	// ContentText header value for Text data.
	ContentText = "text/plain"
	// ContentType header constant.
	ContentType = "Content-Type"
	// ContentXHTML header value for XHTML data.
	ContentXHTML = "application/xhtml+xml"
	// ContentXML header value for XML data.
	ContentXML = "text/xml"
	// Default character encoding.
	defaultCharset = "UTF-8"
)

//ErrTooManyViewFiles error rasied when too many view files is given.
//raised by render engine.
var ErrTooManyViewFiles = errors.New("error too many view files")

//WriteJSON write json data to response.
//Return bytes length wrote and any error if raised.
func WriteJSON(w http.ResponseWriter, data []byte, status int) (int, error) {
	w.Header().Set(ContentType, ContentJSON)
	w.WriteHeader(status)
	return w.Write(data)
}

//MustWriteJSON write json data to response.
//Return bytes length wrote.
//Panic if any error raised.
func MustWriteJSON(w http.ResponseWriter, data []byte, status int) int {
	result, err := WriteJSON(w, data, status)
	if err != nil {
		panic(err)
	}
	return result
}

//WriteHTML write html data to response.
//Return bytes length wrote and any error if raised.
func WriteHTML(w http.ResponseWriter, data []byte, status int) (int, error) {
	w.Header().Set(ContentType, ContentHTML)
	w.WriteHeader(status)
	return w.Write(data)
}

//MustWriteHTML write html data to response.
//Return bytes length wrote.
//Panic if any error raised.
func MustWriteHTML(w http.ResponseWriter, data []byte, status int) int {
	result, err := WriteHTML(w, data, status)
	if err != nil {
		panic(err)
	}
	return result
}

//HTMLFile write content of given file to response as html.
//Return bytes length wrote and any error if raised.
func HTMLFile(w http.ResponseWriter, path string, status int) (int, error) {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		return 0, err
	}
	return WriteHTML(w, bytes, status)
}

//MustHTMLFile write content of given file to response as html.
//Return bytes length wrote.
//Panic if any error raised.
func MustHTMLFile(w http.ResponseWriter, path string, status int) int {
	result, err := HTMLFile(w, path, status)
	if err != nil {
		panic(err)
	}
	return result
}

//JSON marshal data as json and write to response
//Return bytes length wrote and any error if raised.
func JSON(w http.ResponseWriter, data interface{}, status int) (int, error) {
	bytes, err := json.Marshal(data)
	if err != nil {
		return 0, err
	}
	return WriteJSON(w, bytes, status)
}

//MustJSON marshal data as json and write to response
//Return bytes length wrote.
//Panic if any error raised.
func MustJSON(w http.ResponseWriter, data interface{}, status int) int {
	result, err := JSON(w, data, status)
	if err != nil {
		panic(err)
	}
	return result
}

//Error write a http error to response
//Return bytes length wrote.
//Panic if any error raised.
func Error(w http.ResponseWriter, status int) (int, error) {
	w.Header().Set(ContentType, ContentText)
	w.WriteHeader(status)
	return w.Write([]byte(http.StatusText(status)))
}

//MustError write a http error to response
//Return bytes length wrote.
//Panic if any error raised.
func MustError(w http.ResponseWriter, status int) int {
	result, err := Error(w, status)
	if err != nil {
		panic(err)
	}
	return result
}
<commit_msg>update<commit_after>package render

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

//const from https://github.com/unrolled/render/blob/v1/render.go
const (
	// ContentBinary header value for binary data.
	ContentBinary = "application/octet-stream"
	// ContentHTML header value for HTML data.
	ContentHTML = "text/html"
	// ContentJSON header value for JSON data.
	ContentJSON = "application/json"
	// ContentJSONP header value for JSONP data.
	ContentJSONP = "application/javascript"
	// ContentLength header constant.
	ContentLength = "Content-Length"
	// ContentText header value for Text data.
	ContentText = "text/plain"
	// ContentType header constant.
	ContentType = "Content-Type"
	// ContentXHTML header value for XHTML data.
	ContentXHTML = "application/xhtml+xml"
	// ContentXML header value for XML data.
	ContentXML = "text/xml"
	// Default character encoding.
	defaultCharset = "UTF-8"
)

//ErrTooManyViewFiles error rasied when too many view files is given.
//raised by render engine.
var ErrTooManyViewFiles = errors.New("error too many view files")

//WriteJSON write json data to response.
//Return bytes length wrote and any error if raised.
func WriteJSON(w http.ResponseWriter, data []byte, status int) (int, error) {
	w.Header().Set(ContentType, ContentJSON)
	w.WriteHeader(status)
	return w.Write(data)
}

//MustWriteJSON write json data to response.
//Return bytes length wrote.
//Panic if any error raised.
func MustWriteJSON(w http.ResponseWriter, data []byte, status int) int {
	result, err := WriteJSON(w, data, status)
	if err != nil {
		panic(err)
	}
	return result
}

//WriteHTML write html data to response.
//Return bytes length wrote and any error if raised.
func WriteHTML(w http.ResponseWriter, data []byte, status int) (int, error) {
	w.Header().Set(ContentType, ContentHTML)
	w.WriteHeader(status)
	return w.Write(data)
}

//MustWriteHTML write html data to response.
//Return bytes length wrote.
//Panic if any error raised.
func MustWriteHTML(w http.ResponseWriter, data []byte, status int) int {
	result, err := WriteHTML(w, data, status)
	if err != nil {
		panic(err)
	}
	return result
}

//HTMLFile write content of given file to response as html.
//Return bytes length wrote and any error if raised.
func HTMLFile(w http.ResponseWriter, path string, status int) (int, error) {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		return 0, err
	}
	return WriteHTML(w, bytes, status)
}

//MustHTMLFile write content of given file to response as html.
//Return bytes length wrote.
//Panic if any error raised.
func MustHTMLFile(w http.ResponseWriter, path string, status int) int {
	result, err := HTMLFile(w, path, status)
	if err != nil {
		panic(err)
	}
	return result
}

//JSON marshal data as json and write to response
//Return bytes length wrote and any error if raised.
func JSON(w http.ResponseWriter, data interface{}, status int) (int, error) {
	bytes, err := json.Marshal(data)
	if err != nil {
		return 0, err
	}
	return WriteJSON(w, bytes, status)
}

//MustJSON marshal data as json and write to response
//Return bytes length wrote.
//Panic if any error raised.
func MustJSON(w http.ResponseWriter, data interface{}, status int) int {
	result, err := JSON(w, data, status)
	if err != nil {
		panic(err)
	}
	return result
}

//Error write a http error to response
//Return bytes length wrote.
//Panic if any error raised.
func Error(w http.ResponseWriter, status int) (int, error) {
	w.Header().Set(ContentType, ContentText)
	w.WriteHeader(status)
	return w.Write([]byte(http.StatusText(status)))
}

//MustError write a http error to response
//Return bytes length wrote.
//Panic if any error raised.
func MustError(w http.ResponseWriter, status int) int {
	result, err := Error(w, status)
	if err != nil {
		panic(err)
	}
	return result
}

//JSONResponse create a json response with give data and status code
func JSONResponse(data interface{}, status int) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		MustJSON(w, data, status)
	}
}

//HTMLResponse create a html response with give data and status code
func HTMLResponse(data string, status int) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		MustWriteHTML(w, []byte(data), status)
	}
}
<|endoftext|>


<commit_before>package main

func match(p Program, q Program) bool {
	if len(p) != len(q) {
		return false
	}
	for i := range p {
		if p[i].Op != q[i].Op {
			return false
		}
		if q[i].Arg != 0 && p[i].Arg != q[i].Arg {
			return false
		}
	}
	return true
}

func loops(p Program) Program {
	var o Program
	for _, cmd := range p {
		switch cmd.Op {
		case BNZ:
			switch b := cmd.Branch; {
			// [-] or [+]
			case match(b, Program{Command{Op: Add}}):
				o = append(o, Command{Op: Clear})
			// [>] or [<]
			case match(b, Program{Command{Op: Move}}):
				o = append(o, Command{Op: Search, Arg: b[0].Arg})
			// [->+<]
			case len(b) == 4 && match(b, Program{
				Command{Op: Add, Arg: -1},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[1].Arg}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[1].Arg,
					Arg: b[2].Arg,
				})
				o = append(o, Command{Op: Clear})
			// [>+<-]
			case len(b) == 4 && match(b, Program{
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[0].Arg},
				Command{Op: Add, Arg: -1}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[0].Arg,
					Arg: b[1].Arg,
				})
				o = append(o, Command{Op: Clear})
			// [->+>+<<] or [->>+<+<]
			case len(b) == 6 && match(b, Program{
				Command{Op: Add, Arg: -1},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[1].Arg - b[3].Arg}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[1].Arg,
					Arg: b[2].Arg,
				})
				o = append(o, Command{
					Op:  Mult,
					Dst: b[1].Arg + b[3].Arg,
					Arg: b[4].Arg,
				})
				o = append(o, Command{Op: Clear})
			// [>+>+<<-] or [>>+<+<-]
			case len(b) == 6 && match(b, Program{
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[0].Arg - b[2].Arg},
				Command{Op: Add, Arg: -1}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[0].Arg,
					Arg: b[1].Arg,
				})
				o = append(o, Command{
					Op:  Mult,
					Dst: b[0].Arg + b[2].Arg,
					Arg: b[3].Arg,
				})
				o = append(o, Command{Op: Clear})
			default:
				o = append(o, Command{Op: BNZ, Branch: loops(b)})
			}
		default:
			// passthrough
			o = append(o, cmd)
		}
	}
	return o
}

func scan(p Program) (Command, int) {
	n := 1
	c := p[0]
	for _, cmd := range p[1:] {
		if cmd.Op == c.Op {
			c.Arg += cmd.Arg
			n++
		} else {
			break
		}
	}
	return c, n
}

func contract(p Program) Program {
	var o Program
	for i := 0; i < len(p); i++ {
		cmd := p[i]
		switch cmd.Op {
		case BNZ:
			cmd.Branch = contract(cmd.Branch)
		case Add, Move:
			var n int
			cmd, n = scan(p[i:])
			i += n - 1
		}
		o = append(o, cmd)
	}
	return o
}

func Optimize(p Program) Program {
	o := contract(p)
	return loops(o)
}
<commit_msg>Readd guards<commit_after>package main

func match(p Program, q Program) bool {
	if len(p) != len(q) {
		return false
	}
	for i := range p {
		if p[i].Op != q[i].Op {
			return false
		}
		if q[i].Arg != 0 && p[i].Arg != q[i].Arg {
			return false
		}
	}
	return true
}

func loops(p Program) Program {
	var o Program
	for _, cmd := range p {
		switch cmd.Op {
		case BNZ:
			switch b := cmd.Branch; {
			// [-] or [+]
			case len(b) == 1 && match(b, Program{Command{Op: Add}}):
				o = append(o, Command{Op: Clear})
			// [>] or [<]
			case len(b) == 1 && match(b, Program{Command{Op: Move}}):
				o = append(o, Command{Op: Search, Arg: b[0].Arg})
			// [->+<]
			case len(b) == 4 && match(b, Program{
				Command{Op: Add, Arg: -1},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[1].Arg}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[1].Arg,
					Arg: b[2].Arg,
				})
				o = append(o, Command{Op: Clear})
			// [>+<-]
			case len(b) == 4 && match(b, Program{
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[0].Arg},
				Command{Op: Add, Arg: -1}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[0].Arg,
					Arg: b[1].Arg,
				})
				o = append(o, Command{Op: Clear})
			// [->+>+<<] or [->>+<+<]
			case len(b) == 6 && match(b, Program{
				Command{Op: Add, Arg: -1},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[1].Arg - b[3].Arg}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[1].Arg,
					Arg: b[2].Arg,
				})
				o = append(o, Command{
					Op:  Mult,
					Dst: b[1].Arg + b[3].Arg,
					Arg: b[4].Arg,
				})
				o = append(o, Command{Op: Clear})
			// [>+>+<<-] or [>>+<+<-]
			case len(b) == 6 && match(b, Program{
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move},
				Command{Op: Add},
				Command{Op: Move, Arg: -b[0].Arg - b[2].Arg},
				Command{Op: Add, Arg: -1}}):
				o = append(o, Command{
					Op:  Mult,
					Dst: b[0].Arg,
					Arg: b[1].Arg,
				})
				o = append(o, Command{
					Op:  Mult,
					Dst: b[0].Arg + b[2].Arg,
					Arg: b[3].Arg,
				})
				o = append(o, Command{Op: Clear})
			default:
				o = append(o, Command{Op: BNZ, Branch: loops(b)})
			}
		default:
			// passthrough
			o = append(o, cmd)
		}
	}
	return o
}

func scan(p Program) (Command, int) {
	n := 1
	c := p[0]
	for _, cmd := range p[1:] {
		if cmd.Op == c.Op {
			c.Arg += cmd.Arg
			n++
		} else {
			break
		}
	}
	return c, n
}

func contract(p Program) Program {
	var o Program
	for i := 0; i < len(p); i++ {
		cmd := p[i]
		switch cmd.Op {
		case BNZ:
			cmd.Branch = contract(cmd.Branch)
		case Add, Move:
			var n int
			cmd, n = scan(p[i:])
			i += n - 1
		}
		o = append(o, cmd)
	}
	return o
}

func Optimize(p Program) Program {
	o := contract(p)
	return loops(o)
}
<|endoftext|>


<commit_before>//	Radix -- Asynchronous Redis client for Go.
//
// Simple client for accessing the Redis database. After establishing a connection
// with NewRedisDatabase() commands can be executed with Command(). So every command
// is possible. The method returns a ResultSet with different methods for success
// testing and access to the retrieved values. The method MultiCommand() can be used
// for transactions. The passed function gets a MultiCommand instance as argument for
// calling the inner Command() methods.
package redis
<commit_msg>another small godoc fix<commit_after>// Radix -- Asynchronous Redis client for Go.
//
// Simple client for accessing the Redis database. After establishing a connection
// with NewRedisDatabase() commands can be executed with Command(). So every command
// is possible. The method returns a ResultSet with different methods for success
// testing and access to the retrieved values. The method MultiCommand() can be used
// for transactions. The passed function gets a MultiCommand instance as argument for
// calling the inner Command() methods.
package redis
<|endoftext|>


<commit_before>package gomail_test

import (
	"fmt"
	"html/template"
	"io"
	"log"
	"time"

	"github.com/fjace05/gomail"
)

func Example() {
	m := gomail.NewMessage()
	m.SetHeader("From", "alex@example.com")
	m.SetHeader("To", "bob@example.com", "cora@example.com")
	m.SetAddressHeader("Cc", "dan@example.com", "Dan")
	m.SetHeader("Subject", "Hello!")
	m.SetBody("text/html", "Hello Bob and Cora!")
	m.Attach("/home/Alex/lolcat.jpg")

	d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")

	// Send the email to Bob, Cora and Dan.
	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

// A daemon that listens to a channel and sends all incoming messages.
func Example_daemon() {
	ch := make(chan *gomail.Message)

	go func() {
		d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")

		var s gomail.SendCloser
		var err error
		open := false
		for {
			select {
			case m, ok := <-ch:
				if !ok {
					return
				}
				if !open {
					if s, err = d.Dial(); err != nil {
						panic(err)
					}
					open = true
				}
				if err := gomail.Send(s, m); err != nil {
					/*
					If a message fails to send, the SMTP channel can be reset so additional messages
					can be attempted.
					 */
					s.Reset()
					log.Print(err)
				}
			// Close the connection to the SMTP server if no email was sent in
			// the last 30 seconds.
			case <-time.After(30 * time.Second):
				if open {
					if err := s.Close(); err != nil {
						panic(err)
					}
					open = false
				}
			}
		}
	}()

	// Use the channel in your program to send emails.

	// Close the channel to stop the mail daemon.
	close(ch)
}

// Efficiently send a customized newsletter to a list of recipients.
func Example_newsletter() {
	// The list of recipients.
	var list []struct {
		Name    string
		Address string
	}

	d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")
	s, err := d.Dial()
	if err != nil {
		panic(err)
	}

	m := gomail.NewMessage()
	for _, r := range list {
		m.SetHeader("From", "no-reply@example.com")
		m.SetAddressHeader("To", r.Address, r.Name)
		m.SetHeader("Subject", "Newsletter #1")
		m.SetBody("text/html", fmt.Sprintf("Hello %s!", r.Name))

		if err := gomail.Send(s, m); err != nil {
			log.Printf("Could not send email to %q: %v", r.Address, err)
		}
		m.Reset()
	}
}

// Send an email using a local SMTP server.
func Example_noAuth() {
	m := gomail.NewMessage()
	m.SetHeader("From", "from@example.com")
	m.SetHeader("To", "to@example.com")
	m.SetHeader("Subject", "Hello!")
	m.SetBody("text/plain", "Hello!")

	d := gomail.Dialer{Host: "localhost", Port: 587}
	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

// Send an email using an API or postfix.
func Example_noSMTP() {
	m := gomail.NewMessage()
	m.SetHeader("From", "from@example.com")
	m.SetHeader("To", "to@example.com")
	m.SetHeader("Subject", "Hello!")
	m.SetBody("text/plain", "Hello!")

	s := gomail.SendFunc(func(from string, to []string, msg io.WriterTo) error {
		// Implements you email-sending function, for example by calling
		// an API, or running postfix, etc.
		fmt.Println("From:", from)
		fmt.Println("To:", to)
		return nil
	})

	if err := gomail.Send(s, m); err != nil {
		panic(err)
	}
	// Output:
	// From: from@example.com
	// To: [to@example.com]
}

var m *gomail.Message

func ExampleSetCopyFunc() {
	m.Attach("foo.txt", gomail.SetCopyFunc(func(w io.Writer) error {
		_, err := w.Write([]byte("Content of foo.txt"))
		return err
	}))
}

func ExampleSetHeader() {
	h := map[string][]string{"Content-ID": {"<foo@bar.mail>"}}
	m.Attach("foo.jpg", gomail.SetHeader(h))
}

func ExampleRename() {
	m.Attach("/tmp/0000146.jpg", gomail.Rename("picture.jpg"))
}

func ExampleMessage_AddAlternative() {
	m.SetBody("text/plain", "Hello!")
	m.AddAlternative("text/html", "
Hello!
")
}

func ExampleMessage_AddAlternativeWriter() {
	t := template.Must(template.New("example").Parse("Hello {{.}}!"))
	m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
		return t.Execute(w, "Bob")
	})
}

func ExampleMessage_Attach() {
	m.Attach("/tmp/image.jpg")
}

func ExampleMessage_Embed() {
	m.Embed("/tmp/image.jpg")
	m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
}

func ExampleMessage_FormatAddress() {
	m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora"))
}

func ExampleMessage_FormatDate() {
	m.SetHeaders(map[string][]string{
		"X-Date": {m.FormatDate(time.Now())},
	})
}

func ExampleMessage_SetAddressHeader() {
	m.SetAddressHeader("To", "bob@example.com", "Bob")
}

func ExampleMessage_SetBody() {
	m.SetBody("text/plain", "Hello!")
}

func ExampleMessage_SetDateHeader() {
	m.SetDateHeader("X-Date", time.Now())
}

func ExampleMessage_SetHeader() {
	m.SetHeader("Subject", "Hello!")
}

func ExampleMessage_SetHeaders() {
	m.SetHeaders(map[string][]string{
		"From":    {m.FormatAddress("alex@example.com", "Alex")},
		"To":      {"bob@example.com", "cora@example.com"},
		"Subject": {"Hello"},
	})
}

func ExampleSetCharset() {
	m = gomail.NewMessage(gomail.SetCharset("ISO-8859-1"))
}

func ExampleSetEncoding() {
	m = gomail.NewMessage(gomail.SetEncoding(gomail.Base64))
}

func ExampleSetPartEncoding() {
	m.SetBody("text/plain", "Hello!", gomail.SetPartEncoding(gomail.Unencoded))
}
<commit_msg>Reverted example_test because of the versioned gomail import.<commit_after>package gomail_test

import (
	"fmt"
	"html/template"
	"io"
	"log"
	"time"

	"gopkg.in/gomail.v2"
)

func Example() {
	m := gomail.NewMessage()
	m.SetHeader("From", "alex@example.com")
	m.SetHeader("To", "bob@example.com", "cora@example.com")
	m.SetAddressHeader("Cc", "dan@example.com", "Dan")
	m.SetHeader("Subject", "Hello!")
	m.SetBody("text/html", "Hello Bob and Cora!")
	m.Attach("/home/Alex/lolcat.jpg")

	d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")

	// Send the email to Bob, Cora and Dan.
	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

// A daemon that listens to a channel and sends all incoming messages.
func Example_daemon() {
	ch := make(chan *gomail.Message)

	go func() {
		d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")

		var s gomail.SendCloser
		var err error
		open := false
		for {
			select {
			case m, ok := <-ch:
				if !ok {
					return
				}
				if !open {
					if s, err = d.Dial(); err != nil {
						panic(err)
					}
					open = true
				}
				if err := gomail.Send(s, m); err != nil {
					log.Print(err)
				}
			// Close the connection to the SMTP server if no email was sent in
			// the last 30 seconds.
			case <-time.After(30 * time.Second):
				if open {
					if err := s.Close(); err != nil {
						panic(err)
					}
					open = false
				}
			}
		}
	}()

	// Use the channel in your program to send emails.

	// Close the channel to stop the mail daemon.
	close(ch)
}

// Efficiently send a customized newsletter to a list of recipients.
func Example_newsletter() {
	// The list of recipients.
	var list []struct {
		Name    string
		Address string
	}

	d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")
	s, err := d.Dial()
	if err != nil {
		panic(err)
	}

	m := gomail.NewMessage()
	for _, r := range list {
		m.SetHeader("From", "no-reply@example.com")
		m.SetAddressHeader("To", r.Address, r.Name)
		m.SetHeader("Subject", "Newsletter #1")
		m.SetBody("text/html", fmt.Sprintf("Hello %s!", r.Name))

		if err := gomail.Send(s, m); err != nil {
			log.Printf("Could not send email to %q: %v", r.Address, err)
		}
		m.Reset()
	}
}

// Send an email using a local SMTP server.
func Example_noAuth() {
	m := gomail.NewMessage()
	m.SetHeader("From", "from@example.com")
	m.SetHeader("To", "to@example.com")
	m.SetHeader("Subject", "Hello!")
	m.SetBody("text/plain", "Hello!")

	d := gomail.Dialer{Host: "localhost", Port: 587}
	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

// Send an email using an API or postfix.
func Example_noSMTP() {
	m := gomail.NewMessage()
	m.SetHeader("From", "from@example.com")
	m.SetHeader("To", "to@example.com")
	m.SetHeader("Subject", "Hello!")
	m.SetBody("text/plain", "Hello!")

	s := gomail.SendFunc(func(from string, to []string, msg io.WriterTo) error {
		// Implements you email-sending function, for example by calling
		// an API, or running postfix, etc.
		fmt.Println("From:", from)
		fmt.Println("To:", to)
		return nil
	})

	if err := gomail.Send(s, m); err != nil {
		panic(err)
	}
	// Output:
	// From: from@example.com
	// To: [to@example.com]
}

var m *gomail.Message

func ExampleSetCopyFunc() {
	m.Attach("foo.txt", gomail.SetCopyFunc(func(w io.Writer) error {
		_, err := w.Write([]byte("Content of foo.txt"))
		return err
	}))
}

func ExampleSetHeader() {
	h := map[string][]string{"Content-ID": {"<foo@bar.mail>"}}
	m.Attach("foo.jpg", gomail.SetHeader(h))
}

func ExampleRename() {
	m.Attach("/tmp/0000146.jpg", gomail.Rename("picture.jpg"))
}

func ExampleMessage_AddAlternative() {
	m.SetBody("text/plain", "Hello!")
	m.AddAlternative("text/html", "
Hello!
")
}

func ExampleMessage_AddAlternativeWriter() {
	t := template.Must(template.New("example").Parse("Hello {{.}}!"))
	m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
		return t.Execute(w, "Bob")
	})
}

func ExampleMessage_Attach() {
	m.Attach("/tmp/image.jpg")
}

func ExampleMessage_Embed() {
	m.Embed("/tmp/image.jpg")
	m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
}

func ExampleMessage_FormatAddress() {
	m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora"))
}

func ExampleMessage_FormatDate() {
	m.SetHeaders(map[string][]string{
		"X-Date": {m.FormatDate(time.Now())},
	})
}

func ExampleMessage_SetAddressHeader() {
	m.SetAddressHeader("To", "bob@example.com", "Bob")
}

func ExampleMessage_SetBody() {
	m.SetBody("text/plain", "Hello!")
}

func ExampleMessage_SetDateHeader() {
	m.SetDateHeader("X-Date", time.Now())
}

func ExampleMessage_SetHeader() {
	m.SetHeader("Subject", "Hello!")
}

func ExampleMessage_SetHeaders() {
	m.SetHeaders(map[string][]string{
		"From":    {m.FormatAddress("alex@example.com", "Alex")},
		"To":      {"bob@example.com", "cora@example.com"},
		"Subject": {"Hello"},
	})
}

func ExampleSetCharset() {
	m = gomail.NewMessage(gomail.SetCharset("ISO-8859-1"))
}

func ExampleSetEncoding() {
	m = gomail.NewMessage(gomail.SetEncoding(gomail.Base64))
}

func ExampleSetPartEncoding() {
	m.SetBody("text/plain", "Hello!", gomail.SetPartEncoding(gomail.Unencoded))
}
<|endoftext|>


<commit_before>package machineid_test

import (
	"fmt"
	"log"

	"github.com/denisbrodbeck/machineid"
)

func Example() {
	id, err := machineid.ID()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(id)
}
<commit_msg>Add example for protected id.<commit_after>package machineid_test

import (
	"fmt"
	"log"

	"github.com/denisbrodbeck/machineid"
)

func Example() {
	id, err := machineid.ID()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(id)
}

func ExampleProtected() {
	appID := "Corp.SomeApp"
	id, err := machineid.ProtectedID(appID)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(id)
}
<|endoftext|>


<commit_before>package jsonptr_test

import (
	"encoding/json"
	"fmt"

	"github.com/dolmen-go/jsonptr"
)

// Example from https://tools.ietf.org/html/rfc6901#section-5
func Example() {
	const JSON = `
{
   "foo": ["bar", "baz"],
   "": 0,
   "a/b": 1,
   "c%d": 2,
   "e^f": 3,
   "g|h": 4,
   "i\\j": 5,
   "k\"l": 6,
   " ": 7,
   "m~n": 8
}`
	var doc interface{}
	_ = json.Unmarshal([]byte(JSON), &doc)

	for _, ptr := range []string{
		"/foo",
		"/foo/0",
		"/",
		"/a~1b",
		"/c%d",
		"/e^f",
		"/g|h",
		"/i\\j",
		"/k\"l",
		"/ ",
		"/m~0n",
	} {
		result, _ := jsonptr.Get(doc, ptr)
		fmt.Printf("%-12q %#v\n", ptr, result)
	}
	// Output:
	// "/foo"       []interface {}{"bar", "baz"}
	// "/foo/0"     "bar"
	// "/"          0
	// "/a~1b"      1
	// "/c%d"       2
	// "/e^f"       3
	// "/g|h"       4
	// "/i\\j"      5
	// "/k\"l"      6
	// "/ "         7
	// "/m~0n"      8
}
<commit_msg>Add example of building an object with Set()<commit_after>package jsonptr_test

import (
	"encoding/json"
	"fmt"

	"github.com/dolmen-go/jsonptr"
)

// Example from https://tools.ietf.org/html/rfc6901#section-5
func Example() {
	const JSON = `
{
   "foo": ["bar", "baz"],
   "": 0,
   "a/b": 1,
   "c%d": 2,
   "e^f": 3,
   "g|h": 4,
   "i\\j": 5,
   "k\"l": 6,
   " ": 7,
   "m~n": 8
}`
	var doc interface{}
	_ = json.Unmarshal([]byte(JSON), &doc)

	for _, ptr := range []string{
		"/foo",
		"/foo/0",
		"/",
		"/a~1b",
		"/c%d",
		"/e^f",
		"/g|h",
		"/i\\j",
		"/k\"l",
		"/ ",
		"/m~0n",
	} {
		result, _ := jsonptr.Get(doc, ptr)
		fmt.Printf("%-12q %#v\n", ptr, result)
	}
	// Output:
	// "/foo"       []interface {}{"bar", "baz"}
	// "/foo/0"     "bar"
	// "/"          0
	// "/a~1b"      1
	// "/c%d"       2
	// "/e^f"       3
	// "/g|h"       4
	// "/i\\j"      5
	// "/k\"l"      6
	// "/ "         7
	// "/m~0n"      8
}

func ExampleSet() {

	newArray := func() interface{} {
		return make([]interface{}, 0)
	}

	newObject := func() interface{} {
		return make(map[string]interface{})
	}

	var doc interface{}

	for _, step := range []struct {
		where string
		what  interface{}
	}{
		{"", newObject},
		{"/arr", newArray},
		{"/arr/-", 3},
		{"/arr/-", 2},
		{"/arr/-", 1},
		{"/obj", newObject},
		{"/obj/str", "hello"},
		{"/obj/bool", true},
		{"/arr/-", 0},
		{"/obj/", nil},
	} {
		what := step.what
		if f, isFunc := what.(func() interface{}); isFunc {
			what = f()
		}
		err := jsonptr.Set(&doc, step.where, what)
		if err != nil {
			panic(err)
		}
		//fmt.Printf("%#v\n", doc)
	}

	fmt.Println(func() string { x, _ := json.Marshal(doc); return string(x) }())
	// Output:
	// {"arr":[3,2,1,0],"obj":{"":null,"bool":true,"str":"hello"}}
}
<|endoftext|>


<commit_before>package message_test

import (
	"bytes"
	"io"
	"log"
	"strings"

	"github.com/emersion/go-message"
)

func ExampleRead() {
	// Let's assume r is an io.Reader that contains a message.
	var r io.Reader

	m, err := message.Read(r)
	if message.IsUnknownCharset(err) {
		// This error is not fatal
		log.Println("Unknown encoding:", err)
	} else if err != nil {
		log.Fatal(err)
	}

	if mr := m.MultipartReader(); mr != nil {
		// This is a multipart message
		log.Println("This is a multipart message containing:")
		for {
			p, err := mr.NextPart()
			if err == io.EOF {
				break
			} else if err != nil {
				log.Fatal(err)
			}

			t, _, _ := p.Header.ContentType()
			log.Println("A part with type", t)
		}
	} else {
		t, _, _ := m.Header.ContentType()
		log.Println("This is a non-multipart message with type", t)
	}
}

func ExampleWriter() {
	var b bytes.Buffer

	var h message.Header
	h.SetContentType("multipart/alternative", nil)
	w, err := message.CreateWriter(&b, h)
	if err != nil {
		log.Fatal(err)
	}

	var h1 message.Header
	h1.SetContentType("text/html", nil)
	w1, err := w.CreatePart(h1)
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w1, "
Hello World!

This is an HTML part.
")
	w1.Close()

	var h2 message.Header
	h1.SetContentType("text/plain", nil)
	w2, err := w.CreatePart(h2)
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w2, "Hello World!\n\nThis is a text part.")
	w2.Close()

	w.Close()

	log.Println(b.String())
}

func Example_transform() {
	// Let's assume r is an io.Reader that contains a message.
	var r io.Reader

	m, err := message.Read(r)
	if message.IsUnknownCharset(err) {
		log.Println("Unknown encoding:", err)
	} else if err != nil {
		log.Fatal(err)
	}

	// We'll add "This message is powered by Go" at the end of each text entity.
	poweredBy := "\n\nThis message is powered by Go."

	var b bytes.Buffer
	w, err := message.CreateWriter(&b, m.Header)
	if err != nil {
		log.Fatal(err)
	}

	// Define a function that transforms message.
	var transform func(w *message.Writer, e *message.Entity) error
	transform = func(w *message.Writer, e *message.Entity) error {
		if mr := e.MultipartReader(); mr != nil {
			// This is a multipart entity, transform each of its parts
			for {
				p, err := mr.NextPart()
				if err == io.EOF {
					break
				} else if err != nil {
					return err
				}

				pw, err := w.CreatePart(p.Header)
				if err != nil {
					return err
				}

				if err := transform(pw, p); err != nil {
					return err
				}

				pw.Close()
			}
			return nil
		} else {
			body := e.Body
			if strings.HasPrefix(m.Header.Get("Content-Type"), "text/") {
				body = io.MultiReader(body, strings.NewReader(poweredBy))
			}
			_, err := io.Copy(w, body)
			return err
		}
	}

	if err := transform(w, m); err != nil {
		log.Fatal(err)
	}
	w.Close()

	log.Println(b.String())
}
<commit_msg>Fixing wrong var in example_test.go<commit_after>package message_test

import (
	"bytes"
	"io"
	"log"
	"strings"

	"github.com/emersion/go-message"
)

func ExampleRead() {
	// Let's assume r is an io.Reader that contains a message.
	var r io.Reader

	m, err := message.Read(r)
	if message.IsUnknownCharset(err) {
		// This error is not fatal
		log.Println("Unknown encoding:", err)
	} else if err != nil {
		log.Fatal(err)
	}

	if mr := m.MultipartReader(); mr != nil {
		// This is a multipart message
		log.Println("This is a multipart message containing:")
		for {
			p, err := mr.NextPart()
			if err == io.EOF {
				break
			} else if err != nil {
				log.Fatal(err)
			}

			t, _, _ := p.Header.ContentType()
			log.Println("A part with type", t)
		}
	} else {
		t, _, _ := m.Header.ContentType()
		log.Println("This is a non-multipart message with type", t)
	}
}

func ExampleWriter() {
	var b bytes.Buffer

	var h message.Header
	h.SetContentType("multipart/alternative", nil)
	w, err := message.CreateWriter(&b, h)
	if err != nil {
		log.Fatal(err)
	}

	var h1 message.Header
	h1.SetContentType("text/html", nil)
	w1, err := w.CreatePart(h1)
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w1, "
Hello World!

This is an HTML part.
")
	w1.Close()

	var h2 message.Header
	h2.SetContentType("text/plain", nil)
	w2, err := w.CreatePart(h2)
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w2, "Hello World!\n\nThis is a text part.")
	w2.Close()

	w.Close()

	log.Println(b.String())
}

func Example_transform() {
	// Let's assume r is an io.Reader that contains a message.
	var r io.Reader

	m, err := message.Read(r)
	if message.IsUnknownCharset(err) {
		log.Println("Unknown encoding:", err)
	} else if err != nil {
		log.Fatal(err)
	}

	// We'll add "This message is powered by Go" at the end of each text entity.
	poweredBy := "\n\nThis message is powered by Go."

	var b bytes.Buffer
	w, err := message.CreateWriter(&b, m.Header)
	if err != nil {
		log.Fatal(err)
	}

	// Define a function that transforms message.
	var transform func(w *message.Writer, e *message.Entity) error
	transform = func(w *message.Writer, e *message.Entity) error {
		if mr := e.MultipartReader(); mr != nil {
			// This is a multipart entity, transform each of its parts
			for {
				p, err := mr.NextPart()
				if err == io.EOF {
					break
				} else if err != nil {
					return err
				}

				pw, err := w.CreatePart(p.Header)
				if err != nil {
					return err
				}

				if err := transform(pw, p); err != nil {
					return err
				}

				pw.Close()
			}
			return nil
		} else {
			body := e.Body
			if strings.HasPrefix(m.Header.Get("Content-Type"), "text/") {
				body = io.MultiReader(body, strings.NewReader(poweredBy))
			}
			_, err := io.Copy(w, body)
			return err
		}
	}

	if err := transform(w, m); err != nil {
		log.Fatal(err)
	}
	w.Close()

	log.Println(b.String())
}
<|endoftext|>