<commit_before>package main

import (
	"errors"
	"fmt"
	"github.com/gonuts/flag"
	"github.com/jbenet/commander"
	h "github.com/jbenet/go-ipfs/server/http"
)

var cmdIpfsServe = &commander.Command{
	UsageLine: "serve",
	Short:     "Serve an interface to ipfs",
	Subcommands: []*commander.Command{
		cmdIpfsServeHttp,
	},
	Flag: *flag.NewFlagSet("ipfs-serve", flag.ExitOnError),
}

var cmdIpfsServeHttp = &commander.Command{
	UsageLine: "http",
	Short:     "Serve an HTTP API",
	Long:      `ipfs serve http - Serve an http gateway into ipfs.`,
	Run:       serveHttpCmd,
	Flag:      *flag.NewFlagSet("ipfs-serve-http", flag.ExitOnError),
}

func init() {
	cmdIpfsServeHttp.Flag.Uint("port", 8080, "Port number")
	cmdIpfsServeHttp.Flag.String("hostname", "localhost", "Hostname")
}

func serveHttpCmd(c *commander.Command, _ []string) error {
	port := c.Flag.Lookup("port").Value.Get().(uint)
	if port < 1 || port > 65535 {
		return errors.New("invalid port number")
	}

	hostname := c.Flag.Lookup("hostname").Value.Get().(string)

	n, err := localNode()
	if err != nil {
		return err
	}

	address := fmt.Sprintf("%s:%d", hostname, port)
	fmt.Printf("Serving on %s\n", address)

	return h.Serve(address, n)
}
<commit_msg>daemon listener to http serve code<commit_after>package main

import (
	"errors"
	"fmt"

	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/gonuts/flag"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/commander"
	"github.com/jbenet/go-ipfs/daemon"
	h "github.com/jbenet/go-ipfs/server/http"
)

var cmdIpfsServe = &commander.Command{
	UsageLine: "serve",
	Short:     "Serve an interface to ipfs",
	Subcommands: []*commander.Command{
		cmdIpfsServeHttp,
	},
	Flag: *flag.NewFlagSet("ipfs-serve", flag.ExitOnError),
}

var cmdIpfsServeHttp = &commander.Command{
	UsageLine: "http",
	Short:     "Serve an HTTP API",
	Long:      `ipfs serve http - Serve an http gateway into ipfs.`,
	Run:       serveHttpCmd,
	Flag:      *flag.NewFlagSet("ipfs-serve-http", flag.ExitOnError),
}

func init() {
	cmdIpfsServeHttp.Flag.Uint("port", 8080, "Port number")
	cmdIpfsServeHttp.Flag.String("hostname", "localhost", "Hostname")
}

func serveHttpCmd(c *commander.Command, _ []string) error {
	port := c.Flag.Lookup("port").Value.Get().(uint)
	if port < 1 || port > 65535 {
		return errors.New("invalid port number")
	}

	n, err := localNode(true)
	if err != nil {
		return err
	}

	fmt.Println("starting new daemon listener...")
	dl, err := daemon.NewDaemonListener(n, "localhost:12345")
	if err != nil {
		return err
	}
	go dl.Listen()
	defer dl.Close()

	hostname := c.Flag.Lookup("hostname").Value.Get().(string)
	address := fmt.Sprintf("%s:%d", hostname, port)
	fmt.Printf("Serving on %s\n", address)

	return h.Serve(address, n)
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/base64"
	"errors"
	"os"
	"path/filepath"

	cmds "github.com/jbenet/go-ipfs/commands"
	config "github.com/jbenet/go-ipfs/config"
	ci "github.com/jbenet/go-ipfs/crypto"
	peer "github.com/jbenet/go-ipfs/peer"
	updates "github.com/jbenet/go-ipfs/updates"
	u "github.com/jbenet/go-ipfs/util"
)

var initCmd = &cmds.Command{
	Options: []cmds.Option{
		cmds.Option{[]string{"bits", "b"}, cmds.Int},
		cmds.Option{[]string{"passphrase", "p"}, cmds.String},
		cmds.Option{[]string{"force", "f"}, cmds.Bool},
		cmds.Option{[]string{"datastore", "d"}, cmds.String},
	},
	Help: `ipfs init

	Initializes ipfs configuration files and generates a
	new keypair.
	`,
	Run: func(res cmds.Response, req cmds.Request) {

		arg, found := req.Option("d")
		dspath, ok := arg.(string)
		if found && !ok {
			res.SetError(errors.New("failed to parse datastore flag"), cmds.ErrNormal)
			return
		}

		arg, found = req.Option("f")
		force, ok := arg.(bool) // TODO param
		if found && !ok {
			res.SetError(errors.New("failed to parse force flag"), cmds.ErrNormal)
			return
		}

		err := foo(res, req, dspath, force)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
	},
}

func foo(res cmds.Response, req cmds.Request, dspath string, force bool) error {
	ctx := req.Context()

	u.POut("initializing ipfs node at %s\n", ctx.ConfigRoot)
	filename, err := config.Filename(ctx.ConfigRoot)
	if err != nil {
		return errors.New("Couldn't get home directory path")
	}

	fi, err := os.Lstat(filename)
	if fi != nil || (err != nil && !os.IsNotExist(err)) {
		if !force {
			// TODO multi-line string
			return errors.New("ipfs configuration file already exists!\nReinitializing would overwrite your keys.\n(use -f to force overwrite)")
		}
	}
	cfg := new(config.Config)

	cfg.Datastore = config.Datastore{}
	if len(dspath) == 0 {
		dspath, err = config.DataStorePath("")
		if err != nil {
			return err
		}
	}
	cfg.Datastore.Path = dspath
	cfg.Datastore.Type = "leveldb"

	// Construct the data store if missing
	if err := os.MkdirAll(dspath, os.ModePerm); err != nil {
		return err
	}

	// Check the directory is writeable
	if f, err := os.Create(filepath.Join(dspath, "._check_writeable")); err == nil {
		os.Remove(f.Name())
	} else {
		return errors.New("Datastore '" + dspath + "' is not writeable")
	}

	cfg.Identity = config.Identity{}

	// setup the node addresses.
	cfg.Addresses = config.Addresses{
		Swarm: "/ip4/0.0.0.0/tcp/4001",
		API:   "/ip4/127.0.0.1/tcp/5001",
	}

	// setup the node mount points.
	cfg.Mounts = config.Mounts{
		IPFS: "/ipfs",
		IPNS: "/ipns",
	}

	arg, found = req.Option("b")
	nbits, ok := arg.(int) // TODO param
	if found && !ok {
		return errors.New("failed to get bits flag")
	} else if !found {
		nbits = 4096
	}
	if nbits < 1024 {
		return errors.New("Bitsize less than 1024 is considered unsafe.")
	}

	u.POut("generating key pair\n")
	sk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)
	if err != nil {
		return err
	}

	// currently storing key unencrypted. in the future we need to encrypt it.
	// TODO(security)
	skbytes, err := sk.Bytes()
	if err != nil {
		return err
	}
	cfg.Identity.PrivKey = base64.StdEncoding.EncodeToString(skbytes)

	id, err := peer.IDFromPubKey(pk)
	if err != nil {
		return err
	}
	cfg.Identity.PeerID = id.Pretty()

	// Use these hardcoded bootstrap peers for now.
	cfg.Bootstrap = []*config.BootstrapPeer{
		&config.BootstrapPeer{
			// mars.i.ipfs.io
			PeerID:  "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",
			Address: "/ip4/104.131.131.82/tcp/4001",
		},
	}

	// tracking ipfs version used to generate the init folder and adding update checker default setting.
	cfg.Version = config.Version{
		Check:   "error",
		Current: updates.Version,
	}

	err = config.WriteConfigFile(filename, cfg)
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>refactor(init) extract bits flag<commit_after>package main

import (
	"encoding/base64"
	"errors"
	"os"
	"path/filepath"

	cmds "github.com/jbenet/go-ipfs/commands"
	config "github.com/jbenet/go-ipfs/config"
	ci "github.com/jbenet/go-ipfs/crypto"
	peer "github.com/jbenet/go-ipfs/peer"
	updates "github.com/jbenet/go-ipfs/updates"
	u "github.com/jbenet/go-ipfs/util"
)

var initCmd = &cmds.Command{
	Options: []cmds.Option{
		cmds.Option{[]string{"bits", "b"}, cmds.Int},
		cmds.Option{[]string{"passphrase", "p"}, cmds.String},
		cmds.Option{[]string{"force", "f"}, cmds.Bool},
		cmds.Option{[]string{"datastore", "d"}, cmds.String},
	},
	Help: `ipfs init

	Initializes ipfs configuration files and generates a
	new keypair.
	`,
	Run: func(res cmds.Response, req cmds.Request) {

		arg, found := req.Option("d")
		dspath, ok := arg.(string)
		if found && !ok {
			res.SetError(errors.New("failed to parse datastore flag"), cmds.ErrNormal)
			return
		}

		arg, found = req.Option("f")
		force, ok := arg.(bool) // TODO param
		if found && !ok {
			res.SetError(errors.New("failed to parse force flag"), cmds.ErrNormal)
			return
		}

		arg, found = req.Option("b")
		nBitsForKeypair, ok := arg.(int) // TODO param
		if found && !ok {
			res.SetError(errors.New("failed to get bits flag"), cmds.ErrNormal)
			return
		} else if !found {
			nBitsForKeypair = 4096
		}

		err := foo(res, req, dspath, force, nBitsForKeypair)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
	},
}

func foo(res cmds.Response, req cmds.Request, dspath string, force bool, nBitsForKeypair int) error {
	ctx := req.Context()

	u.POut("initializing ipfs node at %s\n", ctx.ConfigRoot)
	filename, err := config.Filename(ctx.ConfigRoot)
	if err != nil {
		return errors.New("Couldn't get home directory path")
	}

	fi, err := os.Lstat(filename)
	if fi != nil || (err != nil && !os.IsNotExist(err)) {
		if !force {
			// TODO multi-line string
			return errors.New("ipfs configuration file already exists!\nReinitializing would overwrite your keys.\n(use -f to force overwrite)")
		}
	}
	cfg := new(config.Config)

	cfg.Datastore = config.Datastore{}
	if len(dspath) == 0 {
		dspath, err = config.DataStorePath("")
		if err != nil {
			return err
		}
	}
	cfg.Datastore.Path = dspath
	cfg.Datastore.Type = "leveldb"

	// Construct the data store if missing
	if err := os.MkdirAll(dspath, os.ModePerm); err != nil {
		return err
	}

	// Check the directory is writeable
	if f, err := os.Create(filepath.Join(dspath, "._check_writeable")); err == nil {
		os.Remove(f.Name())
	} else {
		return errors.New("Datastore '" + dspath + "' is not writeable")
	}

	cfg.Identity = config.Identity{}

	// setup the node addresses.
	cfg.Addresses = config.Addresses{
		Swarm: "/ip4/0.0.0.0/tcp/4001",
		API:   "/ip4/127.0.0.1/tcp/5001",
	}

	// setup the node mount points.
	cfg.Mounts = config.Mounts{
		IPFS: "/ipfs",
		IPNS: "/ipns",
	}

	// TODO guard
	if nBitsForKeypair < 1024 {
		return errors.New("Bitsize less than 1024 is considered unsafe.")
	}

	u.POut("generating key pair\n")
	sk, pk, err := ci.GenerateKeyPair(ci.RSA, nBitsForKeypair)
	if err != nil {
		return err
	}

	// currently storing key unencrypted. in the future we need to encrypt it.
	// TODO(security)
	skbytes, err := sk.Bytes()
	if err != nil {
		return err
	}
	cfg.Identity.PrivKey = base64.StdEncoding.EncodeToString(skbytes)

	id, err := peer.IDFromPubKey(pk)
	if err != nil {
		return err
	}
	cfg.Identity.PeerID = id.Pretty()

	// Use these hardcoded bootstrap peers for now.
	cfg.Bootstrap = []*config.BootstrapPeer{
		&config.BootstrapPeer{
			// mars.i.ipfs.io
			PeerID:  "QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",
			Address: "/ip4/104.131.131.82/tcp/4001",
		},
	}

	// tracking ipfs version used to generate the init folder and adding update checker default setting.
	cfg.Version = config.Version{
		Check:   "error",
		Current: updates.Version,
	}

	err = config.WriteConfigFile(filename, cfg)
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"os/signal"
	"runtime/pprof"

	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-logging"
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net"

	cmds "github.com/jbenet/go-ipfs/commands"
	cmdsCli "github.com/jbenet/go-ipfs/commands/cli"
	cmdsHttp "github.com/jbenet/go-ipfs/commands/http"
	"github.com/jbenet/go-ipfs/config"
	"github.com/jbenet/go-ipfs/core"
	commands "github.com/jbenet/go-ipfs/core/commands2"
	daemon "github.com/jbenet/go-ipfs/daemon2"
	u "github.com/jbenet/go-ipfs/util"
)

// log is the command logger
var log = u.Logger("cmd/ipfs")

const (
	cpuProfile  = "ipfs.cpuprof"
	heapProfile = "ipfs.memprof"
	errorFormat = "ERROR: %v\n\n"
)

func main() {
	err := run()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func run() error {
	handleInterrupt()

	args := os.Args[1:]
	req, root, err := createRequest(args)
	if err != nil {
		return err
	}

	debug, _, err := req.Option("debug").Bool()
	if err != nil {
		return err
	}
	if debug {
		u.Debug = true
		u.SetAllLoggers(logging.DEBUG)
	}

	if u.Debug {
		stopProfilingFunc, err := startProfiling()
		if err != nil {
			return err
		}
		defer stopProfilingFunc() // to be executed as late as possible
	}

	helpTextDisplayed, err := handleHelpOption(req, root)
	if err != nil {
		return err
	}
	if helpTextDisplayed {
		return nil
	}

	res, err := callCommand(req, root)
	if err != nil {
		return err
	}

	err = outputResponse(res, root)
	if err != nil {
		return err
	}

	return nil
}

func createRequest(args []string) (cmds.Request, *cmds.Command, error) {
	req, root, cmd, path, err := cmdsCli.Parse(args, Root, commands.Root)

	// handle parse error (which means the commandline input was wrong,
	// e.g. incorrect number of args, or nonexistent subcommand)
	if err != nil {
		return nil, nil, handleParseError(req, root, cmd, path, err)
	}

	configPath, err := getConfigRoot(req)
	if err != nil {
		return nil, nil, err
	}

	conf, err := getConfig(configPath)
	if err != nil {
		return nil, nil, err
	}
	ctx := req.Context()
	ctx.ConfigRoot = configPath
	ctx.Config = conf

	// if no encoding was specified by user, default to plaintext encoding
	// (if command doesn't support plaintext, use JSON instead)
	if !req.Option("encoding").Found() {
		if req.Command().Marshallers != nil && req.Command().Marshallers[cmds.Text] != nil {
			req.SetOption("encoding", cmds.Text)
		} else {
			req.SetOption("encoding", cmds.JSON)
		}
	}

	return req, root, nil
}

func handleParseError(req cmds.Request, root *cmds.Command, cmd *cmds.Command, path []string, parseError error) error {
	var longHelp, shortHelp bool

	if req != nil {
		// help and h are defined in the root. We expect them to be bool.
		var err error
		longHelp, _, err = req.Option("help").Bool()
		if err != nil {
			return err
		}
		shortHelp, _, err = req.Option("h").Bool()
		if err != nil {
			return err
		}
	}

	// if the -help flag wasn't specified, show the error message
	// or if a path was returned (user specified a valid subcommand), show the error message
	// (this means there was an option or argument error)
	if path != nil && len(path) > 0 {
		if !longHelp && !shortHelp {
			fmt.Printf(errorFormat, parseError)
		}
	}

	if cmd == nil {
		root = commands.Root
	}

	// show the long help text if the -help flag was specified or we are at the root command
	// otherwise, show short help text
	helpFunc := cmdsCli.ShortHelp
	if longHelp || len(path) == 0 {
		helpFunc = cmdsCli.LongHelp
	}

	htErr := helpFunc("ipfs", root, path, os.Stdout)
	if htErr != nil {
		fmt.Println(htErr)
	}
	return parseError
}

func handleHelpOption(req cmds.Request, root *cmds.Command) (helpTextDisplayed bool, err error) {
	longHelp, _, err := req.Option("help").Bool()
	if err != nil {
		return false, err
	}
	shortHelp, _, err := req.Option("h").Bool()
	if err != nil {
		return false, err
	}
	if !longHelp && !shortHelp {
		return false, nil
	}
	helpFunc := cmdsCli.ShortHelp
	if longHelp || len(req.Path()) == 0 {
		helpFunc = cmdsCli.LongHelp
	}

	err = helpFunc("ipfs", root, req.Path(), os.Stdout)
	if err != nil {
		return false, err
	}
	return true, nil
}

func callCommand(req cmds.Request, root *cmds.Command) (cmds.Response, error) {
	var res cmds.Response

	if root == Root { // TODO explain what it means when root == Root
		res = root.Call(req)

	} else {
		local, found, err := req.Option("local").Bool()
		if err != nil {
			return nil, err
		}

		remote := !found || !local

		if remote && daemon.Locked(req.Context().ConfigRoot) {
			addr, err := ma.NewMultiaddr(req.Context().Config.Addresses.API)
			if err != nil {
				return nil, err
			}

			_, host, err := manet.DialArgs(addr)
			if err != nil {
				return nil, err
			}

			client := cmdsHttp.NewClient(host)

			res, err = client.Send(req)
			if err != nil {
				return nil, err
			}

		} else {
			node, err := core.NewIpfsNode(req.Context().Config, false)
			if err != nil {
				return nil, err
			}
			defer node.Close()
			req.Context().Node = node

			res = root.Call(req)
		}
	}

	return res, nil
}

func outputResponse(res cmds.Response, root *cmds.Command) error {
	if res.Error() != nil {
		fmt.Printf(errorFormat, res.Error().Error())

		if res.Error().Code != cmds.ErrClient {
			return res.Error()
		}

		// if this is a client error, we try to display help text
		if res.Error().Code == cmds.ErrClient {
			err := cmdsCli.ShortHelp("ipfs", root, res.Request().Path(), os.Stdout)
			if err != nil {
				fmt.Println(err)
			}
		}

		emptyErr := errors.New("") // already displayed error text
		return emptyErr
	}

	out, err := res.Reader()
	if err != nil {
		return err
	}

	io.Copy(os.Stdout, out)
	return nil
}

func getConfigRoot(req cmds.Request) (string, error) {
	configOpt, found, err := req.Option("config").String()
	if err != nil {
		return "", err
	}
	if found && configOpt != "" {
		return configOpt, nil
	}

	configPath, err := config.PathRoot()
	if err != nil {
		return "", err
	}
	return configPath, nil
}

func getConfig(path string) (*config.Config, error) {
	configFile, err := config.Filename(path)
	if err != nil {
		return nil, err
	}

	return config.Load(configFile)
}

// startProfiling begins CPU profiling and returns a `stop` function to be
// executed as late as possible. The stop function captures the memprofile.
func startProfiling() (func(), error) {

	// start CPU profiling as early as possible
	ofi, err := os.Create(cpuProfile)
	if err != nil {
		return nil, err
	}
	pprof.StartCPUProfile(ofi)

	stopProfiling := func() {
		pprof.StopCPUProfile()
		defer ofi.Close() // captured by the closure
		err := writeHeapProfileToFile()
		if err != nil {
			log.Critical(err)
		}
	}
	return stopProfiling, nil
}

func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
		return err
	}
	defer mprof.Close() // _after_ writing the heap profile
	return pprof.WriteHeapProfile(mprof)
}

// listen for and handle SIGTERM
func handleInterrupt() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	go func() {
		for _ = range c {
			log.Info("Received interrupt signal, terminating...")
			os.Exit(0)
		}
	}()
}
<commit_msg>cmds2: errHelpRequested error<commit_after>package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"os/signal"
	"runtime/pprof"

	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-logging"
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr/net"

	cmds "github.com/jbenet/go-ipfs/commands"
	cmdsCli "github.com/jbenet/go-ipfs/commands/cli"
	cmdsHttp "github.com/jbenet/go-ipfs/commands/http"
	"github.com/jbenet/go-ipfs/config"
	"github.com/jbenet/go-ipfs/core"
	commands "github.com/jbenet/go-ipfs/core/commands2"
	daemon "github.com/jbenet/go-ipfs/daemon2"
	u "github.com/jbenet/go-ipfs/util"
)

// log is the command logger
var log = u.Logger("cmd/ipfs")

// signal to output help
var errHelpRequested = errors.New("Help Requested")

const (
	cpuProfile  = "ipfs.cpuprof"
	heapProfile = "ipfs.memprof"
	errorFormat = "ERROR: %v\n\n"
)

func main() {
	err := run()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func run() error {
	handleInterrupt()

	args := os.Args[1:]
	req, root, err := createRequest(args)
	if err != nil {
		// when the error is errOutputHelp, just exit gracefully.
		if err == errHelpRequested {
			return nil
		}
		return err
	}

	debug, _, err := req.Option("debug").Bool()
	if err != nil {
		return err
	}
	if debug {
		u.Debug = true
		u.SetAllLoggers(logging.DEBUG)
	}

	if u.Debug {
		stopProfilingFunc, err := startProfiling()
		if err != nil {
			return err
		}
		defer stopProfilingFunc() // to be executed as late as possible
	}

	helpTextDisplayed, err := handleHelpOption(req, root)
	if err != nil {
		return err
	}
	if helpTextDisplayed {
		return nil
	}

	res, err := callCommand(req, root)
	if err != nil {
		return err
	}

	err = outputResponse(res, root)
	if err != nil {
		return err
	}

	return nil
}

func createRequest(args []string) (cmds.Request, *cmds.Command, error) {
	req, root, cmd, path, err := cmdsCli.Parse(args, Root, commands.Root)

	// handle parse error (which means the commandline input was wrong,
	// e.g. incorrect number of args, or nonexistent subcommand)
	if err != nil {
		return nil, nil, handleParseError(req, root, cmd, path, err)
	}

	configPath, err := getConfigRoot(req)
	if err != nil {
		return nil, nil, err
	}

	conf, err := getConfig(configPath)
	if err != nil {
		return nil, nil, err
	}
	ctx := req.Context()
	ctx.ConfigRoot = configPath
	ctx.Config = conf

	// if no encoding was specified by user, default to plaintext encoding
	// (if command doesn't support plaintext, use JSON instead)
	if !req.Option("encoding").Found() {
		if req.Command().Marshallers != nil && req.Command().Marshallers[cmds.Text] != nil {
			req.SetOption("encoding", cmds.Text)
		} else {
			req.SetOption("encoding", cmds.JSON)
		}
	}

	return req, root, nil
}

func handleParseError(req cmds.Request, root *cmds.Command, cmd *cmds.Command, path []string, parseError error) error {
	var longHelp, shortHelp bool

	if req != nil {
		// help and h are defined in the root. We expect them to be bool.
		var err error
		longHelp, _, err = req.Option("help").Bool()
		if err != nil {
			return err
		}
		shortHelp, _, err = req.Option("h").Bool()
		if err != nil {
			return err
		}

		// override the error to avoid signaling other issues.
		parseError = errHelpRequested
	}

	// if the -help flag wasn't specified, show the error message
	// or if a path was returned (user specified a valid subcommand), show the error message
	// (this means there was an option or argument error)
	if path != nil && len(path) > 0 {
		if !longHelp && !shortHelp {
			fmt.Printf(errorFormat, parseError)
		}
	}

	if cmd == nil {
		root = commands.Root
	}

	// show the long help text if the -help flag was specified or we are at the root command
	// otherwise, show short help text
	helpFunc := cmdsCli.ShortHelp
	if longHelp || len(path) == 0 {
		helpFunc = cmdsCli.LongHelp
	}

	htErr := helpFunc("ipfs", root, path, os.Stdout)
	if htErr != nil {
		fmt.Println(htErr)
	}
	return parseError
}

func handleHelpOption(req cmds.Request, root *cmds.Command) (helpTextDisplayed bool, err error) {
	longHelp, _, err := req.Option("help").Bool()
	if err != nil {
		return false, err
	}
	shortHelp, _, err := req.Option("h").Bool()
	if err != nil {
		return false, err
	}
	if !longHelp && !shortHelp {
		return false, nil
	}
	helpFunc := cmdsCli.ShortHelp
	if longHelp || len(req.Path()) == 0 {
		helpFunc = cmdsCli.LongHelp
	}

	err = helpFunc("ipfs", root, req.Path(), os.Stdout)
	if err != nil {
		return false, err
	}
	return true, nil
}

func callCommand(req cmds.Request, root *cmds.Command) (cmds.Response, error) {
	var res cmds.Response

	if root == Root { // TODO explain what it means when root == Root
		res = root.Call(req)

	} else {
		local, found, err := req.Option("local").Bool()
		if err != nil {
			return nil, err
		}

		remote := !found || !local

		if remote && daemon.Locked(req.Context().ConfigRoot) {
			addr, err := ma.NewMultiaddr(req.Context().Config.Addresses.API)
			if err != nil {
				return nil, err
			}

			_, host, err := manet.DialArgs(addr)
			if err != nil {
				return nil, err
			}

			client := cmdsHttp.NewClient(host)

			res, err = client.Send(req)
			if err != nil {
				return nil, err
			}

		} else {
			node, err := core.NewIpfsNode(req.Context().Config, false)
			if err != nil {
				return nil, err
			}
			defer node.Close()
			req.Context().Node = node

			res = root.Call(req)
		}
	}

	return res, nil
}

func outputResponse(res cmds.Response, root *cmds.Command) error {
	if res.Error() != nil {
		fmt.Printf(errorFormat, res.Error().Error())

		if res.Error().Code != cmds.ErrClient {
			return res.Error()
		}

		// if this is a client error, we try to display help text
		if res.Error().Code == cmds.ErrClient {
			err := cmdsCli.ShortHelp("ipfs", root, res.Request().Path(), os.Stdout)
			if err != nil {
				fmt.Println(err)
			}
		}

		emptyErr := errors.New("") // already displayed error text
		return emptyErr
	}

	out, err := res.Reader()
	if err != nil {
		return err
	}

	io.Copy(os.Stdout, out)
	return nil
}

func getConfigRoot(req cmds.Request) (string, error) {
	configOpt, found, err := req.Option("config").String()
	if err != nil {
		return "", err
	}
	if found && configOpt != "" {
		return configOpt, nil
	}

	configPath, err := config.PathRoot()
	if err != nil {
		return "", err
	}
	return configPath, nil
}

func getConfig(path string) (*config.Config, error) {
	configFile, err := config.Filename(path)
	if err != nil {
		return nil, err
	}

	return config.Load(configFile)
}

// startProfiling begins CPU profiling and returns a `stop` function to be
// executed as late as possible. The stop function captures the memprofile.
func startProfiling() (func(), error) {

	// start CPU profiling as early as possible
	ofi, err := os.Create(cpuProfile)
	if err != nil {
		return nil, err
	}
	pprof.StartCPUProfile(ofi)

	stopProfiling := func() {
		pprof.StopCPUProfile()
		defer ofi.Close() // captured by the closure
		err := writeHeapProfileToFile()
		if err != nil {
			log.Critical(err)
		}
	}
	return stopProfiling, nil
}

func writeHeapProfileToFile() error {
	mprof, err := os.Create(heapProfile)
	if err != nil {
		return err
	}
	defer mprof.Close() // _after_ writing the heap profile
	return pprof.WriteHeapProfile(mprof)
}

// listen for and handle SIGTERM
func handleInterrupt() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	go func() {
		for _ = range c {
			log.Info("Received interrupt signal, terminating...")
			os.Exit(0)
		}
	}()
}
<|endoftext|>


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

// Package main creates a HTTP server for a single HTML page that
// controls editing, writing and running go programs.
//
// To run download from git and run:
//     git clone http://code.google.com/p/go-play
//    cd go-play/goplay
//    go run goplay.go # or go build goplay.go && ./goplay
//
// In a web browser load http://localhost:3998/
//
// You should see the standard "Hello World" program, which you can
// compile and run by pressing shift-enter.
//
// Some options are given with --help
//
// A note on security: anyone with access to the goplay web interface
// can run arbitrary code on your computer. Goplay is not a sandbox,
// and has no other security mechanisms. Do not deploy it in untrusted
// environments.  By default, goplay listens only on localhost. This
// can be overridden with the -http parameter. Do so at your own risk.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strconv"
	"text/template"
)

/************** FIXME: put in a separate file ****************/
import (
	"encoding/json"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
)

type fmtResponse struct {
	Body  string
	Error string
}

var tmpdir string

// FmtHandler handles a Go-source format request. The go source code
// is given in req and the formated output is passed back in w.  This
// routine must be called via an HTTP POST request.
func FmtHandler(w http.ResponseWriter, req *http.Request) {
	resp := new(fmtResponse)
	if req.Method != "POST" {
		http.Error(w, "Forbidden, need POST", http.StatusForbidden)
		return
	}
	body, err := gofmt(req.FormValue("body"))
	if err != nil {
		resp.Error = err.Error()
	} else {
		resp.Body = body
	}
	json.NewEncoder(w).Encode(resp)
}

func gofmt(body string) (string, error) {
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "prog.go", body, parser.ParseComments)
	if err != nil {
		return "", err
	}
	ast.SortImports(fset, f)
	var buf bytes.Buffer
	config := &printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
	err = config.Fprint(&buf, fset, f)
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}
/*******************/

// CompileHandler is an HTTP handler that reads Go source code from req,
// runs the program (returning any errors),
// and sends the program's output as the HTTP response to w.
func CompileHandler(w http.ResponseWriter, req *http.Request) {
	out, err := compile(req)
	if err != nil {
		error_(w, out, err)
		return
	}

	// write the output of x as the http response
	if *htmlOutput {
		w.Write(out)
	} else {
		output.Execute(w, out)
	}
}

/*******************/

const DefaultSaveName = "save"
const GoPathSuffix    = ".go"

// SaveHandler writes a Go program to file.
//
// We have to do this in Go since HTML5 Doesn't grok file paths.
//
// In order to be able to distinguish relative versus absolute paths,
// we add an X in the URL. For example /save/X/tmp/save.go versus
// /save/Xtmp/save.go. The latter refers to ./tmp/save.go.
//
// This routine must be called via POST.
func SaveHandler(w http.ResponseWriter, req *http.Request) {
	filename := DefaultSaveName
	// +3 for enclosing "/X", e.g. "/save/X" not "save"
	SaveLen := len(DefaultSaveName) + 3
	if len(req.URL.Path) > SaveLen {
		filename = req.URL.Path[SaveLen:];
		if filename[0] != '/' {
			filename = filepath.Join(tmpdir, filename);
		}
	}
	if req.Method != "POST" {
		http.Error(w, "Forbidden, need POST", http.StatusForbidden)
		return
	}

	/** fmt.Printf("Req %s\n", req) **/
	body := new(bytes.Buffer)
	_, err := body.ReadFrom(req.Body)
	if err != nil {
		http.Error(w, "Server Error in SaveHandler reading Body text",
			http.StatusInternalServerError)
		return
	}
	req.Body.Close()

	if filename[len(filename)-len(GoPathSuffix):] != GoPathSuffix {
		filename += GoPathSuffix
	}
	err = ioutil.WriteFile(filename, body.Bytes(), 0600)
	if err != nil {
		fmt.Printf("Save Error: %s\n", err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Printf("File: %s saved\n", filename)
	w.Write([]byte(filename))
}

/*******************/

func ShareHandler(w http.ResponseWriter, req *http.Request) {
	fmt.Printf("Redirecting\n");
	http.Redirect(w, req, "http://play.golang.org/share", http.StatusFound)
}

/*******************/

var (
	httpListen = flag.String("http", "127.0.0.1:3998",
		"host:port to listen on")
	htmlOutput = flag.Bool("html", false, "render program output as HTML")
	resourceDir = "../static"
	resourceDirP = &resourceDir
	// resourceDir = flag.String("resource-root", "../static",
	// 	"Location of CSS and JavaScript resources")
)

var (
	// a source of numbers, for naming temporary files
	uniq = make(chan int)
)

func main() {
	flag.Parse()

	// source of unique numbers
	go func() {
		for i := 0; ; i++ {
			uniq <- i
		}
	}()

	// find real temporary directory (for rewriting filename in output)
	var err error
	tmpdir, err = filepath.EvalSymlinks(os.TempDir())
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", edit)
	http.HandleFunc("/compile", CompileHandler)
	http.HandleFunc("/fmt",     FmtHandler)
	http.HandleFunc("/save",    SaveHandler)
	http.HandleFunc("/share",   ShareHandler)
	http.HandleFunc("/save/",   SaveHandler)

	http.Handle("/static/", http.StripPrefix("/static/",
		http.FileServer(http.Dir("../static"))))
	fmt.Printf("Runnning Go Play. Attempting to listening on %s\n",
		*httpListen)
	log.Fatal(http.ListenAndServe(*httpListen, nil))
}

var editTemplate = template.Must(template.ParseFiles("goplay.html"))

type Snippet struct {
	Body []byte
}

type editData struct {
	Snippet *Snippet
	ResourceDir string
}

// edit is an HTTP handler that renders the goplay interface.
// If a filename is supplied in the path component of the URI,
// its contents will be put in the interface's text area.
// Otherwise, the default "hello, world" program is displayed.
func edit(w http.ResponseWriter, req *http.Request) {
	data, err := ioutil.ReadFile(req.URL.Path[1:])
	if err != nil {
		data = []byte(hello)
	}

	snip := &Snippet{Body: data}
	editTemplate.Execute(w, &editData{snip, *resourceDirP})
}

var (
	commentRe = regexp.MustCompile(`(?m)^#.*\n`)
)

func compile(req *http.Request) (out []byte, err error) {
	// x is the base name for .go, .6, executable files
	x := filepath.Join(tmpdir, "compile"+strconv.Itoa(<-uniq))
	src := x + ".go"
	bin := x
	if runtime.GOOS == "windows" {
		bin += ".exe"
	}

	// rewrite filename in error output
	defer func() {
		if err != nil {
			// drop messages from the go tool like '# _/compile0'
			out = commentRe.ReplaceAll(out, nil)
		}
		out = bytes.Replace(out, []byte(src+":"), []byte("main.go:"), -1)
	}()

	// write body to x.go
	body := new(bytes.Buffer)
	if _, err = body.ReadFrom(req.Body); err != nil {
		return
	}
	defer os.Remove(src)
	if err = ioutil.WriteFile(src, body.Bytes(), 0666); err != nil {
		return
	}

	// build x.go, creating x
	dir, file := filepath.Split(src)
	out, err = run(dir, "go", "build", "-o", bin, file)
	defer os.Remove(bin)
	if err != nil {
		return
	}

	// run x
	return run("", bin)
}

// error writes compile, link, or runtime errors to the HTTP connection.
// The JavaScript interface uses the 404 status code to identify the error.
func error_(w http.ResponseWriter, out []byte, err error) {
	w.WriteHeader(404)
	if out != nil {
		output.Execute(w, out)
	} else {
		output.Execute(w, err.Error())
	}
}

// run executes the specified command and returns its output and an error.
func run(dir string, args ...string) ([]byte, error) {
	var buf bytes.Buffer
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = dir
	cmd.Stdout = &buf
	cmd.Stderr = cmd.Stdout
	err := cmd.Run()
	return buf.Bytes(), err
}

// HTML output template snippet
const outputText = `<pre>{{printf "%s" . |html}}</pre>`
var output = template.Must(template.New("output").Parse(outputText))

// Default program to start out with.
const hello = `package main

import "fmt"

func main() {
	fmt.Println("hello, world")
}
`
<commit_msg>More doc tweaking<commit_after>// Copyright 2013 Rocky Bernstein.
// Copyright 2010 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package main creates a HTTP server for a single HTML page that
// controls editing, writing and running go programs.
//
// To run download from git and run:
//    git clone http://code.google.com/p/go-play
//    cd go-play/goplay
//    go run goplay.go # or go build goplay.go && ./goplay
//
// In a web browser load http://localhost:3998/
//
// You should see the standard "Hello World" program, which you can
// compile and run by pressing shift-enter.
//
// Options
//
// * --help  give a list of all options
// * --http  host:port to listen on. The default is 127.0.0.1:3998
//
//
// Security
//
// Anyone with access to the goplay web interface
// can run arbitrary code on your computer. Goplay is not a sandbox,
// and has no other security mechanisms. Do not deploy it in untrusted
// environments.  By default, goplay listens only on localhost. This
// can be overridden with the -http parameter. Do so at your own risk.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strconv"
	"text/template"
)

/************** FIXME: put in a separate file ****************/
import (
	"encoding/json"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
)

type fmtResponse struct {
	Body  string
	Error string
}

var tmpdir string

// FmtHandler handles a Go-source format request. The go source code
// is given in req and the formated output is passed back in w.  This
// routine must be called via an HTTP POST request.
func FmtHandler(w http.ResponseWriter, req *http.Request) {
	resp := new(fmtResponse)
	if req.Method != "POST" {
		http.Error(w, "Forbidden, need POST", http.StatusForbidden)
		return
	}
	body, err := gofmt(req.FormValue("body"))
	if err != nil {
		resp.Error = err.Error()
	} else {
		resp.Body = body
	}
	json.NewEncoder(w).Encode(resp)
}

func gofmt(body string) (string, error) {
	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "prog.go", body, parser.ParseComments)
	if err != nil {
		return "", err
	}
	ast.SortImports(fset, f)
	var buf bytes.Buffer
	config := &printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
	err = config.Fprint(&buf, fset, f)
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}
/*******************/

// CompileHandler is an HTTP handler that reads Go source code from req,
// runs the program (returning any errors),
// and sends the program's output as the HTTP response to w.
func CompileHandler(w http.ResponseWriter, req *http.Request) {
	out, err := compile(req)
	if err != nil {
		error_(w, out, err)
		return
	}

	// write the output of x as the http response
	if *htmlOutput {
		w.Write(out)
	} else {
		output.Execute(w, out)
	}
}

/*******************/

const DefaultSaveName = "save"
const GoPathSuffix    = ".go"

// SaveHandler writes a Go program to file.
//
// We have to do this in Go since HTML5 Doesn't grok file paths.
//
// In order to be able to distinguish relative versus absolute paths,
// we add an X in the URL. For example /save/X/tmp/save.go versus
// /save/Xtmp/save.go. The latter refers to ./tmp/save.go.
//
// This routine must be called via POST.
func SaveHandler(w http.ResponseWriter, req *http.Request) {
	filename := DefaultSaveName
	// +3 for enclosing "/X", e.g. "/save/X" not "save"
	SaveLen := len(DefaultSaveName) + 3
	if len(req.URL.Path) > SaveLen {
		filename = req.URL.Path[SaveLen:];
		if filename[0] != '/' {
			filename = filepath.Join(tmpdir, filename);
		}
	}
	if req.Method != "POST" {
		http.Error(w, "Forbidden, need POST", http.StatusForbidden)
		return
	}

	/** fmt.Printf("Req %s\n", req) **/
	body := new(bytes.Buffer)
	_, err := body.ReadFrom(req.Body)
	if err != nil {
		http.Error(w, "Server Error in SaveHandler reading Body text",
			http.StatusInternalServerError)
		return
	}
	req.Body.Close()

	if filename[len(filename)-len(GoPathSuffix):] != GoPathSuffix {
		filename += GoPathSuffix
	}
	err = ioutil.WriteFile(filename, body.Bytes(), 0600)
	if err != nil {
		fmt.Printf("Save Error: %s\n", err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Printf("File: %s saved\n", filename)
	w.Write([]byte(filename))
}

/*******************/

func ShareHandler(w http.ResponseWriter, req *http.Request) {
	fmt.Printf("Redirecting\n");
	http.Redirect(w, req, "http://play.golang.org/share", http.StatusFound)
}

/*******************/

var (
	httpListen = flag.String("http", "127.0.0.1:3998",
		"host:port to listen on")
	htmlOutput = flag.Bool("html", false, "render program output as HTML")
	resourceDir = "../static"
	resourceDirP = &resourceDir
	// resourceDir = flag.String("resource-root", "../static",
	// 	"Location of CSS and JavaScript resources")
)

var (
	// a source of numbers, for naming temporary files
	uniq = make(chan int)
)

func main() {
	flag.Parse()

	// source of unique numbers
	go func() {
		for i := 0; ; i++ {
			uniq <- i
		}
	}()

	// find real temporary directory (for rewriting filename in output)
	var err error
	tmpdir, err = filepath.EvalSymlinks(os.TempDir())
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", edit)
	http.HandleFunc("/compile", CompileHandler)
	http.HandleFunc("/fmt",     FmtHandler)
	http.HandleFunc("/save",    SaveHandler)
	http.HandleFunc("/share",   ShareHandler)
	http.HandleFunc("/save/",   SaveHandler)

	http.Handle("/static/", http.StripPrefix("/static/",
		http.FileServer(http.Dir("../static"))))
	fmt.Printf("Runnning Go Play. Attempting to listening on %s\n",
		*httpListen)
	log.Fatal(http.ListenAndServe(*httpListen, nil))
}

var editTemplate = template.Must(template.ParseFiles("goplay.html"))

type Snippet struct {
	Body []byte
}

type editData struct {
	Snippet *Snippet
	ResourceDir string
}

// edit is an HTTP handler that renders the goplay interface.
// If a filename is supplied in the path component of the URI,
// its contents will be put in the interface's text area.
// Otherwise, the default "hello, world" program is displayed.
func edit(w http.ResponseWriter, req *http.Request) {
	data, err := ioutil.ReadFile(req.URL.Path[1:])
	if err != nil {
		data = []byte(hello)
	}

	snip := &Snippet{Body: data}
	editTemplate.Execute(w, &editData{snip, *resourceDirP})
}

var (
	commentRe = regexp.MustCompile(`(?m)^#.*\n`)
)

func compile(req *http.Request) (out []byte, err error) {
	// x is the base name for .go, .6, executable files
	x := filepath.Join(tmpdir, "compile"+strconv.Itoa(<-uniq))
	src := x + ".go"
	bin := x
	if runtime.GOOS == "windows" {
		bin += ".exe"
	}

	// rewrite filename in error output
	defer func() {
		if err != nil {
			// drop messages from the go tool like '# _/compile0'
			out = commentRe.ReplaceAll(out, nil)
		}
		out = bytes.Replace(out, []byte(src+":"), []byte("main.go:"), -1)
	}()

	// write body to x.go
	body := new(bytes.Buffer)
	if _, err = body.ReadFrom(req.Body); err != nil {
		return
	}
	defer os.Remove(src)
	if err = ioutil.WriteFile(src, body.Bytes(), 0666); err != nil {
		return
	}

	// build x.go, creating x
	dir, file := filepath.Split(src)
	out, err = run(dir, "go", "build", "-o", bin, file)
	defer os.Remove(bin)
	if err != nil {
		return
	}

	// run x
	return run("", bin)
}

// error writes compile, link, or runtime errors to the HTTP connection.
// The JavaScript interface uses the 404 status code to identify the error.
func error_(w http.ResponseWriter, out []byte, err error) {
	w.WriteHeader(404)
	if out != nil {
		output.Execute(w, out)
	} else {
		output.Execute(w, err.Error())
	}
}

// run executes the specified command and returns its output and an error.
func run(dir string, args ...string) ([]byte, error) {
	var buf bytes.Buffer
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = dir
	cmd.Stdout = &buf
	cmd.Stderr = cmd.Stdout
	err := cmd.Run()
	return buf.Bytes(), err
}

// HTML output template snippet
const outputText = `<pre>{{printf "%s" . |html}}</pre>`
var output = template.Must(template.New("output").Parse(outputText))

// Default program to start out with.
const hello = `package main

import "fmt"

func main() {
	fmt.Println("hello, world")
}
`
<|endoftext|>


<commit_before>package main

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

const (
	templ = `%s
===
Content goes here...

### EOF
` + "```yaml" + `
date: %s
summary: # summary for this article
weather: # hey, what's the weather like?
license: all-rights-reserved # "cc-40-by", "cc-40-by-sa", "cc-40-by-nd", "cc-40-by-nc", "cc-40-by-nc-nd", "cc-40-by-nc-sa", "cc-40-zero", "public-domain".
location: # where you wrote this?
background: # banner image for this article, or RGBA hex color value(i.e. starting with '#')
tags:
  - tag1
  - tag2
` + "```"
)

var mkdir = func(name string) error {
	return os.MkdirAll(name, 0755)
}

func mayFail(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s title\n", os.Args[0])
		os.Exit(1)
	}
	title := os.Args[1]
	dir := formatName(title)

	mayFail(mkdir(dir))

	f := filepath.Join(dir, "README.md")
	_, err := os.Stat(f)
	if err == nil {
		fmt.Printf("%s already existed, discard it? y/n: ", f)
		b := make([]byte, 50)
		n, err := os.Stdin.Read(b)
		mayFail(err)
		if n < 1 || b[0] != 'y' {
			fmt.Println("aborted.")
			os.Exit(0)
		}
	}

	out, err := os.Create(f)

	mayFail(err)

	mayFail(newMD(title, out))

	fmt.Println("done :)")
}

func newMD(title string, out io.Writer) error {
	_, err := out.Write([]byte(fmt.Sprintf(templ, title, time.Now().Format(time.RFC3339))))
	return err
}

func formatName(name string) string {
	return strings.Replace(strings.ToLower(name), " ", "-", -1)
}
<commit_msg>Change `newmd` default template options<commit_after>package main

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

const (
	templ = `# %s
Content goes here..

## EOF
` + "```yaml" + `
date: %s
summary: # summary for this article
weather: # hey, what's the weather like?
license: cc-40-by # "all-rights-reserved", "cc-40-by-sa", "cc-40-by-nd", "cc-40-by-nc", "cc-40-by-nc-nd", "cc-40-by-nc-sa", "cc-40-zero", "public-domain".
location: # where you wrote this?
background: # banner image for this article, or RGBA hex color value(i.e. starting with '#')
tags:
  - tag1
  - tag2
` + "```"
)

var mkdir = func(name string) error {
	return os.MkdirAll(name, 0755)
}

func mayFail(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s title\n", os.Args[0])
		os.Exit(1)
	}
	title := os.Args[1]
	dir := formatName(title)

	mayFail(mkdir(dir))

	f := filepath.Join(dir, "README.md")
	_, err := os.Stat(f)
	if err == nil {
		fmt.Printf("%s already existed, discard it? y/n: ", f)
		b := make([]byte, 50)
		n, err := os.Stdin.Read(b)
		mayFail(err)
		if n < 1 || b[0] != 'y' {
			fmt.Println("aborted.")
			os.Exit(0)
		}
	}

	out, err := os.Create(f)

	mayFail(err)

	mayFail(newMD(title, out))

	fmt.Println("done :)")
}

func newMD(title string, out io.Writer) error {
	_, err := out.Write([]byte(fmt.Sprintf(templ, title, time.Now().Format(time.RFC3339))))
	return err
}

func formatName(name string) string {
	return strings.Replace(strings.ToLower(name), " ", "-", -1)
}
<|endoftext|>


<commit_before>// Package main is located in the cmd/ponzu directory and contains the code to build
// and operate the command line interface (CLI) to manage Ponzu systems. Here,
// you will find the code that is used to create new Ponzu projects, generate
// code for content types and other files, build Ponzu binaries and run servers.
package main

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/ponzu-cms/ponzu/system/admin"
	"github.com/ponzu-cms/ponzu/system/api"
	"github.com/ponzu-cms/ponzu/system/api/analytics"
	"github.com/ponzu-cms/ponzu/system/db"
	"github.com/ponzu-cms/ponzu/system/tls"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	_ "github.com/ponzu-cms/ponzu/content"
)

var (
	port      int
	httpsport int
	https     bool
	devhttps  bool
	cli       bool

	// for ponzu internal / core development
	dev   bool
	fork  string
	gocmd string
	year  = fmt.Sprintf("%d", time.Now().Year())
)

var rootCmd = &cobra.Command{
	Use: "ponzu",
	Long: `Ponzu is a powerful and efficient open-source HTTP server framework and CMS. It
provides automatic, free, and secure HTTP/2 over TLS (certificates obtained via
[Let's Encrypt](https://letsencrypt.org)), a useful CMS and scaffolding to
generate set-up code, and a fast HTTP API on which to build modern applications.

Ponzu is released under the BSD-3-Clause license (see LICENSE).
(c) 2016 - ` + year + ` Boss Sauce Creative, LLC`,
}

var runCmd = &cobra.Command{
	Use:   "run <service(,service)>",
	Short: "starts the 'ponzu' HTTP server for the JSON API and or Admin System.",
	Long: `Starts the 'ponzu' HTTP server for the JSON API, Admin System, or both.
The segments, separated by a comma, describe which services to start, either
'admin' (Admin System / CMS backend) or 'api' (JSON API), and, optionally,
if the server should utilize TLS encryption - served over HTTPS, which is
automatically managed using Let's Encrypt (https://letsencrypt.org)

Defaults to '-port=8080 run admin,api' (running Admin & API on port 8080, without TLS)

Note:
Admin and API cannot run on separate processes unless you use a copy of the
database, since the first process to open it receives a lock. If you intend
to run the Admin and API on separate processes, you must call them with the
'ponzu' command independently.`,
	Example: `$ ponzu run
(or)
$ ponzu -port=8080 --https run admin,api
(or)
$ ponzu run admin
(or)
$ ponzu -port=8888 run api`,
	RunE: func(cmd *cobra.Command, args []string) error {
		var addTLS string
		if https {
			addTLS = "--https"
		} else {
			addTLS = "--https=false"
		}

		if devhttps {
			addTLS = "--devhttps"
		}

		var services string
		if len(args) > 0 {
			services = args[0]
		} else {
			services = "admin,api"
		}

		name := buildOutputName()
		buildPathName := strings.Join([]string{".", name}, string(filepath.Separator))
		serve := exec.Command(buildPathName,
			fmt.Sprintf("--port=%d", port),
			fmt.Sprintf("--httpsport=%d", httpsport),
			addTLS,
			"serve",
			services,
		)
		serve.Stderr = os.Stderr
		serve.Stdout = os.Stdout

		return serve.Run()
	},
}

var ErrWrongOrMissingService = errors.New("To execute 'ponzu serve', " +
	"you must specify which service to run.")

var serveCmd = &cobra.Command{
	Use:     "serve <service,service>",
	Aliases: []string{"s"},
	Short:   "actually run the server",
	Hidden:  true,
	RunE: func(cmd *cobra.Command, args []string) error {
		if len(args) == 0 {
			return ErrWrongOrMissingService
		}

		db.Init()
		defer db.Close()

		analytics.Init()
		defer analytics.Close()

		services := strings.Split(args[0], ",")

		for _, service := range services {
			if service == "api" {
				api.Run()
			} else if service == "admin" {
				admin.Run()
			} else {
				return ErrWrongOrMissingService
			}
		}

		// save the https port the system is listening on
		err := db.PutConfig("https_port", fmt.Sprintf("%d", httpsport))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		// cannot run production HTTPS and development HTTPS together
		if devhttps {
			fmt.Println("Enabling self-signed HTTPS... [DEV]")

			go tls.EnableDev()
			fmt.Println("Server listening on https://localhost:10443 for requests... [DEV]")
			fmt.Println("----")
			fmt.Println("If your browser rejects HTTPS requests, try allowing insecure connections on localhost.")
			fmt.Println("on Chrome, visit chrome://flags/#allow-insecure-localhost")

		} else if https {
			fmt.Println("Enabling HTTPS...")

			go tls.Enable()
			fmt.Printf("Server listening on :%s for HTTPS requests...\n", db.ConfigCache("https_port").(string))
		}

		// save the https port the system is listening on so internal system can make
		// HTTP api calls while in dev or production w/o adding more cli flags
		err = db.PutConfig("http_port", fmt.Sprintf("%d", port))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		fmt.Printf("Server listening on :%d for HTTP requests...\n", port)
		fmt.Println("\nvisit `/admin` to get started.")
		log.Fatalln(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
		return nil
	},
}

func init() {
	for _, cmd := range []*cobra.Command{runCmd, serveCmd} {
		cmd.Flags().IntVar(&port, "port", 8080, "port for ponzu to bind its HTTP listener")
		cmd.Flags().IntVar(&httpsport, "httpsport", 443, "port for ponzu to bind its HTTPS listener")
		cmd.Flags().BoolVar(&https, "https", false, "enable automatic TLS/SSL certificate management")
		cmd.Flags().BoolVar(&devhttps, "devhttps", false, "[dev environment] enable automatic TLS/SSL certificate management")
	}

	RegisterCmdlineCommand(runCmd)
	RegisterCmdlineCommand(serveCmd)

	pflags := rootCmd.PersistentFlags()
	pflags.StringVar(&gocmd, "gocmd", "go", "custom go command if using beta or new release of Go")

	viper.SetEnvPrefix("PONZU")
	viper.BindPFlag("gocmd", pflags.Lookup("gocmd"))
	// bind the flags for run to environment variables, with PONZU_ prefix.
	viper.BindPFlag("port", runCmd.Flags().Lookup("port"))
	viper.BindPFlag("httpsport", runCmd.Flags().Lookup("httpsport"))
	viper.BindPFlag("devhttps", runCmd.Flags().Lookup("devhttps"))
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func execAndWait(command string, arg ...string) error {
	cmd := exec.Command(command, arg...)
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout

	err := cmd.Start()
	if err != nil {
		return err

	}
	return cmd.Wait()
}
<commit_msg>remove use of viper to parse env variables<commit_after>// Package main is located in the cmd/ponzu directory and contains the code to build
// and operate the command line interface (CLI) to manage Ponzu systems. Here,
// you will find the code that is used to create new Ponzu projects, generate
// code for content types and other files, build Ponzu binaries and run servers.
package main

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/ponzu-cms/ponzu/system/admin"
	"github.com/ponzu-cms/ponzu/system/api"
	"github.com/ponzu-cms/ponzu/system/api/analytics"
	"github.com/ponzu-cms/ponzu/system/db"
	"github.com/ponzu-cms/ponzu/system/tls"
	"github.com/spf13/cobra"

	_ "github.com/ponzu-cms/ponzu/content"
)

var (
	port      int
	httpsport int
	https     bool
	devhttps  bool
	cli       bool

	// for ponzu internal / core development
	dev   bool
	fork  string
	gocmd string
	year  = fmt.Sprintf("%d", time.Now().Year())
)

var rootCmd = &cobra.Command{
	Use: "ponzu",
	Long: `Ponzu is a powerful and efficient open-source HTTP server framework and CMS. It
provides automatic, free, and secure HTTP/2 over TLS (certificates obtained via
[Let's Encrypt](https://letsencrypt.org)), a useful CMS and scaffolding to
generate set-up code, and a fast HTTP API on which to build modern applications.

Ponzu is released under the BSD-3-Clause license (see LICENSE).
(c) 2016 - ` + year + ` Boss Sauce Creative, LLC`,
}

var runCmd = &cobra.Command{
	Use:   "run <service(,service)>",
	Short: "starts the 'ponzu' HTTP server for the JSON API and or Admin System.",
	Long: `Starts the 'ponzu' HTTP server for the JSON API, Admin System, or both.
The segments, separated by a comma, describe which services to start, either
'admin' (Admin System / CMS backend) or 'api' (JSON API), and, optionally,
if the server should utilize TLS encryption - served over HTTPS, which is
automatically managed using Let's Encrypt (https://letsencrypt.org)

Defaults to '-port=8080 run admin,api' (running Admin & API on port 8080, without TLS)

Note:
Admin and API cannot run on separate processes unless you use a copy of the
database, since the first process to open it receives a lock. If you intend
to run the Admin and API on separate processes, you must call them with the
'ponzu' command independently.`,
	Example: `$ ponzu run
(or)
$ ponzu -port=8080 --https run admin,api
(or)
$ ponzu run admin
(or)
$ ponzu -port=8888 run api`,
	RunE: func(cmd *cobra.Command, args []string) error {
		var addTLS string
		if https {
			addTLS = "--https"
		} else {
			addTLS = "--https=false"
		}

		if devhttps {
			addTLS = "--devhttps"
		}

		var services string
		if len(args) > 0 {
			services = args[0]
		} else {
			services = "admin,api"
		}

		name := buildOutputName()
		buildPathName := strings.Join([]string{".", name}, string(filepath.Separator))
		serve := exec.Command(buildPathName,
			fmt.Sprintf("--port=%d", port),
			fmt.Sprintf("--httpsport=%d", httpsport),
			addTLS,
			"serve",
			services,
		)
		serve.Stderr = os.Stderr
		serve.Stdout = os.Stdout

		return serve.Run()
	},
}

var ErrWrongOrMissingService = errors.New("To execute 'ponzu serve', " +
	"you must specify which service to run.")

var serveCmd = &cobra.Command{
	Use:     "serve <service,service>",
	Aliases: []string{"s"},
	Short:   "actually run the server",
	Hidden:  true,
	RunE: func(cmd *cobra.Command, args []string) error {
		if len(args) == 0 {
			return ErrWrongOrMissingService
		}

		db.Init()
		defer db.Close()

		analytics.Init()
		defer analytics.Close()

		services := strings.Split(args[0], ",")

		for _, service := range services {
			if service == "api" {
				api.Run()
			} else if service == "admin" {
				admin.Run()
			} else {
				return ErrWrongOrMissingService
			}
		}

		// save the https port the system is listening on
		err := db.PutConfig("https_port", fmt.Sprintf("%d", httpsport))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		// cannot run production HTTPS and development HTTPS together
		if devhttps {
			fmt.Println("Enabling self-signed HTTPS... [DEV]")

			go tls.EnableDev()
			fmt.Println("Server listening on https://localhost:10443 for requests... [DEV]")
			fmt.Println("----")
			fmt.Println("If your browser rejects HTTPS requests, try allowing insecure connections on localhost.")
			fmt.Println("on Chrome, visit chrome://flags/#allow-insecure-localhost")

		} else if https {
			fmt.Println("Enabling HTTPS...")

			go tls.Enable()
			fmt.Printf("Server listening on :%s for HTTPS requests...\n", db.ConfigCache("https_port").(string))
		}

		// save the https port the system is listening on so internal system can make
		// HTTP api calls while in dev or production w/o adding more cli flags
		err = db.PutConfig("http_port", fmt.Sprintf("%d", port))
		if err != nil {
			log.Fatalln("System failed to save config. Please try to run again.", err)
		}

		fmt.Printf("Server listening on :%d for HTTP requests...\n", port)
		fmt.Println("\nvisit `/admin` to get started.")
		log.Fatalln(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
		return nil
	},
}

func init() {
	for _, cmd := range []*cobra.Command{runCmd, serveCmd} {
		cmd.Flags().IntVar(&port, "port", 8080, "port for ponzu to bind its HTTP listener")
		cmd.Flags().IntVar(&httpsport, "httpsport", 443, "port for ponzu to bind its HTTPS listener")
		cmd.Flags().BoolVar(&https, "https", false, "enable automatic TLS/SSL certificate management")
		cmd.Flags().BoolVar(&devhttps, "devhttps", false, "[dev environment] enable automatic TLS/SSL certificate management")
	}

	RegisterCmdlineCommand(runCmd)
	RegisterCmdlineCommand(serveCmd)

	pflags := rootCmd.PersistentFlags()
	pflags.StringVar(&gocmd, "gocmd", "go", "custom go command if using beta or new release of Go")
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func execAndWait(command string, arg ...string) error {
	cmd := exec.Command(command, arg...)
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout

	err := cmd.Start()
	if err != nil {
		return err

	}
	return cmd.Wait()
}
<|endoftext|>


<commit_before>package notify

import (
	"fmt"
	"strings"
)

func Print(m Message) {
	if m == nil {
		return
	}
	switch m.Type() {
	case NotifyInfo:
		printInfo(m.Message())
	case NotifyWarning:
		printWarning(m.Message())
	case NotifyError:
		printError(m.Message())
	}
}

func printInfo(args ...interface{}) {
	fmt.Fprintf(Console.StandardOut, "INFO: %s\n", args...)
}

func printError(args ...interface{}) {
	fmt.Fprintf(Console.StandardError, "ERROR: %s\n", args...)
}

func printWarning(args ...interface{}) {
	fmt.Fprintf(Console.StandardOut, "WARN: %s\n", args...)
}

func Debugf(format string, args ...interface{}) {
	// make sure it ends with newline
	if !strings.HasSuffix(format, "\n") {
		format += "\n"
	}
	fmt.Fprintf(Console.StandardOut, format, args...)
}
<commit_msg>restore term colors<commit_after>package notify

import (
	"fmt"
	"strings"
)

func Print(m Message) {
	if m == nil {
		return
	}
	switch m.Type() {
	case NotifyInfo:
		printInfo(m.Message())
	case NotifyWarning:
		printWarning(m.Message())
	case NotifyError:
		printError(m.Message())
	}
}

// Println is to inject a function that can report info,error and warning
var Println = fmt.Println

// func printInfo(args ...interface{}) {
// 	fmt.Fprintf(Console.StandardOut, "INFO: %s\n", args...)
// }

// func printError(args ...interface{}) {
// 	fmt.Fprintf(Console.StandardError, "ERROR: %s\n", args...)
// }

// func printWarning(args ...interface{}) {
// 	fmt.Fprintf(Console.StandardOut, "WARN: %s\n", args...)
// }

func Debugf(format string, args ...interface{}) {
	// make sure it ends with newline
	if !strings.HasSuffix(format, "\n") {
		format += "\n"
	}
	fmt.Fprintf(Console.StandardOut, format, args...)
}

func printInfo(args ...interface{}) {
	Println(append([]interface{}{"\033[1;32minfo:\033[0m"}, args...)...)
}

func printError(args ...interface{}) {
	Println(append([]interface{}{"\033[1;31merror:\033[0m"}, args...)...)
}

func printWarning(args ...interface{}) {
	Println(append([]interface{}{"\033[1;33mwarning:\033[0m"}, args...)...)
}
<|endoftext|>


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

package main

import (
	"github.com/globocom/tsuru/cmd"
	"github.com/globocom/tsuru/cmd/tsuru-base"
	"os"
)

const (
	version = "0.7.6"
	header  = "Supported-Tsuru"
)

func buildManager(name string) *cmd.Manager {
	m := cmd.BuildBaseManager(name, version, header)
	m.Register(&tsuru.AppRun{})
	m.Register(&tsuru.AppInfo{})
	m.Register(&AppCreate{})
	m.Register(&AppRemove{})
	m.Register(&UnitAdd{})
	m.Register(&UnitRemove{})
	m.Register(tsuru.AppList{})
	m.Register(&tsuru.AppLog{})
	m.Register(&tsuru.AppGrant{})
	m.Register(&tsuru.AppRevoke{})
	m.Register(&tsuru.AppRestart{})
	m.Register(&tsuru.SetCName{})
	m.Register(&tsuru.UnsetCName{})
	m.Register(&tsuru.EnvGet{})
	m.Register(&tsuru.EnvSet{})
	m.Register(&tsuru.EnvUnset{})
	m.Register(&KeyAdd{})
	m.Register(&KeyRemove{})
	m.Register(tsuru.ServiceList{})
	m.Register(tsuru.ServiceAdd{})
	m.Register(tsuru.ServiceRemove{})
	m.Register(tsuru.ServiceDoc{})
	m.Register(tsuru.ServiceInfo{})
	m.Register(tsuru.ServiceInstanceStatus{})
	m.Register(&tsuru.ServiceBind{})
	m.Register(&tsuru.ServiceUnbind{})
	return m
}

func main() {
	name := cmd.ExtractProgramName(os.Args[0])
	manager := buildManager(name)
	manager.Run(os.Args[1:])
}
<commit_msg>cmd/tsuru: version 0.7.7<commit_after>// Copyright 2013 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"github.com/globocom/tsuru/cmd"
	"github.com/globocom/tsuru/cmd/tsuru-base"
	"os"
)

const (
	version = "0.7.7"
	header  = "Supported-Tsuru"
)

func buildManager(name string) *cmd.Manager {
	m := cmd.BuildBaseManager(name, version, header)
	m.Register(&tsuru.AppRun{})
	m.Register(&tsuru.AppInfo{})
	m.Register(&AppCreate{})
	m.Register(&AppRemove{})
	m.Register(&UnitAdd{})
	m.Register(&UnitRemove{})
	m.Register(tsuru.AppList{})
	m.Register(&tsuru.AppLog{})
	m.Register(&tsuru.AppGrant{})
	m.Register(&tsuru.AppRevoke{})
	m.Register(&tsuru.AppRestart{})
	m.Register(&tsuru.SetCName{})
	m.Register(&tsuru.UnsetCName{})
	m.Register(&tsuru.EnvGet{})
	m.Register(&tsuru.EnvSet{})
	m.Register(&tsuru.EnvUnset{})
	m.Register(&KeyAdd{})
	m.Register(&KeyRemove{})
	m.Register(tsuru.ServiceList{})
	m.Register(tsuru.ServiceAdd{})
	m.Register(tsuru.ServiceRemove{})
	m.Register(tsuru.ServiceDoc{})
	m.Register(tsuru.ServiceInfo{})
	m.Register(tsuru.ServiceInstanceStatus{})
	m.Register(&tsuru.ServiceBind{})
	m.Register(&tsuru.ServiceUnbind{})
	return m
}

func main() {
	name := cmd.ExtractProgramName(os.Args[0])
	manager := buildManager(name)
	manager.Run(os.Args[1:])
}
<|endoftext|>


<commit_before>package notify

import (
	"errors"

	"github.com/godbus/dbus"
)

// Returns the capabilities of the notification server as a string array
func GetCapabilities() (c []string, err error) {

	connection, err := dbus.SessionBus()
	if err != nil {

		return
	}

	call := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").Call("org.freedesktop.Notifications.GetCapabilities", 0)

	if call.Err != nil {

		return nil, call.Err
	}

	if err := call.Store(&c); err != nil {

		return nil, err
	}

	return
}

// Create a new notification object with some basic information
func NewNotification(summary, body string) (n *Notification, err error) {

	if len(summary) == 0 {

		return nil, errors.New("The Notification must contain a summary")
	}

	n = &Notification{

		Summary: summary,
		Body:    body,
		Timeout: -1,
	}
	return
}

// Send the notification
func (n *Notification) Send() (id uint32, err error) {

	hints := map[string]dbus.Variant{}
	if len(n.Hints) != 0 {

		for k, v := range n.Hints {

			hints[k] = dbus.MakeVariant(v)
		}
	}

	connection, err := dbus.SessionBus()
	if err != nil {

		return
	}
	obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")

	call := obj.Call(
		"org.freedesktop.Notifications.Notify",
		0,
		n.AppName,
		n.ReplacesID,
		n.AppIcon,
		n.Summary,
		n.Body,
		n.Actions,
		hints,
		n.Timeout)

	if call.Err != nil {

		return 0, call.Err
	}

	if err := call.Store(&id); err != nil {

		return 0, err
	}

	return
}

// Closes the notification if it exists using its id
func CloseNotification(id uint32) (err error) {

	connection, err := dbus.SessionBus()
	if err != nil {

		return
	}

	call := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").Call("org.freedesktop.Notifications.GetCapabilities", 0, id)

	if call.Err != nil {

		return call.Err
	}

	return
}
<commit_msg>Added server capabilities method, categories, and  urgency levels.<commit_after>package notify

import (
	"errors"

	"github.com/godbus/dbus"
)

// Categories
const (
	Device              = "device"
	DeviceAdded         = "device.added"
	DeviceError         = "device.error"
	DeviceRemoved       = "device.removed"
	Email               = "email"
	EmailArrived        = "email.arrived"
	EmailBounced        = "email.bounced"
	Im                  = "im"
	ImError             = "im.error"
	ImReceived          = "im.received"
	Network             = "network"
	NetworkConnected    = "network.connected"
	NetworkDisconnected = "network.disconnected"
	NetworkError        = "network.error"
	Presence            = "presence"
	PresenceOffline     = "presence.offline"
	PresenceOnline      = "presence.online"
	Transfer            = "transfer"
	TransferComplete    = "transfer.complete"
	TransferError       = "transfer.error"
)

// Urgency Levels
const (
	Low      = 0
	Normal   = 1
	Critical = 2
)

// Capabilities
const (
	ActionIcons    = "action-icons"
	Actions        = "actions"
	Body           = "body"
	BodyHyperlinks = "body-hyperlinks"
	BodyImages     = "body-images"
	BodyMarkup     = "body-markup"
	IconMulti      = "icon-multi"
	IconStatic     = "icon-static"
	Persistence    = "persistence"
	Sound          = "sound"
)

type Capabilities struct {
	ActionIcons    bool
	Actions        bool
	Body           bool
	BodyHyperlinks bool
	BodyImages     bool
	BodyMarkup     bool
	IconMulti      bool
	IconStatic     bool
	Persistence    bool
	Sound          bool
}

// Returns the capabilities of the notification server as a string array
func GetCapabilities() (c *Capabilities, err error) {

	connection, err := dbus.SessionBus()
	if err != nil {

		return
	}
	obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")

	call := obj.Call("org.freedesktop.Notifications.GetCapabilities", 0)
	if call.Err != nil {

		return nil, call.Err
	}

	c = &Capabilities{}
	s := []string{}

	if err := call.Store(&s); err != nil {

		return nil, err
	}

	for _, v := range s {

		if v == ActionIcons {

			c.ActionIcons = true
			continue
		}

		if v == Actions {

			c.Actions = true
			continue
		}

		if v == Body {

			c.Body = true
			continue
		}

		if v == BodyHyperlinks {

			c.BodyHyperlinks = true
			continue
		}

		if v == BodyImages {

			c.BodyImages = true
			continue
		}

		if v == BodyMarkup {

			c.BodyMarkup = true
			continue
		}

		if v == IconMulti {

			c.IconMulti = true
			continue
		}

		if v == IconStatic {

			c.IconStatic = true
			continue
		}

		if v == Persistence {

			c.Persistence = true
			continue
		}

		if v == Sound {

			c.Sound = true
			continue
		}
	}

	return
}

// Create a new notification object with some basic information
func NewNotification(summary, body string) (n *Notification, err error) {

	if len(summary) == 0 {

		return nil, errors.New("The Notification must contain a summary")
	}

	n = &Notification{

		Summary: summary,
		Body:    body,
		Timeout: -1,
	}
	return
}

// Send the notification
func (n *Notification) Send() (id uint32, err error) {

	hints := map[string]dbus.Variant{}
	if len(n.Hints) != 0 {

		for k, v := range n.Hints {

			hints[k] = dbus.MakeVariant(v)
		}
	}

	connection, err := dbus.SessionBus()
	if err != nil {

		return
	}
	obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")

	call := obj.Call(
		"org.freedesktop.Notifications.Notify",
		0,
		n.AppName,
		n.ReplacesID,
		n.AppIcon,
		n.Summary,
		n.Body,
		n.Actions,
		hints,
		n.Timeout)

	if call.Err != nil {

		return 0, call.Err
	}

	if err := call.Store(&id); err != nil {

		return 0, err
	}

	return
}

// Closes the notification if it exists using its id
func CloseNotification(id uint32) (err error) {

	connection, err := dbus.SessionBus()
	if err != nil {

		return
	}
	obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")

	call := obj.Call("org.freedesktop.Notifications.GetCapabilities", 0, id)
	if call.Err != nil {

		return call.Err
	}

	return
}

type ServerInformation struct {
	Name        string
	Vendor      string
	Version     string
	SpecVersion string
}

// Gets information about the notification server
func GetServerInformation() (i *ServerInformation, err error) {

	connection, err := dbus.SessionBus()
	if err != nil {

		return
	}
	obj := connection.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")

	call := obj.Call("org.freedesktop.Notifications.GetServerInformation", 0)
	if call.Err != nil {

		return nil, call.Err
	}

	i = &ServerInformation{}
	if err := call.Store(&i.Name, i.Vendor, i.Version, i.SpecVersion); err != nil {

		return nil, err
	}

	return
}
<|endoftext|>


<commit_before>package sqlf

import (
	"errors"
)

var errNotImplemented = errors.New("not implemented")

type InsertRowStmt struct {
	commonStmt
}

func MustPrepareInsertRow(row interface{}, sql string) *InsertRowStmt {
	stmt, err := PrepareInsertRow(row, sql)
	if err != nil {
		panic(err)
	}
	return stmt
}

func PrepareInsertRow(row interface{}, sql string) (*InsertRowStmt, error) {
	return nil, errNotImplemented
}

func (stmt *InsertRowStmt) Exec(db Execer, row interface{}) error {
	return errNotImplemented
}

func (stmt *InsertRowStmt) WithConfig(cfg *Config) *InsertRowStmt {
	return stmt
}

type UpdateRowStmt struct {
	commonStmt
}

func MustPrepareUpdateRow(row interface{}, sql string) *UpdateRowStmt {
	stmt := &UpdateRowStmt{}
	stmt.err = errNotImplemented
	return stmt
}

func PrepareUpdateRow(row interface{}, sql string) (*UpdateRowStmt, error) {
	stmt := &UpdateRowStmt{}
	stmt.err = errNotImplemented
	return stmt, errNotImplemented
}

func (stmt *UpdateRowStmt) Exec(db Execer, row interface{}) (int, error) {
	return 0, errNotImplemented
}

func (stmt *UpdateRowStmt) WithConfig(cfg *Config) *UpdateRowStmt {
	return stmt
}

type GetRowStmt struct {
	commonStmt
}

func MustPrepareGetRow(row interface{}, sql string) *GetRowStmt {
	stmt, err := PrepareGetRow(row, sql)
	if err != nil {
		panic(err)
	}
	return stmt
}

func PrepareGetRow(row interface{}, sql string) (*GetRowStmt, error) {
	return nil, errNotImplemented
}

func (stmt *GetRowStmt) Get(db Queryer, row interface{}) (int, error) {
	return 0, errNotImplemented
}

func (stmt *GetRowStmt) WithConfig(cfg *Config) *GetRowStmt {
	return stmt
}

type SelectStmt struct {
	commonStmt
}

func MustPrepareSelect(row interface{}, sql string) *SelectStmt {
	stmt, err := PrepareSelect(row, sql)
	if err != nil {
		panic(err)
	}
	return stmt
}

func PrepareSelect(row interface{}, sql string) (*SelectStmt, error) {
	return nil, errNotImplemented
}

func (stmt *SelectStmt) Select(db Queryer, dest interface{}, args ...interface{}) error {
	return errNotImplemented
}

func (stmt *SelectStmt) WithConfig(cfg *Config) *SelectStmt {
	return stmt
}

type commonStmt struct {
	err error
}

// String prints the SQL query associated with the statement.
func (stmt *commonStmt) String() string {
	return "not implemented"
}
<commit_msg>Stop panics due to not implemented errors.<commit_after>package sqlf

import (
	"errors"
)

var errNotImplemented = errors.New("not implemented")

type InsertRowStmt struct {
	commonStmt
}

func MustPrepareInsertRow(row interface{}, sql string) *InsertRowStmt {
	stmt, err := PrepareInsertRow(row, sql)
	if err != nil {
		panic(err)
	}
	return stmt
}

func PrepareInsertRow(row interface{}, sql string) (*InsertRowStmt, error) {
	return &InsertRowStmt{}, nil
}

func (stmt *InsertRowStmt) Exec(db Execer, row interface{}) error {
	return errNotImplemented
}

type UpdateRowStmt struct {
	commonStmt
}

func MustPrepareUpdateRow(row interface{}, sql string) *UpdateRowStmt {
	stmt, err := PrepareUpdateRow(row, sql)
	if err != nil {
		panic(err)
	}
	return stmt
}

func PrepareUpdateRow(row interface{}, sql string) (*UpdateRowStmt, error) {
	return &UpdateRowStmt{}, nil
}

func (stmt *UpdateRowStmt) Exec(db Execer, row interface{}) (int, error) {
	return 0, errNotImplemented
}

type GetRowStmt struct {
	commonStmt
}

func MustPrepareGetRow(row interface{}, sql string) *GetRowStmt {
	stmt, err := PrepareGetRow(row, sql)
	if err != nil {
		panic(err)
	}
	return stmt
}

func PrepareGetRow(row interface{}, sql string) (*GetRowStmt, error) {
	return &GetRowStmt{}, nil
}

func (stmt *GetRowStmt) Get(db Queryer, row interface{}) (int, error) {
	return 0, errNotImplemented
}

type SelectStmt struct {
	commonStmt
}

func MustPrepareSelect(row interface{}, sql string) *SelectStmt {
	stmt, err := PrepareSelect(row, sql)
	if err != nil {
		panic(err)
	}
	return stmt
}

func PrepareSelect(row interface{}, sql string) (*SelectStmt, error) {
	return &SelectStmt{}, nil
}

func (stmt *SelectStmt) Select(db Queryer, dest interface{}, args ...interface{}) error {
	return errNotImplemented
}

type commonStmt struct {
	err error
}

// String prints the SQL query associated with the statement.
func (stmt *commonStmt) String() string {
	return "not implemented"
}
<|endoftext|>


<commit_before>// Copyright © 2015 Steve Francia <spf@spf13.com>.
//
// 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 cmd

import (
	"fmt"
	"os"
	"path"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var (
	pkgName string

	initCmd = &cobra.Command{
		Use:     "init [name]",
		Aliases: []string{"initialize", "initialise", "create"},
		Short:   "Initialize a Cobra Application",
		Long: `Initialize (cobra init) will create a new application, with a license
and the appropriate structure for a Cobra-based CLI application.

  * If a name is provided, it will be created in the current directory;
  * If no name is provided, the current directory will be assumed;
  * If a relative path is provided, it will be created inside $GOPATH
    (e.g. github.com/spf13/hugo);
  * If an absolute path is provided, it will be created;
  * If the directory already exists but is empty, it will be used.

Init will not use an existing directory with contents.`,

		Run: func(cmd *cobra.Command, args []string) {

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

			if len(args) > 0 {
				if args[0] != "." {
					wd = fmt.Sprintf("%s/%s", wd, args[0])
				}
			}

			project := &Project{
				AbsolutePath: wd,
				PkgName:      pkgName,
				Legal:        getLicense(),
				Copyright:    copyrightLine(),
				Viper:        viper.GetBool("useViper"),
				AppName:      path.Base(pkgName),
			}

			if err := project.Create(); err != nil {
				er(err)
			}

			fmt.Printf("Your Cobra applicaton is ready at\n%s\n", project.AbsolutePath)
		},
	}
)

func init() {
	initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")
	initCmd.MarkFlagRequired("pkg-name")
}
<commit_msg>Fixed typo. (#1087)<commit_after>// Copyright © 2015 Steve Francia <spf@spf13.com>.
//
// 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 cmd

import (
	"fmt"
	"os"
	"path"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var (
	pkgName string

	initCmd = &cobra.Command{
		Use:     "init [name]",
		Aliases: []string{"initialize", "initialise", "create"},
		Short:   "Initialize a Cobra Application",
		Long: `Initialize (cobra init) will create a new application, with a license
and the appropriate structure for a Cobra-based CLI application.

  * If a name is provided, it will be created in the current directory;
  * If no name is provided, the current directory will be assumed;
  * If a relative path is provided, it will be created inside $GOPATH
    (e.g. github.com/spf13/hugo);
  * If an absolute path is provided, it will be created;
  * If the directory already exists but is empty, it will be used.

Init will not use an existing directory with contents.`,

		Run: func(cmd *cobra.Command, args []string) {

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

			if len(args) > 0 {
				if args[0] != "." {
					wd = fmt.Sprintf("%s/%s", wd, args[0])
				}
			}

			project := &Project{
				AbsolutePath: wd,
				PkgName:      pkgName,
				Legal:        getLicense(),
				Copyright:    copyrightLine(),
				Viper:        viper.GetBool("useViper"),
				AppName:      path.Base(pkgName),
			}

			if err := project.Create(); err != nil {
				er(err)
			}

			fmt.Printf("Your Cobra application is ready at\n%s\n", project.AbsolutePath)
		},
	}
)

func init() {
	initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")
	initCmd.MarkFlagRequired("pkg-name")
}
<|endoftext|>


<commit_before>package dockerlaunch

import (
	"bufio"
	"io"
	"os"
	"path"
	"strings"
	"syscall"

	log "github.com/Sirupsen/logrus"
	"github.com/rancher/docker-from-scratch/util"
)

const caCrtDir = "/etc/ssl/certs"
const caCrtName = "ca-certificates.crt"
const caCrtDefault = "/usr/etc/ssl/certs/ca-certificates.crt"

var (
	mounts [][]string = [][]string{
		{"devtmpfs", "/dev", "devtmpfs", ""},
		{"none", "/dev/pts", "devpts", ""},
		{"none", "/proc", "proc", ""},
		{"none", "/run", "tmpfs", ""},
		{"none", "/sys", "sysfs", ""},
		{"none", "/sys/fs/cgroup", "tmpfs", ""},
		{"none", "/var/run", "tmpfs", ""},
	}
)

func createMounts(mounts ...[]string) error {
	for _, mount := range mounts {
		log.Debugf("Mounting %s %s %s %s", mount[0], mount[1], mount[2], mount[3])
		err := util.Mount(mount[0], mount[1], mount[2], mount[3])
		if err != nil {
			return err
		}
	}

	return nil
}

func createDirs(dirs ...string) error {
	for _, dir := range dirs {
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			log.Debugf("Creating %s", dir)
			err = os.MkdirAll(dir, 0755)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func mountCgroups() error {
	f, err := os.Open("/proc/cgroups")
	if err != nil {
		return err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)

	for scanner.Scan() {
		cgroup := strings.SplitN(scanner.Text(), "\t", 2)[0]
		if cgroup == "" || cgroup[0] == '#' {
			continue
		}

		if err := mountCgroup(cgroup); err != nil {
			return err
		}
	}

	if err = scanner.Err(); err != nil {
		return err
	}

	log.Debug("Done mouting cgroupfs")
	return nil
}

func mountCgroup(cgroup string) error {
	if err := createDirs("/sys/fs/cgroup/" + cgroup); err != nil {
		return err
	}

	if err := createMounts([][]string{{"none", "/sys/fs/cgroup/" + cgroup, "cgroup", cgroup}}...); err != nil {
		return err
	}

	return nil
}

func execDocker(docker string, args []string) error {
	log.Debugf("Launching Docker %s %s", docker, args)
	return syscall.Exec(docker, append([]string{docker}, args...), os.Environ())
}

func copyFile(src, folder, name string) error {
	dst := path.Join(folder, name)
	if _, err := os.Stat(dst); err == nil {
		return nil
	}

	if err := createDirs(folder); err != nil {
		return err
	}

	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	return err
}

func createPasswd() error {
	if _, err := os.Stat("/etc/passwd"); err == nil {
		return nil
	}

	f, err := os.Create("/etc/passwd")
	if err != nil {
		return err
	}

	defer f.Close()

	_, err = f.Write([]byte("root:x:0:0:root:/root:/bin/bash\n"))
	return err
}

func LaunchDocker(docker string, args ...string) error {
	os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")

	if err := createPasswd(); err != nil {
		return err
	}

	if err := createDirs("/tmp", "/root/.ssh"); err != nil {
		return err
	}

	if err := createMounts(mounts...); err != nil {
		return err
	}

	if err := mountCgroups(); err != nil {
		return err
	}

	if err := copyFile(caCrtDefault, caCrtDir, caCrtName); err != nil {
		return err
	}

	return execDocker(docker, args)
}
<commit_msg>Mount and symlink based off of cgroup hierarchy<commit_after>package dockerlaunch

import (
	"bufio"
	"io"
	"os"
	"path"
	"strings"
	"syscall"

	log "github.com/Sirupsen/logrus"
	"github.com/rancher/docker-from-scratch/util"
)

const caCrtDir = "/etc/ssl/certs"
const caCrtName = "ca-certificates.crt"
const caCrtDefault = "/usr/etc/ssl/certs/ca-certificates.crt"

var (
	mounts [][]string = [][]string{
		{"devtmpfs", "/dev", "devtmpfs", ""},
		{"none", "/dev/pts", "devpts", ""},
		{"none", "/proc", "proc", ""},
		{"none", "/run", "tmpfs", ""},
		{"none", "/sys", "sysfs", ""},
		{"none", "/sys/fs/cgroup", "tmpfs", ""},
		{"none", "/var/run", "tmpfs", ""},
	}
)

func createMounts(mounts ...[]string) error {
	for _, mount := range mounts {
		log.Debugf("Mounting %s %s %s %s", mount[0], mount[1], mount[2], mount[3])
		err := util.Mount(mount[0], mount[1], mount[2], mount[3])
		if err != nil {
			return err
		}
	}

	return nil
}

func createDirs(dirs ...string) error {
	for _, dir := range dirs {
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			log.Debugf("Creating %s", dir)
			err = os.MkdirAll(dir, 0755)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func mountCgroups() error {
	f, err := os.Open("/proc/cgroups")
	if err != nil {
		return err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)

	hierarchies := make(map[string][]string)

	for scanner.Scan() {
		fields := strings.SplitN(scanner.Text(), "\t", 2)
		cgroup := fields[0]
		if cgroup == "" || cgroup[0] == '#' || len(fields) < 2 {
			continue
		}

		hierarchy := fields[1]
		hierarchies[hierarchy] = append(hierarchies[hierarchy], cgroup)
	}

	for _, hierarchy := range hierarchies {
		if err := mountCgroup(strings.Join(hierarchy, ",")); err != nil {
			return err
		}
	}

	if err = scanner.Err(); err != nil {
		return err
	}

	log.Debug("Done mouting cgroupfs")
	return nil
}

func createSymlink(src, dest string) error {
	if _, err := os.Stat(dest); os.IsNotExist(err) {
		log.Debugf("Symlinking %s => %s", src, dest)
		if err = os.Symlink(src, dest); err != nil {
			return err
		}
	}

	return nil
}

func mountCgroup(cgroup string) error {
	if err := createDirs("/sys/fs/cgroup/" + cgroup); err != nil {
		return err
	}

	if err := createMounts([][]string{{"none", "/sys/fs/cgroup/" + cgroup, "cgroup", cgroup}}...); err != nil {
		return err
	}

	parts := strings.Split(cgroup, ",")
	if len(parts) > 1 {
		for _, part := range parts {
			if err := createSymlink("/sys/fs/cgroup/"+cgroup, "/sys/fs/cgroup/"+part); err != nil {
				return err
			}
		}
	}

	return nil
}

func execDocker(docker string, args []string) error {
	log.Debugf("Launching Docker %s %s", docker, args)
	return syscall.Exec(docker, append([]string{docker}, args...), os.Environ())
}

func copyFile(src, folder, name string) error {
	dst := path.Join(folder, name)
	if _, err := os.Stat(dst); err == nil {
		return nil
	}

	if err := createDirs(folder); err != nil {
		return err
	}

	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	return err
}

func createPasswd() error {
	if _, err := os.Stat("/etc/passwd"); err == nil {
		return nil
	}

	f, err := os.Create("/etc/passwd")
	if err != nil {
		return err
	}

	defer f.Close()

	_, err = f.Write([]byte("root:x:0:0:root:/root:/bin/bash\n"))
	return err
}

func LaunchDocker(docker string, args ...string) error {
	os.Setenv("PATH", "/sbin:/usr/sbin:/usr/bin")

	if err := createPasswd(); err != nil {
		return err
	}

	if err := createDirs("/tmp", "/root/.ssh"); err != nil {
		return err
	}

	if err := createMounts(mounts...); err != nil {
		return err
	}

	if err := mountCgroups(); err != nil {
		return err
	}

	if err := copyFile(caCrtDefault, caCrtDir, caCrtName); err != nil {
		return err
	}

	return execDocker(docker, args)
}
<|endoftext|>