<commit_before>package main

import (
	"errors"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/gizak/termui"
	"github.com/kolo/xmlrpc"
	"github.com/spf13/viper"
)

var selector int

// AccountReturn contains fields for informations about the Gandi account
type AccountReturn struct {
	AverageCreditCost     float64   `xmlrpc:"average_credit_cost"`
	Credits               int       `xmlrpc:"credits"`
	CycleDay              int       `xmlrpc:"cycle_day"`
	DateCreditsExpiration time.Time `xmlrpc:"date_credits_expiration"`
	FullName              string    `xmlrpc:"fullname"`
	Handle                string    `xmlrpc:"handle"`
	ID                    int       `xmlrpc:"id"`
}

// DiskReturn contains fields for informations about the Disks
type DiskReturn struct {
	CanSnapshot   bool      `xmlrpc:"can_snapshot"`
	DatacenterID  int       `xmlrpc:"datacenter_id"`
	DateCreated   time.Time `xmlrpc:"date_created"`
	DateUpdated   time.Time `xmlrpc:"date_updated"`
	ID            int       `xmlrpc:"id"`
	IsBootDisk    bool      `xmlrpc:"is_boot_disk"`
	KernelVersion string    `xmlrpc:"kernel_version"`
	Label         string    `xmlrpc:"label"`
	Name          string    `xmlrpc:"name"`
	Size          int       `xmlrpc:"size"`
	State         string    `xmlrpc:"state"`
	TotalSize     int       `xmlrpc:"total_size"`
	Type          string    `xmlrpc:"type"`
	Visibility    string    `xmlrpc:"visibility"`
}

// VMReturn contains fields for informations about the virtual machines
type VMReturn struct {
	AiActive     int          `xmlrpc:"ai_active"`
	Console      int          `xmlrpc:"console"`
	ConsoleURL   string       `xmlrpc:"console_url"`
	Cores        int          `xmlrpc:"cores"`
	DatacenterID int          `xmlrpc:"datacenter_id"`
	DateCreated  time.Time    `xmlrpc:"date_created"`
	DateUpdated  time.Time    `xmlrpc:"date_updated"`
	Description  string       `xmlrpc:"description"`
	Disks        []DiskReturn `xmlrpc:"disks"`
	Farm         string       `xmlrpc:"farm"`
	FlexShares   int          `xmlrpc:"flex_shares"`
	Hostname     string       `xmlrpc:"hostname"`
	HVMState     string       `xmlrpc:"hvm_state"`
	ID           int          `xmlrpc:"id"`
	Memory       int          `xmlrpc:"memory"`
	State        string       `xmlrpc:"state"`
	VMmaxMemory  int          `xmlrpc:"vm_max_memory"`
}

// LoadAPI returns the api and apiKey according to the settings defined in the
// configuration file, respectively.
func LoadAPI() (api *xmlrpc.Client, apiKey string, err error) {
	viper.SetConfigName("bapu")

	homePath := os.Getenv("HOME")
	viper.AddConfigPath(homePath)
	viper.AddConfigPath("/usr/local/etc")
	viper.AddConfigPath("/etc")

	err = viper.ReadInConfig()
	if err != nil {
		return api, apiKey, err
	}

	production := viper.GetBool("production.enabled")
	if production {
		apiKey = viper.GetString("production.apiKey")
		api, err = xmlrpc.NewClient("https://rpc.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
	}

	development := viper.GetBool("development.enabled")
	if development {
		log.Println("Development Config found")
		api, err = xmlrpc.NewClient("https://rpc.ote.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
		apiKey = viper.GetString("development.apiKey")
	}

	if api == nil {
		return api, apiKey, errors.New("neither production nor development environment enabled in config")
	}

	return api, apiKey, nil
}

func serverList(list []VMReturn) (servers [][]string) {

	servers = append(servers, []string{
		"Selected",
		"Hostname",
		"Datacenter",
		"Cores",
		"Memory",
		"State",
	})

	for i, val := range list {
		s := ""
		if selector == i {
			s = "*"
		}
		servers = append(servers, []string{
			s,
			val.Hostname,
			strconv.Itoa(val.DatacenterID),
			strconv.Itoa(val.Cores),
			strconv.Itoa(val.Memory) + "MB",
			val.State,
		})
	}

	return servers
}

func main() {
	// Load API
	api, apiKey, err := LoadAPI()
	if err != nil {
		log.Fatal(err)
	}

	// initialize termui
	err = termui.Init()
	if err != nil {
		log.Fatal(err)
	}
	defer termui.Close()

	// Title
	uiTitle := termui.NewPar("Bapu -- Control your Gandi Machines")
	uiTitle.Border = false
	uiTitle.Height = 3
	uiTitle.TextFgColor = termui.ColorMagenta

	// Summary
	var hostingVMCount *int
	err = api.Call("hosting.vm.count", apiKey, &hostingVMCount)
	if err != nil {
		log.Fatal(err)
	}
	var hostingAccountInfo *AccountReturn
	err = api.Call("hosting.account.info", apiKey, &hostingAccountInfo)
	if err != nil {
		log.Fatal(err)
	}

	info := *hostingAccountInfo

	uiSummary := termui.NewPar("Owner: " + info.FullName + "    Virtual Machines: " + strconv.Itoa(*hostingVMCount) + "    Remaining Credit: " + strconv.Itoa(info.Credits) + ":::" + strconv.Itoa(selector))
	uiSummary.Height = 3
	uiSummary.Border = true
	uiSummary.BorderLabel = "Summary"
	uiSummary.TextFgColor = termui.ColorWhite

	// List instances
	var hostingVMList *[]VMReturn
	err = api.Call("hosting.vm.list", apiKey, &hostingVMList)
	if err != nil {
		log.Fatal(err)
	}

	list := *hostingVMList
	servers := serverList(list)

	uiTable := termui.NewTable()
	uiTable.Rows = servers
	uiTable.FgColor = termui.ColorWhite
	uiTable.BgColor = termui.ColorDefault
	uiTable.TextAlign = termui.AlignCenter
	uiTable.Seperator = false
	uiTable.Analysis()
	uiTable.SetSize()
	uiTable.BgColors[0] = termui.ColorWhite
	uiTable.FgColors[0] = termui.ColorBlack
	uiTable.Y = 20
	uiTable.X = 0
	uiTable.Border = false
	for i := 0; i < len(list); i++ {
		switch list[i].State {
		case "paused":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "running":
			uiTable.BgColors[i+1] = termui.ColorBlue
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "halted":
			uiTable.BgColors[i+1] = termui.ColorYellow
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "locked":
			uiTable.BgColors[i+1] = termui.ColorMagenta
			uiTable.FgColors[i+1] = termui.ColorGreen
		case "being_created":
			uiTable.BgColors[i+1] = termui.ColorWhite
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "deleted":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorRed
		}
	}

	// Commands
	uiCommands := termui.NewPar("<[S]tart>    <St[o]p>    <[R]eboot>")
	uiCommands.Height = 3
	uiCommands.Border = false
	uiCommands.BorderLabel = "Summary"
	uiCommands.TextFgColor = termui.ColorBlack
	uiCommands.TextBgColor = termui.ColorWhite

	// Create termui Grid system
	termui.Body.AddRows(
		termui.NewRow(
			termui.NewCol(12, 0, uiTitle),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiSummary),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiTable),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiCommands),
		),
	)

	// calculate layout
	termui.Body.Align()
	termui.Render(termui.Body)

	// Quit with q
	termui.Handle("/sys/kbd/q", func(termui.Event) {
		termui.StopLoop()
	})

	termui.Handle("/sys/kbd/<up>", func(termui.Event) {
		if selector > 0 {
			selector--
		}
		servers = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/sys/kbd/<down>", func(termui.Event) {
		if selector < len(list) {
			selector++
		}
		servers = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/timer/1s", func(e termui.Event) {
		t := e.Data.(termui.EvtTimer)
		// t is a EvtTimer
		if t.Count%2 == 0 {
			termui.Body.Align()
			termui.Render(termui.Body)
		}
	})

	termui.Loop()
}
<commit_msg>select VMs correctly<commit_after>package main

import (
	"errors"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/gizak/termui"
	"github.com/kolo/xmlrpc"
	"github.com/spf13/viper"
)

var selector int

// AccountReturn contains fields for informations about the Gandi account
type AccountReturn struct {
	AverageCreditCost     float64   `xmlrpc:"average_credit_cost"`
	Credits               int       `xmlrpc:"credits"`
	CycleDay              int       `xmlrpc:"cycle_day"`
	DateCreditsExpiration time.Time `xmlrpc:"date_credits_expiration"`
	FullName              string    `xmlrpc:"fullname"`
	Handle                string    `xmlrpc:"handle"`
	ID                    int       `xmlrpc:"id"`
}

// DiskReturn contains fields for informations about the Disks
type DiskReturn struct {
	CanSnapshot   bool      `xmlrpc:"can_snapshot"`
	DatacenterID  int       `xmlrpc:"datacenter_id"`
	DateCreated   time.Time `xmlrpc:"date_created"`
	DateUpdated   time.Time `xmlrpc:"date_updated"`
	ID            int       `xmlrpc:"id"`
	IsBootDisk    bool      `xmlrpc:"is_boot_disk"`
	KernelVersion string    `xmlrpc:"kernel_version"`
	Label         string    `xmlrpc:"label"`
	Name          string    `xmlrpc:"name"`
	Size          int       `xmlrpc:"size"`
	State         string    `xmlrpc:"state"`
	TotalSize     int       `xmlrpc:"total_size"`
	Type          string    `xmlrpc:"type"`
	Visibility    string    `xmlrpc:"visibility"`
}

// VMReturn contains fields for informations about the virtual machines
type VMReturn struct {
	AiActive     int          `xmlrpc:"ai_active"`
	Console      int          `xmlrpc:"console"`
	ConsoleURL   string       `xmlrpc:"console_url"`
	Cores        int          `xmlrpc:"cores"`
	DatacenterID int          `xmlrpc:"datacenter_id"`
	DateCreated  time.Time    `xmlrpc:"date_created"`
	DateUpdated  time.Time    `xmlrpc:"date_updated"`
	Description  string       `xmlrpc:"description"`
	Disks        []DiskReturn `xmlrpc:"disks"`
	Farm         string       `xmlrpc:"farm"`
	FlexShares   int          `xmlrpc:"flex_shares"`
	Hostname     string       `xmlrpc:"hostname"`
	HVMState     string       `xmlrpc:"hvm_state"`
	ID           int          `xmlrpc:"id"`
	Memory       int          `xmlrpc:"memory"`
	State        string       `xmlrpc:"state"`
	VMmaxMemory  int          `xmlrpc:"vm_max_memory"`
}

// LoadAPI returns the api and apiKey according to the settings defined in the
// configuration file, respectively.
func LoadAPI() (api *xmlrpc.Client, apiKey string, err error) {
	viper.SetConfigName("bapu")

	homePath := os.Getenv("HOME")
	viper.AddConfigPath(homePath)
	viper.AddConfigPath("/usr/local/etc")
	viper.AddConfigPath("/etc")

	err = viper.ReadInConfig()
	if err != nil {
		return api, apiKey, err
	}

	production := viper.GetBool("production.enabled")
	if production {
		apiKey = viper.GetString("production.apiKey")
		api, err = xmlrpc.NewClient("https://rpc.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
	}

	development := viper.GetBool("development.enabled")
	if development {
		log.Println("Development Config found")
		api, err = xmlrpc.NewClient("https://rpc.ote.gandi.net/xmlrpc/", nil)
		if err != nil {
			return api, apiKey, err
		}
		apiKey = viper.GetString("development.apiKey")
	}

	if api == nil {
		return api, apiKey, errors.New("neither production nor development environment enabled in config")
	}

	return api, apiKey, nil
}

func serverList(list []VMReturn) (servers [][]string) {

	servers = append(servers, []string{
		"Selected",
		"Hostname",
		"Datacenter",
		"Cores",
		"Memory",
		"State",
	})

	for i, val := range list {
		s := ""
		if selector == i {
			s = "*"
		}
		servers = append(servers, []string{
			s,
			val.Hostname,
			strconv.Itoa(val.DatacenterID),
			strconv.Itoa(val.Cores),
			strconv.Itoa(val.Memory) + "MB",
			val.State,
		})
	}

	return servers
}

func main() {
	// Load API
	api, apiKey, err := LoadAPI()
	if err != nil {
		log.Fatal(err)
	}

	// initialize termui
	err = termui.Init()
	if err != nil {
		log.Fatal(err)
	}
	defer termui.Close()

	// Title
	uiTitle := termui.NewPar("Bapu -- Control your Gandi Machines")
	uiTitle.Border = false
	uiTitle.Height = 3
	uiTitle.TextFgColor = termui.ColorMagenta

	// Summary
	var hostingVMCount *int
	err = api.Call("hosting.vm.count", apiKey, &hostingVMCount)
	if err != nil {
		log.Fatal(err)
	}
	var hostingAccountInfo *AccountReturn
	err = api.Call("hosting.account.info", apiKey, &hostingAccountInfo)
	if err != nil {
		log.Fatal(err)
	}

	info := *hostingAccountInfo

	uiSummary := termui.NewPar("Owner: " + info.FullName + "    Virtual Machines: " + strconv.Itoa(*hostingVMCount) + "    Remaining Credit: " + strconv.Itoa(info.Credits))
	uiSummary.Height = 3
	uiSummary.Border = true
	uiSummary.BorderLabel = "Summary"
	uiSummary.TextFgColor = termui.ColorWhite

	// List instances
	var hostingVMList *[]VMReturn
	err = api.Call("hosting.vm.list", apiKey, &hostingVMList)
	if err != nil {
		log.Fatal(err)
	}

	list := *hostingVMList

	uiTable := termui.NewTable()
	uiTable.Rows = serverList(list)
	uiTable.FgColor = termui.ColorWhite
	uiTable.BgColor = termui.ColorDefault
	uiTable.TextAlign = termui.AlignCenter
	uiTable.Seperator = false
	uiTable.Analysis()
	uiTable.SetSize()
	uiTable.BgColors[0] = termui.ColorWhite
	uiTable.FgColors[0] = termui.ColorBlack
	uiTable.Y = 20
	uiTable.X = 0
	uiTable.Border = false
	for i := 0; i < len(list); i++ {
		switch list[i].State {
		case "paused":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "running":
			uiTable.BgColors[i+1] = termui.ColorBlue
			uiTable.FgColors[i+1] = termui.ColorWhite
		case "halted":
			uiTable.BgColors[i+1] = termui.ColorYellow
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "locked":
			uiTable.BgColors[i+1] = termui.ColorMagenta
			uiTable.FgColors[i+1] = termui.ColorGreen
		case "being_created":
			uiTable.BgColors[i+1] = termui.ColorWhite
			uiTable.FgColors[i+1] = termui.ColorBlack
		case "deleted":
			uiTable.BgColors[i+1] = termui.ColorBlack
			uiTable.FgColors[i+1] = termui.ColorRed
		}
	}

	// Commands
	uiCommands := termui.NewPar("<[S]tart>    <St[o]p>    <[R]eboot>  Virtual Machine |   <[Q]uit>")
	uiCommands.Height = 3
	uiCommands.Border = false
	uiCommands.BorderLabel = "Summary"
	uiCommands.TextFgColor = termui.ColorBlack
	uiCommands.TextBgColor = termui.ColorWhite

	// Create termui Grid system
	termui.Body.AddRows(
		termui.NewRow(
			termui.NewCol(12, 0, uiTitle),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiSummary),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiTable),
		),
		termui.NewRow(
			termui.NewCol(12, 0, uiCommands),
		),
	)

	// calculate layout
	termui.Body.Align()
	termui.Render(termui.Body)

	// Quit with q
	termui.Handle("/sys/kbd/q", func(termui.Event) {
		termui.StopLoop()
	})

	termui.Handle("/sys/kbd/<up>", func(termui.Event) {
		if selector > 0 {
			selector--
		}
		uiTable.Rows = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/sys/kbd/<down>", func(termui.Event) {
		if selector < len(list)-1 {
			selector++
		}
		uiTable.Rows = serverList(list)
		termui.Render(termui.Body)
	})

	termui.Handle("/sys/kbd/s", func(termui.Event) {
		err = api.Call("hosting.vm.start", apiKey, list[selector].ID)
		if err != nil {
			log.Fatal(err)
		}
	})

	termui.Handle("/sys/kbd/o", func(termui.Event) {
		err = api.Call("hosting.vm.stop", apiKey, list[selector].ID)
		if err != nil {
			log.Fatal(err)
		}
	})

	termui.Handle("/sys/kbd/r", func(termui.Event) {
		err = api.Call("hosting.vm.reboot", apiKey, list[selector].ID)
		if err != nil {
			log.Fatal(err)
		}
	})

	termui.Handle("/timer/1s", func(e termui.Event) {
		t := e.Data.(termui.EvtTimer)
		// t is a EvtTimer
		if t.Count%2 == 0 {
			termui.Body.Align()
			termui.Render(termui.Body)
		}
	})

	termui.Loop()
}
<|endoftext|>


<commit_before>// Copyright 2012 Dmitry Chestnykh. 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

//TODO(dchest): implement flags maxmem, maxmemfrac, maxtime.

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"log"
	"os"

	"code.google.com/p/go.crypto/scrypt"
)

const (
	headerMagic   = "scrypt"
	headerVersion = 0
)

type params struct {
	logN byte
	r, p int
	salt []byte
}

func deriveKeys(password []byte, p *params) (keyEnc, keyHmac []byte, err error) {
	N := int(1 << uint64(p.logN))
	k, err := scrypt.Key(password, p.salt, N, p.r, p.p, 64)
	if err != nil {
		return
	}
	keyEnc = k[0:32]
	keyHmac = k[32:64]
	return
}

func clearBytes(b []byte) {
	for i := range b {
		b[i] = 0
	}
}

func scanLine(r *bufio.Reader, msg string) ([]byte, error) {
	fmt.Printf(msg)
	line, err := r.ReadBytes('\n')
	if err != nil {
		return nil, err
	}
	return bytes.TrimRight(line, "\n\r"), nil
}

func askForPassword(confirm bool) (password []byte, err error) {
	//TODO(dchest): turn off terminal echo.
	r := bufio.NewReader(os.Stdin)
	for {
		password, err = scanLine(r, "Enter passphrase: ")
		if err != nil {
			return
		}
		if !confirm {
			break
		}
		var confirmation []byte
		confirmation, err = scanLine(r, "Confirm passphrase: ")
		if err != nil {
			return
		}
		if len(password) == 0 {
			fmt.Println("Empty password, please try again.")
			clearBytes(confirmation)
			continue
		}
		if bytes.Equal(password, confirmation) {
			clearBytes(confirmation)
			break
		}
		fmt.Println("Passphrases mismatch, please try again.")
		clearBytes(confirmation)
		clearBytes(password)
	}
	return
}

func usage() {
	fmt.Printf("Usage: %s {enc | dec} infile [outfile]\n", os.Args[0])
	os.Exit(1)
}

func main() {
	log.SetFlags(0)
	flag.Parse()
	// Check arguments.
	if flag.NArg() < 2 || flag.Arg(0) != "enc" && flag.Arg(0) != "dec" {
		usage()
	}
	// Ask for password.
	password, err := askForPassword(flag.Arg(0) == "enc")
	if err != nil {
		log.Fatalf("%s", err)
	}
	// Function fatal will clean password, output message and exit.
	fatal := func(msg string, args ...interface{}) {
		clearBytes(password)
		log.Fatalf(msg, args...)
	}
	// Defer cleaning of password for normal exit.
	defer func() {
		clearBytes(password)
	}()
	// Open input file.
	in, err := os.Open(flag.Arg(1))
	if err != nil {
		fatal("%s", err)
	}
	defer in.Close()
	// Open output file.
	var out *os.File
	if flag.NArg() < 3 {
		out = os.Stdout
	} else {
		out, err = os.Create(flag.Arg(2))
		if err != nil {
			fatal("create: %s", err)
		}
		defer func() {
			if err := out.Sync(); err != nil {
				log.Printf("fsync: %s", err)
			}
			if err := out.Close(); err != nil {
				fatal("close: %s", err)
			}
		}()
	}
	// Encrypt/decrypt.
	switch flag.Arg(0) {
	case "enc":
		if err := encrypt(in, out, password); err != nil {
			fatal("decrypt: %s", err)
		}
	case "dec":
		if err := decrypt(in, out, password); err != nil {
			fatal("decrypt: %s", err)
		}
	}
}
<commit_msg>If not input file given, read from stdin.<commit_after>// Copyright 2012 Dmitry Chestnykh. 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

//TODO(dchest): implement flags maxmem, maxmemfrac, maxtime.

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"log"
	"os"

	"code.google.com/p/go.crypto/scrypt"
)

const (
	headerMagic   = "scrypt"
	headerVersion = 0
)

type params struct {
	logN byte
	r, p int
	salt []byte
}

func deriveKeys(password []byte, p *params) (keyEnc, keyHmac []byte, err error) {
	N := int(1 << uint64(p.logN))
	k, err := scrypt.Key(password, p.salt, N, p.r, p.p, 64)
	if err != nil {
		return
	}
	keyEnc = k[0:32]
	keyHmac = k[32:64]
	return
}

func clearBytes(b []byte) {
	for i := range b {
		b[i] = 0
	}
}

func scanLine(r *bufio.Reader, msg string) ([]byte, error) {
	fmt.Printf(msg)
	line, err := r.ReadBytes('\n')
	if err != nil {
		return nil, err
	}
	return bytes.TrimRight(line, "\n\r"), nil
}

func askForPassword(confirm bool) (password []byte, err error) {
	//TODO(dchest): turn off terminal echo.
	r := bufio.NewReader(os.Stdin)
	for {
		password, err = scanLine(r, "Enter passphrase: ")
		if err != nil {
			return
		}
		if !confirm {
			break
		}
		var confirmation []byte
		confirmation, err = scanLine(r, "Confirm passphrase: ")
		if err != nil {
			return
		}
		if len(password) == 0 {
			fmt.Println("Empty password, please try again.")
			clearBytes(confirmation)
			continue
		}
		if bytes.Equal(password, confirmation) {
			clearBytes(confirmation)
			break
		}
		fmt.Println("Passphrases mismatch, please try again.")
		clearBytes(confirmation)
		clearBytes(password)
	}
	return
}

func usage() {
	fmt.Printf("Usage: %s {enc | dec} [infile] [outfile]\n", os.Args[0])
	os.Exit(1)
}

func main() {
	log.SetFlags(0)
	flag.Parse()
	// Check arguments.
	if flag.NArg() < 1 || flag.Arg(0) != "enc" && flag.Arg(0) != "dec" {
		usage()
	}
	// Ask for password.
	password, err := askForPassword(flag.Arg(0) == "enc")
	if err != nil {
		log.Fatalf("%s", err)
	}
	// Function fatal will clean password, output message and exit.
	fatal := func(msg string, args ...interface{}) {
		clearBytes(password)
		log.Fatalf(msg, args...)
	}
	// Defer cleaning of password for normal exit.
	defer func() {
		clearBytes(password)
	}()
	// Open input file.
	var in, out *os.File
	if flag.NArg() < 2 {
		in = os.Stdin
	} else {
		in, err := os.Open(flag.Arg(1))
		if err != nil {
			fatal("%s", err)
		}
		defer in.Close()
	}
	// Open output file.
	if flag.NArg() < 3 {
		out = os.Stdout
	} else {
		out, err = os.Create(flag.Arg(2))
		if err != nil {
			fatal("create: %s", err)
		}
		defer func() {
			if err := out.Sync(); err != nil {
				log.Printf("fsync: %s", err)
			}
			if err := out.Close(); err != nil {
				fatal("close: %s", err)
			}
		}()
	}
	// Encrypt/decrypt.
	switch flag.Arg(0) {
	case "enc":
		if err := encrypt(in, out, password); err != nil {
			fatal("decrypt: %s", err)
		}
	case "dec":
		if err := decrypt(in, out, password); err != nil {
			fatal("decrypt: %s", err)
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io"
	"math"
	"os"

	"github.com/go-hep/hepmc"
	"github.com/go-hep/lhef"
)

var (
	ifname = flag.String("i", "", "path to LHEF input file (default: STDIN)")
	ofname = flag.String("o", "", "path to HEPMC output file (default: STDOUT)")

	// in case IDWTUP == +/-4, one has to keep track of the accumulated
	// weights and event numbers to evaluate the cross section on-the-fly.
	// The last evaluation is the one used.
	// Better to be sure that crossSection() is never used to fill the
	// histograms, but only in the finalization stage, by reweighting the
	// histograms with crossSection()/sumOfWeights()
	acc_weight         = 0.0
	acc_weight_squared = 0.0
	evt_nbr            = 0
)

func main() {
	flag.Parse()

	var r io.Reader
	if *ifname == "" {
		r = os.Stdin
	} else {
		f, err := os.Open(*ifname)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error: %v\n", err)
			os.Exit(1)
		}
		r = f
		defer f.Close()
	}

	var w io.Writer
	if *ofname == "" {
		w = os.Stdout
	} else {
		f, err := os.Create(*ofname)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error: %v\n", err)
			os.Exit(1)
		}
		w = f
		defer f.Close()
	}

	dec, err := lhef.NewDecoder(r)
	if err != nil {
		fmt.Fprintf(os.Stderr, "**error: %v\n", err)
		os.Exit(1)
	}

	enc := hepmc.NewEncoder(w)
	if enc == nil {
		fmt.Fprintf(os.Stderr, "**error: nil hepmc.Encoder\n")
		os.Exit(1)
	}
	defer enc.Close()

	for ievt := 0; ; ievt++ {
		lhevt, err := dec.Decode()
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
		}

		evt := hepmc.Event{
			EventNumber: ievt + 1,
			Particles:   make(map[int]*hepmc.Particle),
			Vertices:    make(map[int]*hepmc.Vertex),
			Weights:     hepmc.NewWeights(),
		}

		// define the units
		evt.MomentumUnit = hepmc.GEV
		evt.LengthUnit = hepmc.MM

		weight := lhevt.XWGTUP
		evt.Weights.Add("0", weight)

		xsecval := -1.0
		xsecerr := -1.0
		switch math.Abs(float64(dec.Run.IDWTUP)) {
		case 3:
			xsecval = dec.Run.XSECUP[0]
			xsecerr = dec.Run.XSECUP[1]

		case 4:
			acc_weight += weight
			acc_weight_squared += weight * weight
			evt_nbr += 1
			xsecval = acc_weight / float64(evt_nbr)
			xsecerr2 := (acc_weight_squared/float64(evt_nbr) - xsecval*xsecval) / float64(evt_nbr)

			if xsecerr2 < 0 {
				fmt.Fprintf(os.Stderr, "WARNING: xsecerr^2 < 0. forcing to zero. (%f)\n", xsecerr2)
				xsecerr2 = 0.
			}
			xsecerr = math.Sqrt(xsecerr2)

		default:
			fmt.Fprintf(
				os.Stderr,
				"**error: IDWTUP=%v value not handled yet.\n",
				dec.Run.IDWTUP,
			)
			os.Exit(1)
		}

		evt.CrossSection = &hepmc.CrossSection{Value: xsecval, Error: xsecerr}
		p1 := hepmc.Particle{
			Momentum: hepmc.FourVector{
				0, 0,
				dec.Run.EBMUP[0],
				dec.Run.EBMUP[0],
			},
			PdgId:   dec.Run.IDBMUP[0],
			Status:  4,
			Barcode: 1,
		}
		p2 := hepmc.Particle{
			Momentum: hepmc.FourVector{
				0, 0,
				dec.Run.EBMUP[1],
				dec.Run.EBMUP[1],
			},
			PdgId:   dec.Run.IDBMUP[1],
			Status:  4,
			Barcode: 2,
		}
		vtx := hepmc.Vertex{
			Barcode: -1,
		}
		vtx.AddParticleIn(&p1)
		vtx.AddParticleIn(&p2)
		evt.Beams[0] = &p1
		evt.Beams[1] = &p2

		imax := int(lhevt.NUP)
		for i := 0; i < imax; i++ {
			if lhevt.ISTUP[i] != 1 {
				continue
			}
			vtx.AddParticleOut(&hepmc.Particle{
				Momentum: hepmc.FourVector{
					lhevt.PUP[i][0],
					lhevt.PUP[i][1],
					lhevt.PUP[i][2],
					lhevt.PUP[i][3],
				},
				GeneratedMass: lhevt.PUP[i][4],
				PdgId:         lhevt.IDUP[i],
				Status:        1,
				Barcode:       3 + i,
			})
		}
		err = evt.AddVertex(&vtx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
			os.Exit(1)
		}

		//fmt.Fprintf(os.Stderr, "nparts: %v\nnverts: %v\n", len(evt.Particles), len(evt.Vertices))

		err = enc.Encode(&evt)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
			os.Exit(1)
		}
	}
}

// EOF
<commit_msg>main: add sanity checks<commit_after>package main

import (
	"flag"
	"fmt"
	"io"
	"math"
	"os"

	"github.com/go-hep/hepmc"
	"github.com/go-hep/lhef"
)

var (
	ifname = flag.String("i", "", "path to LHEF input file (default: STDIN)")
	ofname = flag.String("o", "", "path to HEPMC output file (default: STDOUT)")

	// in case IDWTUP == +/-4, one has to keep track of the accumulated
	// weights and event numbers to evaluate the cross section on-the-fly.
	// The last evaluation is the one used.
	// Better to be sure that crossSection() is never used to fill the
	// histograms, but only in the finalization stage, by reweighting the
	// histograms with crossSection()/sumOfWeights()
	acc_weight         = 0.0
	acc_weight_squared = 0.0
	evt_nbr            = 0
)

func main() {
	flag.Parse()

	var r io.Reader
	if *ifname == "" {
		r = os.Stdin
	} else {
		f, err := os.Open(*ifname)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error: %v\n", err)
			os.Exit(1)
		}
		r = f
		defer f.Close()
	}

	var w io.Writer
	if *ofname == "" {
		w = os.Stdout
	} else {
		f, err := os.Create(*ofname)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error: %v\n", err)
			os.Exit(1)
		}
		w = f
		defer f.Close()
	}

	dec, err := lhef.NewDecoder(r)
	if err != nil {
		fmt.Fprintf(os.Stderr, "**error: %v\n", err)
		os.Exit(1)
	}

	enc := hepmc.NewEncoder(w)
	if enc == nil {
		fmt.Fprintf(os.Stderr, "**error: nil hepmc.Encoder\n")
		os.Exit(1)
	}
	defer enc.Close()

	for ievt := 0; ; ievt++ {
		lhevt, err := dec.Decode()
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
		}

		evt := hepmc.Event{
			EventNumber: ievt + 1,
			Particles:   make(map[int]*hepmc.Particle),
			Vertices:    make(map[int]*hepmc.Vertex),
			Weights:     hepmc.NewWeights(),
		}

		// define the units
		evt.MomentumUnit = hepmc.GEV
		evt.LengthUnit = hepmc.MM

		weight := lhevt.XWGTUP
		evt.Weights.Add("0", weight)

		xsecval := -1.0
		xsecerr := -1.0
		switch math.Abs(float64(dec.Run.IDWTUP)) {
		case 3:
			xsecval = dec.Run.XSECUP[0]
			xsecerr = dec.Run.XSECUP[1]

		case 4:
			acc_weight += weight
			acc_weight_squared += weight * weight
			evt_nbr += 1
			xsecval = acc_weight / float64(evt_nbr)
			xsecerr2 := (acc_weight_squared/float64(evt_nbr) - xsecval*xsecval) / float64(evt_nbr)

			if xsecerr2 < 0 {
				fmt.Fprintf(os.Stderr, "WARNING: xsecerr^2 < 0. forcing to zero. (%f)\n", xsecerr2)
				xsecerr2 = 0.
			}
			xsecerr = math.Sqrt(xsecerr2)

		default:
			fmt.Fprintf(
				os.Stderr,
				"**error: IDWTUP=%v value not handled yet.\n",
				dec.Run.IDWTUP,
			)
			os.Exit(1)
		}

		evt.CrossSection = &hepmc.CrossSection{Value: xsecval, Error: xsecerr}
		vtx := hepmc.Vertex{
			Event:   &evt,
			Barcode: -1,
		}
		p1 := hepmc.Particle{
			Momentum: hepmc.FourVector{
				0, 0,
				dec.Run.EBMUP[0],
				dec.Run.EBMUP[0],
			},
			PdgId:   dec.Run.IDBMUP[0],
			Status:  4,
			Barcode: 1,
		}
		p2 := hepmc.Particle{
			Momentum: hepmc.FourVector{
				0, 0,
				dec.Run.EBMUP[1],
				dec.Run.EBMUP[1],
			},
			PdgId:   dec.Run.IDBMUP[1],
			Status:  4,
			Barcode: 2,
		}
		err = vtx.AddParticleIn(&p1)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
			os.Exit(1)
		}
		err = vtx.AddParticleIn(&p2)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
			os.Exit(1)
		}
		evt.Beams[0] = &p1
		evt.Beams[1] = &p2

		nmax := 2
		imax := int(lhevt.NUP)
		for i := 0; i < imax; i++ {
			if lhevt.ISTUP[i] != 1 {
				continue
			}
			nmax += 1
			vtx.AddParticleOut(&hepmc.Particle{
				Momentum: hepmc.FourVector{
					lhevt.PUP[i][0],
					lhevt.PUP[i][1],
					lhevt.PUP[i][2],
					lhevt.PUP[i][3],
				},
				GeneratedMass: lhevt.PUP[i][4],
				PdgId:         lhevt.IDUP[i],
				Status:        1,
				Barcode:       3 + i,
			})
		}
		err = evt.AddVertex(&vtx)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
			os.Exit(1)
		}

		nparts := len(evt.Particles)
		if nmax != nparts {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: LHEF/HEPMC inconsistency (LHEF particles: %d, HEPMC particles: %d)\n", ievt, nmax, nparts)
			for _, p := range evt.Particles {
				fmt.Fprintf(os.Stderr, "part: %v\n", p)
			}
			fmt.Fprintf(os.Stderr, "p1: %v\n", p1)
			fmt.Fprintf(os.Stderr, "p2: %v\n", p2)
			os.Exit(1)
		}
		if len(evt.Vertices) != 1 {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: inconsistent number of vertices in HEPMC (got %d, expected 1)\n", ievt, len(evt.Vertices))
			os.Exit(1)
		}
		//fmt.Fprintf(os.Stderr, "nparts: %v\nnverts: %v\n", len(evt.Particles), len(evt.Vertices))

		err = enc.Encode(&evt)
		if err != nil {
			fmt.Fprintf(os.Stderr, "**error at evt #%d: %v\n", ievt, err)
			os.Exit(1)
		}
	}
}

// EOF
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	"github.com/go-ini/ini"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/user"
	"strings"
)

//Puerto donde escuchar
const PORT = "8998"

//TODO: Se debe parsear el enum de los comandos de tal forma que no sea necesario tener los valores harcodeados

//TODO: Por el momento suponemos que los pipes estan en /tmp
//Config por defecto, estaría bien usar swig para reusar la clase del daemon
//const CONFIG_FILE = "~/.config/player++/daemon.conf"

//Page contiene datos de la página
type Page struct {
	Title   string
	Request string
}

type Options struct {
	DaemonPipe  string
	ClientPipe  string
	MusicFolder string
	AutoStart   bool
	PidFile     string
	DbFile      string
}

var opt Options

const templatesPath = "./templates/"

var templates = template.Must(template.ParseGlob(templatesPath + "[a-z]*"))

//RenderTemplate renderiza la template con el texto adecuado
func RenderTemplate(w http.ResponseWriter, tmpl string, title string, r interface{}) {
	var err error
	switch request := r.(type) {
	case string:
		err = templates.ExecuteTemplate(w, tmpl, &Page{title, request})
	case error:
		//TODO: Si es un error se imprima en otro formato
		err = templates.ExecuteTemplate(w, tmpl, &Page{title, request.Error()})
	default:
		log.Print("Strange error ocurred")
	}

	if err != nil {
		log.Print("ExecuteTemplate: ", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// RootHandler muestra el index
func RootHandler(w http.ResponseWriter, r *http.Request) {
	RenderTemplate(w, "index", "index", "")
}

func NextHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{2}, 0666)
	if err != nil {
		panic(err)
	}
	RenderTemplate(w, "index", "index", "")
}

func PrevHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{3}, 0666)
	if err != nil {
		panic(err)
	}
	RenderTemplate(w, "index", "index", "")
}

func PauseHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{4}, 0666)
	if err != nil {
		panic(err)
	}
	RenderTemplate(w, "index", "index", "")
}

func GetVolumeHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{16}, 0666)
	if err != nil {
		panic(err)
	}

	f, err := os.Open(opt.DaemonPipe)
	if err != nil {
		panic(err)
	}

	reader := bufio.NewReader(f)
	line, err := reader.ReadString('\n')
	if err != nil {
		panic(err)
	}
	f.Close()
	fmt.Fprint(w, line)
}

func SetVolumeHandler(w http.ResponseWriter, r *http.Request) {
	urlPart := strings.Split(r.URL.Path, "/")
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{15}, 0666)
	if err != nil {
		panic(err)
	}
	err = ioutil.WriteFile(opt.DaemonPipe, []byte(urlPart[2]+"\n"), 0666)
	if err != nil {
		panic(err)
	}
}

func Expand(path string) string {
	usr, err := user.Current()
	if err != nil {
		panic(err)
	}
	return strings.Replace(path, "~", usr.HomeDir, 1)
}

func LoadConfig() {
	cfg, err := ini.Load(Expand("~/.config/player++/daemon.conf"))
	if err != nil {
		panic(err)
	}

	cfg.NameMapper = ini.TitleUnderscore
	err = cfg.MapTo(&opt)
	if err != nil {
		panic(err)
	}
	opt.DaemonPipe = Expand(opt.DaemonPipe)
	opt.ClientPipe = Expand(opt.ClientPipe)
	opt.MusicFolder = Expand(opt.MusicFolder)
	opt.PidFile = Expand(opt.PidFile)
	opt.DbFile = Expand(opt.DbFile)
}

func main() {
	LoadConfig()

	http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
	http.HandleFunc("/", RootHandler)
	http.HandleFunc("/next/", NextHandler)
	http.HandleFunc("/prev/", PrevHandler)
	http.HandleFunc("/pause/", PauseHandler)
	http.HandleFunc("/getvolume/", GetVolumeHandler)
	http.HandleFunc("/setvolume/", SetVolumeHandler)

	log.Print("Escuchando en el puerto " + PORT)
	http.ListenAndServe(":"+PORT, nil)
}
<commit_msg>bug fix<commit_after>package main

import (
	"bufio"
	"fmt"
	"github.com/go-ini/ini"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/user"
	"strings"
)

//Puerto donde escuchar
const PORT = "8998"

//TODO: Se debe parsear el enum de los comandos de tal forma que no sea necesario tener los valores harcodeados

//TODO: Por el momento suponemos que los pipes estan en /tmp
//Config por defecto, estaría bien usar swig para reusar la clase del daemon
//const CONFIG_FILE = "~/.config/player++/daemon.conf"

//Page contiene datos de la página
type Page struct {
	Title   string
	Request string
}

type Options struct {
	DaemonPipe  string
	ClientPipe  string
	MusicFolder string
	AutoStart   bool
	PidFile     string
	DbFile      string
}

var opt Options

const templatesPath = "./templates/"

var templates = template.Must(template.ParseGlob(templatesPath + "[a-z]*"))

//RenderTemplate renderiza la template con el texto adecuado
func RenderTemplate(w http.ResponseWriter, tmpl string, title string, r interface{}) {
	var err error
	switch request := r.(type) {
	case string:
		err = templates.ExecuteTemplate(w, tmpl, &Page{title, request})
	case error:
		//TODO: Si es un error se imprima en otro formato
		err = templates.ExecuteTemplate(w, tmpl, &Page{title, request.Error()})
	default:
		log.Print("Strange error ocurred")
	}

	if err != nil {
		log.Print("ExecuteTemplate: ", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

// RootHandler muestra el index
func RootHandler(w http.ResponseWriter, r *http.Request) {
	RenderTemplate(w, "index", "index", "")
}

func NextHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{2}, 0666)
	if err != nil {
		panic(err)
	}
	RenderTemplate(w, "index", "index", "")
}

func PrevHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{3}, 0666)
	if err != nil {
		panic(err)
	}
	RenderTemplate(w, "index", "index", "")
}

func PauseHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{4}, 0666)
	if err != nil {
		panic(err)
	}
	RenderTemplate(w, "index", "index", "")
}

func GetVolumeHandler(w http.ResponseWriter, r *http.Request) {
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{16}, 0666)
	if err != nil {
		panic(err)
	}

	f, err := os.Open(opt.ClientPipe)
	if err != nil {
		panic(err)
	}

	reader := bufio.NewReader(f)
	line, err := reader.ReadString('\n')
	if err != nil {
		panic(err)
	}
	f.Close()
	fmt.Fprint(w, line)
}

func SetVolumeHandler(w http.ResponseWriter, r *http.Request) {
	urlPart := strings.Split(r.URL.Path, "/")
	err := ioutil.WriteFile(opt.DaemonPipe, []byte{15}, 0666)
	if err != nil {
		panic(err)
	}
	err = ioutil.WriteFile(opt.DaemonPipe, []byte(urlPart[2]+"\n"), 0666)
	if err != nil {
		panic(err)
	}
}

func Expand(path string) string {
	usr, err := user.Current()
	if err != nil {
		panic(err)
	}
	return strings.Replace(path, "~", usr.HomeDir, 1)
}

func LoadConfig() {
	cfg, err := ini.Load(Expand("~/.config/player++/daemon.conf"))
	if err != nil {
		panic(err)
	}

	cfg.NameMapper = ini.TitleUnderscore
	err = cfg.MapTo(&opt)
	if err != nil {
		panic(err)
	}
	opt.DaemonPipe = Expand(opt.DaemonPipe)
	opt.ClientPipe = Expand(opt.ClientPipe)
	opt.MusicFolder = Expand(opt.MusicFolder)
	opt.PidFile = Expand(opt.PidFile)
	opt.DbFile = Expand(opt.DbFile)
}

func main() {
	LoadConfig()

	http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
	http.HandleFunc("/", RootHandler)
	http.HandleFunc("/next/", NextHandler)
	http.HandleFunc("/prev/", PrevHandler)
	http.HandleFunc("/pause/", PauseHandler)
	http.HandleFunc("/getvolume/", GetVolumeHandler)
	http.HandleFunc("/setvolume/", SetVolumeHandler)

	log.Print("Escuchando en el puerto " + PORT)
	http.ListenAndServe(":"+PORT, nil)
}
<|endoftext|>


<commit_before>/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"flag"
	"os"

	"k8s.io/klog/v2"

	genericapiserver "k8s.io/apiserver/pkg/server"
	"k8s.io/component-base/logs"
	"k8s.io/kube-aggregator/pkg/cmd/server"

	// force compilation of packages we'll later rely upon
	_ "k8s.io/kube-aggregator/pkg/apis/apiregistration/install"
	_ "k8s.io/kube-aggregator/pkg/apis/apiregistration/validation"
	_ "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
	_ "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1"
	_ "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1beta1"
)

func main() {
	logs.InitLogs()
	defer logs.FlushLogs()

	stopCh := genericapiserver.SetupSignalHandler()
	options := server.NewDefaultOptions(os.Stdout, os.Stderr)
	cmd := server.NewCommandStartAggregator(options, stopCh)
	cmd.Flags().AddGoFlagSet(flag.CommandLine)
	if err := cmd.Execute(); err != nil {
		klog.Fatal(err)
	}
}
<commit_msg>initialize logging after flag parsing<commit_after>/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"os"

	genericapiserver "k8s.io/apiserver/pkg/server"
	"k8s.io/component-base/cli"
	"k8s.io/kube-aggregator/pkg/cmd/server"

	// force compilation of packages we'll later rely upon
	_ "k8s.io/kube-aggregator/pkg/apis/apiregistration/install"
	_ "k8s.io/kube-aggregator/pkg/apis/apiregistration/validation"
	_ "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
	_ "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1"
	_ "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1beta1"
)

func main() {
	stopCh := genericapiserver.SetupSignalHandler()
	options := server.NewDefaultOptions(os.Stdout, os.Stderr)
	cmd := server.NewCommandStartAggregator(options, stopCh)
	code := cli.Run(cmd)
	os.Exit(code)
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/rand"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"

	"golang.org/x/crypto/nacl/box"
)

func newNonce() ([24]byte, error) {
	var nonce [24]byte
	n, err := rand.Read(nonce[:])

	if err != nil {
		return nonce, err
	}

	if n != 24 {
		return nonce, errors.New("Not enough bytes read for nonce")
	}

	return nonce, nil
}

type secureReader struct {
	wrappedReader io.Reader
	priv, pub     *[32]byte
}

// decrypt
func (r secureReader) Read(p []byte) (int, error) {
	encryptedMessage := make([]byte, len(p))
	n, err := r.wrappedReader.Read(encryptedMessage)

	if err != nil {
		return n, err
	}

	// strip off the nonce
	// and any extra space at the end of the buffer
	nonceSlice := encryptedMessage[:24]
	encryptedMessage = encryptedMessage[24:n]

	// convert the slice to an array
	var nonce [24]byte
	copy(nonce[:], nonceSlice)

	decryptedMessage, auth := box.Open(nil, encryptedMessage, &nonce, r.pub, r.priv)
	// if authentication failed, output bottom
	if !auth {
		return 0, errors.New("Decrypt error")
	}

	if len(decryptedMessage) > len(p) {
		return 0, errors.New("Decrypt error")
	}

	bytesWritten := copy(p, decryptedMessage)

	return bytesWritten, nil
}

type secureWriter struct {
	wrappedWriter io.Writer
	priv, pub     *[32]byte
}

// encrypt
func (w secureWriter) Write(p []byte) (int, error) {
	nonce, err := newNonce()

	if err != nil {
		return 0, err
	}

	encryptedMessage := box.Seal(nil, p, &nonce, w.pub, w.priv)
	// tack the nonce onto the encrypted message
	encWithNonce := append(nonce[:], encryptedMessage...)

	n, err := w.wrappedWriter.Write(encWithNonce)

	return n, err
}

// NewSecureReader instantiates a new SecureReader
func NewSecureReader(r io.Reader, priv, pub *[32]byte) io.Reader {
	return secureReader{r, priv, pub}
}

// NewSecureWriter instantiates a new SecureWriter
func NewSecureWriter(w io.Writer, priv, pub *[32]byte) io.Writer {
	return secureWriter{w, priv, pub}
}

// Dial generates a private/public key pair,
// connects to the server, perform the handshake
// and return a reader/writer.
func Dial(addr string) (io.ReadWriteCloser, error) {
	return nil, nil
}

// Serve starts a secure echo server on the given listener.
func Serve(l net.Listener) error {
	return nil
}

func main() {
	port := flag.Int("l", 0, "Listen mode. Specify port")
	flag.Parse()

	// Server mode
	if *port != 0 {
		l, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
		if err != nil {
			log.Fatal(err)
		}
		defer l.Close()
		log.Fatal(Serve(l))
	}

	// Client mode
	if len(os.Args) != 3 {
		log.Fatalf("Usage: %s <port> <message>", os.Args[0])
	}
	conn, err := Dial("localhost:" + os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	if _, err := conn.Write([]byte(os.Args[2])); err != nil {
		log.Fatal(err)
	}
	buf := make([]byte, len(os.Args[2]))
	n, err := conn.Read(buf)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", buf[:n])
}
<commit_msg>all tests passing<commit_after>package main

import (
	"crypto/rand"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"

	"golang.org/x/crypto/nacl/box"
)

func newNonce() ([24]byte, error) {
	var nonce [24]byte
	n, err := rand.Read(nonce[:])

	if err != nil {
		return nonce, err
	}

	if n != 24 {
		return nonce, errors.New("Not enough bytes read for nonce")
	}

	return nonce, nil
}

type secureReader struct {
	wrappedReader io.Reader
	priv, pub     *[32]byte
}

// decrypt
func (r secureReader) Read(p []byte) (int, error) {
	encryptedMessage := make([]byte, len(p))
	n, err := r.wrappedReader.Read(encryptedMessage)

	if err != nil {
		return n, err
	}

	// strip off the nonce
	// and any extra space at the end of the buffer
	nonceSlice := encryptedMessage[:24]
	encryptedMessage = encryptedMessage[24:n]

	// convert the slice to an array
	var nonce [24]byte
	copy(nonce[:], nonceSlice)

	decryptedMessage, auth := box.Open(nil, encryptedMessage, &nonce, r.pub, r.priv)
	// if authentication failed, output bottom
	if !auth {
		return 0, errors.New("Decrypt error")
	}

	if len(decryptedMessage) > len(p) {
		return 0, errors.New("Decrypt error")
	}

	bytesWritten := copy(p, decryptedMessage)

	return bytesWritten, nil
}

type secureWriter struct {
	wrappedWriter io.Writer
	priv, pub     *[32]byte
}

// encrypt
func (w secureWriter) Write(p []byte) (int, error) {
	nonce, err := newNonce()

	if err != nil {
		return 0, err
	}

	encryptedMessage := box.Seal(nil, p, &nonce, w.pub, w.priv)
	// tack the nonce onto the encrypted message
	encWithNonce := append(nonce[:], encryptedMessage...)

	n, err := w.wrappedWriter.Write(encWithNonce)

	return n, err
}

// NewSecureReader instantiates a new SecureReader
func NewSecureReader(r io.Reader, priv, pub *[32]byte) io.Reader {
	return secureReader{r, priv, pub}
}

// NewSecureWriter instantiates a new SecureWriter
func NewSecureWriter(w io.Writer, priv, pub *[32]byte) io.Writer {
	return secureWriter{w, priv, pub}
}

type secureConn struct {
	io.Reader
	io.Writer
	io.Closer
}

// Dial generates a private/public key pair,
// connects to the server, perform the handshake
// and return a reader/writer.
func Dial(addr string) (io.ReadWriteCloser, error) {
	pub, priv, err := box.GenerateKey(rand.Reader)

	if err != nil {
		return nil, err
	}

	conn, err := net.Dial("tcp", addr)

	if err != nil {
		return nil, err
	}

	// first thing we do is send our public key
	_, err = conn.Write(pub[:])

	if err != nil {
		return nil, err
	}

	// wait for the server's public key
	peerPubSlice := make([]byte, 32)
	n, err := conn.Read(peerPubSlice)

	if err != nil {
		return nil, err
	}

	peerPubSlice = peerPubSlice[:n]
	var peerPub [32]byte
	copy(peerPub[:], peerPubSlice)

	secCon := secureConn{
		NewSecureReader(conn, priv, &peerPub),
		NewSecureWriter(conn, priv, &peerPub),
		conn,
	}

	return secCon, nil
}

// Serve starts a secure echo server on the given listener.
func Serve(l net.Listener) error {
	pub, priv, err := box.GenerateKey(rand.Reader)

	if err != nil {
		return err
	}

	for {
		conn, err := l.Accept()
		if err != nil {
			return err
		}

		go handleConnection(conn, pub, priv)
	}
	return nil
}

func handleConnection(c net.Conn, pub, priv *[32]byte) error {
	// first wait for the client's public key
	peerPubSlice := make([]byte, 32)
	n, err := c.Read(peerPubSlice)

	if err != nil {
		return err
	}

	peerPubSlice = peerPubSlice[:n]
	var peerPub [32]byte
	copy(peerPub[:], peerPubSlice)

	// then, send our public key
	_, err = c.Write(pub[:])

	if err != nil {
		return err
	}

	// now session is "secure"
	secureReader := NewSecureReader(c, priv, &peerPub)
	secureWriter := NewSecureWriter(c, priv, &peerPub)

	// echo
	_, err = io.Copy(secureWriter, secureReader)

	return err
}

func main() {
	port := flag.Int("l", 0, "Listen mode. Specify port")
	flag.Parse()

	// Server mode
	if *port != 0 {
		l, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
		if err != nil {
			log.Fatal(err)
		}
		defer l.Close()
		log.Fatal(Serve(l))
	}

	// Client mode
	if len(os.Args) != 3 {
		log.Fatalf("Usage: %s <port> <message>", os.Args[0])
	}
	conn, err := Dial("localhost:" + os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	if _, err := conn.Write([]byte(os.Args[2])); err != nil {
		log.Fatal(err)
	}
	buf := make([]byte, len(os.Args[2]))
	n, err := conn.Read(buf)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", buf[:n])
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"github.com/jessevdk/go-flags"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
)

const (
	Version = "1.1.0"
)

type Options struct {
	Version bool `short:"v" long:"version" description:"Show version information"`
	Check   bool `short:"c" long:"check" description:"Check instead of overwriting"`
	Force   bool `short:"f" long:"force" description:"Force whitespace checking all files"`
}

func main() {

	// Options for flags package
	var opts Options

	// Build the parser
	parser := flags.NewParser(&opts, flags.Default)

	// Set usage string
	parser.Usage = "[options] FILES"

	// Parse the arguments
	args, err := parser.Parse()
	handle(err)

	// Print version and exit
	if opts.Version {
		fmt.Println(Version)
		os.Exit(0)
	}

	// If no argument is given
	if len(args) == 0 {
		parser.WriteHelp(os.Stdout)
		os.Exit(0)
	}

	whitespace := regexp.MustCompile("[\\t\\f ]+(\\r?(\\n))")

	newline := []byte("\n")
	replace := []byte("$1")

	for _, v := range args {

		name, err := filepath.Abs(v)
		handle(err)

		info, err := os.Stat(name)
		handle(err)

		if info.IsDir() {
			fmt.Println(name + " seems to be a directory. Skipping...")
		} else {
			data, err := ioutil.ReadFile(name)
			handle(err)

			if opts.Check {
				if whitespace.FindIndex(data) != nil {
					check(name, opts)
				}
			} else {
				data = whitespace.ReplaceAll(data, replace)
			}

			if !bytes.HasSuffix(data, newline) {
				data = append(data, newline...)
			}

			if !opts.Check {
				ioutil.WriteFile(name, data, info.Mode())
			}
		}
	}
}

func check(name string, opts Options) {
	fmt.Println("Found whitespace in " + name)

	if !opts.Force {
		os.Exit(0)
	}
}

func handle(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(0)
	}
}
<commit_msg>Improved code<commit_after>package main

import (
	"bytes"
	"fmt"
	"github.com/jessevdk/go-flags"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
)

const (
	Version = "1.1.0"
)

type Options struct {
	Version bool `short:"v" long:"version" description:"Show version information"`
	Check   bool `short:"c" long:"check" description:"Check instead of overwriting"`
	Force   bool `short:"f" long:"force" description:"Force whitespace checking all files"`
}

func main() {

	// Options for flags package
	var opts Options

	// Build the parser
	parser := flags.NewParser(&opts, flags.Default)

	// Set usage string
	parser.Usage = "[options] FILES"

	// Parse the arguments
	args, err := parser.Parse()
	handle(err)

	// Print version and exit
	if opts.Version {
		fmt.Println(Version)
		os.Exit(0)
	}

	// If no argument is given
	if len(args) == 0 {
		parser.WriteHelp(os.Stdout)
		os.Exit(0)
	}

	whitespace := regexp.MustCompile("[\\t\\f ]+(\\r?(\\n))")

	newline := []byte("\n")
	replace := []byte("$1")

	for _, v := range args {

		name, err := filepath.Abs(v)
		handle(err)

		info, err := os.Stat(name)
		handle(err)

		if info.IsDir() {
			fmt.Println(name + " seems to be a directory. Skipping...")
			continue
		}

		data, err := ioutil.ReadFile(name)
		handle(err)

		if opts.Check && whitespace.FindIndex(data) != nil {
			check(name, opts)
			continue
		}

		data = whitespace.ReplaceAll(data, replace)

		if !bytes.HasSuffix(data, newline) {
			data = append(data, newline...)
		}

		ioutil.WriteFile(name, data, info.Mode())
	}
}

func check(name string, opts Options) {
	fmt.Println("Found whitespace in " + name)

	if !opts.Force {
		os.Exit(0)
	}
}

func handle(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(0)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"io"
	"os"
	"time"

	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/jessevdk/go-flags"
	"github.com/moncho/dry/app"
	"github.com/moncho/dry/ui"
	"github.com/nsf/termbox-go"
)
import _ "net/http/pprof"

// command line flags variable
var opts struct {
	// enable profiling
	Profile bool `short:"p" long:"profile" description:"Enable profiling"`
}

//-----------------------------------------------------------------------------
func mainLoop(screen *ui.Screen) {
	app := screen.App
	if ok, _ := app.Ok(); !ok {
		return
	}

	keyboardQueue := make(chan termbox.Event)
	timestampQueue := time.NewTicker(1 * time.Second)

	go func() {
		for {
			keyboardQueue <- termbox.PollEvent()
		}
	}()

	screen.Render(app.Render())
	//belongs outside the loop
	var streamMode = false
	var readOnlyMode = false
loop:
	for {
		var refresh = false
		select {

		case event := <-keyboardQueue:
			switch event.Type {
			case termbox.EventKey:
				if !app.State.ShowingHelp && !readOnlyMode {
					if event.Key == termbox.KeyEsc || event.Ch == 'q' || event.Ch == 'Q' {
						break loop
					} else if event.Key == termbox.KeyF1 { //sort
						app.Sort()
						app.Refresh()
					} else if event.Key == termbox.KeyF2 { //show all containers
						app.ToggleShowAllContainers()
					} else if event.Key == termbox.KeyF5 { // refresh
						app.Refresh()
					} else if event.Ch == '?' || event.Ch == 'h' || event.Ch == 'H' { //help
						app.ShowHelp()
					} else if event.Ch == 'e' || event.Ch == 'E' { //remove
						app.Rm(screen.CursorPosition())
					} else if event.Ch == 'k' || event.Ch == 'K' { //kill
						app.Kill(screen.CursorPosition())
					} else if event.Ch == 'l' || event.Ch == 'L' { //logs
						if logs, err := app.Logs(screen.CursorPosition()); err == nil {
							readOnlyMode = true
							streamMode = true
							stream(screen, logs)
						}
					} else if event.Ch == 'r' || event.Ch == 'R' { //start
						app.StartContainer(screen.CursorPosition())
					} else if event.Ch == 's' || event.Ch == 'S' { //stats
						app.Stats(screen.CursorPosition())
						readOnlyMode = true
						refresh = true
					} else if event.Ch == 't' || event.Ch == 'T' { //stop
						app.StopContainer(screen.CursorPosition())
					} else if event.Key == termbox.KeyArrowUp { //cursor up
						screen.MoveCursorUp()
						refresh = true
					} else if event.Key == termbox.KeyArrowDown { // cursor down
						screen.MoveCursorDown()
						refresh = true
					}
				} else if app.State.ShowingHelp {
					app.ShowDockerInfo()
				} else if readOnlyMode && event.Key == termbox.KeyEsc {
					readOnlyMode = false
					streamMode = false
					refresh = true
				}

			case termbox.EventResize:
				screen.Resize()
				refresh = true
			}

		case <-timestampQueue.C:
			if !streamMode {
				timestamp := time.Now().Format(`3:04:05pm PST`)
				screen.RenderLine(0, 0, `<right><white>`+timestamp+`</></right>`)
			}
		}
		if !streamMode && (refresh || app.Changed()) {
			_ = "breakpoint"
			screen.Clear().Render(app.Render())
		}
	}

	log.Info("something broke the loop")
}

func stream(screen *ui.Screen, stream io.Reader) {
	log.Info("[stream] Showing stream")
	screen.Clear()
	screen.Sync()
	go func() {
		//io.Copy(os.Stdout, stream)
		scanner := bufio.NewScanner(stream)

		screen.RenderLine(0, 0, "ESC to go back")
		for i := 1; scanner.Scan(); i++ {
			screen.RenderLine(0, i, scanner.Text())
		}
		if err := scanner.Err(); err != nil {
			screen.RenderLine(0, 0, "There was an error with the scanner")
		}
	}()

	log.Debugf("[stream] End of stdout")
}

//-----------------------------------------------------------------------------
func main() {
	log.Infof("Launching dry %v", true)
	// parse flags
	_, err := flags.Parse(&opts)
	if err != nil {
		flagError := err.(*flags.Error)
		if flagError.Type == flags.ErrHelp {
			return
		}
		if flagError.Type == flags.ErrUnknownFlag {
			log.Error("Use --help to view all available options.")
			return
		}
		log.Errorf("Error parsing flags: %s\n", err)
		return
	}
	if os.Getenv("DOCKER_HOST") == "" {
		log.Error("No DOCKER_HOST environment variable found.")
		return
	}
	// Start profiling (if required)
	if opts.Profile {
		go func() {
			log.Info(http.ListenAndServe("localhost:6060", nil))
		}()
	}
	_ = "breakpoint"
	app := app.NewDryApp()
	screen := ui.NewScreen(app)
	mainLoop(screen)
	screen.Close()
	log.Info("Bye")
}
<commit_msg>Minor<commit_after>package main

import (
	"bufio"
	"io"
	"os"
	"time"

	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/jessevdk/go-flags"
	"github.com/moncho/dry/app"
	"github.com/moncho/dry/ui"
	"github.com/nsf/termbox-go"
)
import _ "net/http/pprof"

// command line flags variable
var opts struct {
	// enable profiling
	Profile bool `short:"p" long:"profile" description:"Enable profiling"`
}

//-----------------------------------------------------------------------------
func mainLoop(screen *ui.Screen) {
	app := screen.App
	if ok, _ := app.Ok(); !ok {
		return
	}

	keyboardQueue := make(chan termbox.Event)
	timestampQueue := time.NewTicker(1 * time.Second)

	go func() {
		for {
			keyboardQueue <- termbox.PollEvent()
		}
	}()

	screen.Render(app.Render())
	//belongs outside the loop
	var streamMode = false
	var readOnlyMode = false
loop:
	for {
		var refresh = false
		select {

		case event := <-keyboardQueue:
			switch event.Type {
			case termbox.EventKey:
				if !app.State.ShowingHelp && !readOnlyMode {
					if event.Key == termbox.KeyEsc || event.Ch == 'q' || event.Ch == 'Q' {
						break loop
					} else if event.Key == termbox.KeyF1 { //sort
						app.Sort()
						app.Refresh()
					} else if event.Key == termbox.KeyF2 { //show all containers
						app.ToggleShowAllContainers()
					} else if event.Key == termbox.KeyF5 { // refresh
						app.Refresh()
					} else if event.Ch == '?' || event.Ch == 'h' || event.Ch == 'H' { //help
						app.ShowHelp()
					} else if event.Ch == 'e' || event.Ch == 'E' { //remove
						app.Rm(screen.CursorPosition())
					} else if event.Ch == 'k' || event.Ch == 'K' { //kill
						app.Kill(screen.CursorPosition())
					} else if event.Ch == 'l' || event.Ch == 'L' { //logs
						if logs, err := app.Logs(screen.CursorPosition()); err == nil {
							readOnlyMode = true
							streamMode = true
							stream(screen, logs)
						}
					} else if event.Ch == 'r' || event.Ch == 'R' { //start
						app.StartContainer(screen.CursorPosition())
					} else if event.Ch == 's' || event.Ch == 'S' { //stats
						app.Stats(screen.CursorPosition())
						readOnlyMode = true
						refresh = true
					} else if event.Ch == 't' || event.Ch == 'T' { //stop
						app.StopContainer(screen.CursorPosition())
					} else if event.Key == termbox.KeyArrowUp { //cursor up
						screen.MoveCursorUp()
						refresh = true
					} else if event.Key == termbox.KeyArrowDown { // cursor down
						screen.MoveCursorDown()
						refresh = true
					}
				} else if app.State.ShowingHelp {
					app.ShowDockerInfo()
				} else if readOnlyMode && event.Key == termbox.KeyEsc {
					readOnlyMode = false
					streamMode = false
					refresh = true
				}

			case termbox.EventResize:
				screen.Resize()
				refresh = true
			}

		case <-timestampQueue.C:
			if !streamMode {
				timestamp := time.Now().Format(`3:04:05pm PST`)
				screen.RenderLine(0, 0, `<right><white>`+timestamp+`</></right>`)
			}
		}
		if !streamMode && (refresh || app.Changed()) {
			_ = "breakpoint"
			screen.Clear().Render(app.Render())
		}
	}

	log.Info("something broke the loop")
}

func stream(screen *ui.Screen, stream io.Reader) {
	log.Info("[stream] Showing stream")
	screen.Clear()
	screen.Sync()
	go func() {
		//io.Copy(os.Stdout, stream)
		scanner := bufio.NewScanner(stream)

		screen.RenderLine(0, 0, "ESC to go back")
		for i := 1; scanner.Scan(); i++ {
			screen.RenderLine(0, i, scanner.Text())
		}
		if err := scanner.Err(); err != nil {
			screen.RenderLine(0, 0, "There was an error with the scanner")
		}
	}()

	log.Debugf("[stream] End of stdout")
}

//-----------------------------------------------------------------------------
func main() {
	log.Infof("Launching dry")
	// parse flags
	_, err := flags.Parse(&opts)
	if err != nil {
		flagError := err.(*flags.Error)
		if flagError.Type == flags.ErrHelp {
			return
		}
		if flagError.Type == flags.ErrUnknownFlag {
			log.Error("Use --help to view all available options.")
			return
		}
		log.Errorf("Error parsing flags: %s\n", err)
		return
	}
	if os.Getenv("DOCKER_HOST") == "" {
		log.Error("No DOCKER_HOST environment variable found.")
		return
	}
	// Start profiling (if required)
	if opts.Profile {
		go func() {
			log.Info(http.ListenAndServe("localhost:6060", nil))
		}()
	}
	_ = "breakpoint"
	app := app.NewDryApp()
	screen := ui.NewScreen(app)
	mainLoop(screen)
	screen.Close()
	log.Info("Bye")
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"strings"
	"time"
)

const PROGVERSION string = "0.3.0"

type Config struct {
	Main struct {
		Address  string
		Port     int
		Sitename string
	}
}

var cfg Config

func init() {
	rand.Seed(time.Now().UnixNano())
	if !fexists("versions") {
		info("Creating data directory.")
		os.MkdirAll("versions", 0700)
	}
	if !fexists("updates") {
		info("Creating update directory.")
		os.MkdirAll("updates", 0700)
	}
}

func main() {
	var runupdates *bool = flag.Bool("u", false, "Run updates instead of launching web server.")
	var address *string = flag.String("a", "0.0.0.0", "Address to bind to.")
	var port *int = flag.Int("p", 8000, "Port to bind to.")
	var display *bool = flag.Bool("d", false, "Display versions and URLs available, then exit.")
	var version *string = flag.String("v", "", "Display a specific version. If not specified you get everything.")
	flag.Parse()

	if *runupdates {
		updateVersions()
		return
	}

	if *display {
		if *version == "" {
			displayVersions()
		} else {
			displayVersion(*version)
		}
		return
	}

	cfg.Main.Address = *address
	cfg.Main.Port = *port
	cfg.Main.Sitename = "Unity download links"
	initWeb()
	endWeb()
}

var baseurl1 = "http://download.unity3d.com/download_unity/"
var baseurl2 = "http://beta.unity3d.com/download/"

func updateVersions() {
	p("UnityLinks %s", PROGVERSION)
	files, err := ioutil.ReadDir("./updates")
	if err != nil {
		p("Error: %s.", err.Error())
		return
	}
	count := 0
	max := 0
	for _, fi := range files {
		if !fi.IsDir() {
			max++
			s, _ := ioutil.ReadFile("updates/" + fi.Name())
			if s != nil {
				hash := strings.Replace(string(s), "\n", "", -1)
				getMacIni(hash, fi.Name())
				getWinIni(hash, fi.Name())
				count++
			}
		}
	}
	info("Updated %d versions out of %d.", count, max)
}

func getVar(line string) string {
	return strings.TrimSpace(line[strings.IndexByte(line, '=')+1:])
}

func getMacIni(hash string, filename string) {
	url := baseurl1 + hash + "/unity-" + filename + "-osx.ini"
	url2 := baseurl2 + hash + "/unity-" + filename + "-osx.ini"

	info("Downloading %s", url)
	response, _ := http.Get(url)
	p("Status: %d\n", response.StatusCode)
	if response.StatusCode == 404 {
		p("Trying again with %s\n", url2)
		response, _ = http.Get(url2)
		if response.StatusCode == 404 {
			p("Error downloading %s\n", url2)
			return
		}
	}
	defer response.Body.Close()
	bs, err := ioutil.ReadAll(response.Body)
	if err != nil {
		p("Error fetching OS X version: %s\n", err.Error())
		return
	}
	contents := string(bs)
	sections := strings.Split(contents, "[")
	data := ""
	for _, s := range sections {
		if len(s) > 0 {
			lines := strings.Split(s, "\n")
			data += getVar(lines[1]) + "\n"
			data += getVar(lines[2]) + "\n"
			data += baseurl1 + hash + "/" + getVar(lines[3]) + "\n"
			data += getVar(lines[4]) + "\n"
		}
	}
	p("Saving %s (OS X)\n", filename)
	saveVersion(filename, data)
}

//TODO: gcfg can't read the -win.ini properly. Make custom hack.
func getWinIni(hash string, filename string) {
	url := baseurl1 + hash + "/unity-" + filename + "-win.ini"
	url2 := baseurl2 + hash + "/unity-" + filename + "-win.ini"

	info("Downloading %s", url)
	response, _ := http.Get(url)
	if response.StatusCode == 404 {
		p("Trying again with %s\n", url2)
		response, _ = http.Get(url2)
		if response.StatusCode == 404 {
			p("Error downloading %s", url2)
			return
		}
	}
	defer response.Body.Close()
	bs, err := ioutil.ReadAll(response.Body)
	if err != nil {
		p("Error fetching Windows version: %s\n", err.Error())
		return
	}
	contents := string(bs)
	sections := strings.Split(contents, "[")
	data := ""
	for _, s := range sections {
		if len(s) > 0 {
			lines := strings.Split(s, "\n")
			data += getVar(lines[1]) + "\n"
			data += getVar(lines[2]) + "\n"
			l3 := baseurl1 + hash + "/" + getVar(lines[3])
			l4 := baseurl1 + hash + "/" + getVar(lines[4])
			data += l3 + "\n" + l4 + "\n"
		}
	}
	p("Saving %s (Windows)\n", filename)
	saveVersion(filename+".win", data)
}

func saveVersion(version string, data string) {
	file, err := os.OpenFile("versions/"+version, os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		p("Error: %s.", err.Error())
		return
	}

	defer file.Close()
	file.WriteString(data)
	os.Remove("updates/" + version)
}

func displayVersions() {
	files, err := ioutil.ReadDir("versions")
	if err != nil {
		p("Error: %s.", err.Error())
		return
	}
	for _, fi := range files {
		if !fi.IsDir() {
			displayVersion(fi.Name())
		}
	}
}

func displayVersion(version string) {
	name := "versions/" + version
	s, _ := ioutil.ReadFile(name)
	p("%s\n", s)
}
<commit_msg>Updated to version 0.4.0.<commit_after>package main

import (
	"flag"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"strings"
	"time"
)

const PROGVERSION string = "0.4.0"

type Config struct {
	Main struct {
		Address  string
		Port     int
		Sitename string
	}
}

var cfg Config

func init() {
	rand.Seed(time.Now().UnixNano())
	if !fexists("versions") {
		info("Creating data directory.")
		os.MkdirAll("versions", 0700)
	}
	if !fexists("updates") {
		info("Creating update directory.")
		os.MkdirAll("updates", 0700)
	}
}

func main() {
	var runupdates *bool = flag.Bool("u", false, "Run updates instead of launching web server.")
	var address *string = flag.String("a", "0.0.0.0", "Address to bind to.")
	var port *int = flag.Int("p", 8000, "Port to bind to.")
	var display *bool = flag.Bool("d", false, "Display versions and URLs available, then exit.")
	var version *string = flag.String("v", "", "Display a specific version. If not specified you get everything.")
	flag.Parse()

	if *runupdates {
		updateVersions()
		return
	}

	if *display {
		if *version == "" {
			displayVersions()
		} else {
			displayVersion(*version)
		}
		return
	}

	cfg.Main.Address = *address
	cfg.Main.Port = *port
	cfg.Main.Sitename = "Unity download links"
	initWeb()
	endWeb()
}

var baseurl1 = "http://download.unity3d.com/download_unity/"
var baseurl2 = "http://beta.unity3d.com/download/"

func updateVersions() {
	p("UnityLinks %s", PROGVERSION)
	files, err := ioutil.ReadDir("./updates")
	if err != nil {
		p("Error: %s.", err.Error())
		return
	}
	count := 0
	max := 0
	for _, fi := range files {
		if !fi.IsDir() {
			max++
			s, _ := ioutil.ReadFile("updates/" + fi.Name())
			if s != nil {
				hash := strings.Replace(string(s), "\n", "", -1)
				getMacIni(hash, fi.Name())
				getWinIni(hash, fi.Name())
				count++
			}
		}
	}
	info("Updated %d versions out of %d.", count, max)
}

func getVar(line string) string {
	return strings.TrimSpace(line[strings.IndexByte(line, '=')+1:])
}

func getMacIni(hash string, filename string) {
	url := baseurl1 + hash + "/unity-" + filename + "-osx.ini"
	url2 := baseurl2 + hash + "/unity-" + filename + "-osx.ini"

	info("Downloading %s", url)
	response, _ := http.Get(url)
	p("Status: %d\n", response.StatusCode)
	if response.StatusCode == 404 {
		p("Trying again with %s\n", url2)
		response, _ = http.Get(url2)
		if response.StatusCode == 404 {
			p("Error downloading %s\n", url2)
			return
		}
	}
	defer response.Body.Close()
	bs, err := ioutil.ReadAll(response.Body)
	if err != nil {
		p("Error fetching OS X version: %s\n", err.Error())
		return
	}
	contents := string(bs)
	sections := strings.Split(contents, "[")
	data := ""
	for _, s := range sections {
		if len(s) > 0 {
			lines := strings.Split(s, "\n")
			data += getVar(lines[1]) + "\n"
			data += getVar(lines[2]) + "\n"
			data += baseurl1 + hash + "/" + getVar(lines[3]) + "\n"
			data += getVar(lines[4]) + "\n"
		}
	}
	p("Saving %s (OS X)\n", filename)
	saveVersion(filename, data)
}

//TODO: gcfg can't read the -win.ini properly. Make custom hack.
func getWinIni(hash string, filename string) {
	url := baseurl1 + hash + "/unity-" + filename + "-win.ini"
	url2 := baseurl2 + hash + "/unity-" + filename + "-win.ini"

	info("Downloading %s", url)
	response, _ := http.Get(url)
	if response.StatusCode == 404 {
		p("Trying again with %s\n", url2)
		response, _ = http.Get(url2)
		if response.StatusCode == 404 {
			p("Error downloading %s", url2)
			return
		}
	}
	defer response.Body.Close()
	bs, err := ioutil.ReadAll(response.Body)
	if err != nil {
		p("Error fetching Windows version: %s\n", err.Error())
		return
	}
	contents := string(bs)
	sections := strings.Split(contents, "[")
	data := ""
	for _, s := range sections {
		if len(s) > 0 {
			lines := strings.Split(s, "\n")
			data += getVar(lines[1]) + "\n"
			data += getVar(lines[2]) + "\n"
			l3 := baseurl1 + hash + "/" + getVar(lines[3])
			l4 := baseurl1 + hash + "/" + getVar(lines[4])
			data += l3 + "\n" + l4 + "\n"
		}
	}
	p("Saving %s (Windows)\n", filename)
	saveVersion(filename+".win", data)
}

func saveVersion(version string, data string) {
	file, err := os.OpenFile("versions/"+version, os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		p("Error: %s.", err.Error())
		return
	}

	defer file.Close()
	file.WriteString(data)
	os.Remove("updates/" + version)
}

func displayVersions() {
	files, err := ioutil.ReadDir("versions")
	if err != nil {
		p("Error: %s.", err.Error())
		return
	}
	for _, fi := range files {
		if !fi.IsDir() {
			displayVersion(fi.Name())
		}
	}
}

func displayVersion(version string) {
	name := "versions/" + version
	s, _ := ioutil.ReadFile(name)
	p("%s\n", s)
}
<|endoftext|>


<commit_before>package main

import (
	_ "github.com/DanielRenne/GoCore/core"
	_ "github.com/DanielRenne/GoCore/core/app"
	_ "github.com/DanielRenne/GoCore/core/app/api"
	_ "github.com/DanielRenne/GoCore/core/appGen"
	_ "github.com/DanielRenne/GoCore/core/atomicTypes"
	_ "github.com/DanielRenne/GoCore/core/channels"
	_ "github.com/DanielRenne/GoCore/core/crypto"
	_ "github.com/DanielRenne/GoCore/core/dbServices"
	_ "github.com/DanielRenne/GoCore/core/dbServices/bolt/stubs"
	_ "github.com/DanielRenne/GoCore/core/dbServices/common/stubs"
	_ "github.com/DanielRenne/GoCore/core/dbServices/mongo/acct"
	_ "github.com/DanielRenne/GoCore/core/dbServices/mongo/stubs"
	_ "github.com/DanielRenne/GoCore/core/extensions"
	_ "github.com/DanielRenne/GoCore/core/fileCache"
	_ "github.com/DanielRenne/GoCore/core/ginServer"
	_ "github.com/DanielRenne/GoCore/core/gitWebHooks"
	_ "github.com/DanielRenne/GoCore/core/httpExtensions"
	_ "github.com/DanielRenne/GoCore/core/logger"
	_ "github.com/DanielRenne/GoCore/core/pubsub"
	_ "github.com/DanielRenne/GoCore/core/serverSettings"
	_ "github.com/DanielRenne/GoCore/core/store"
	_ "github.com/DanielRenne/GoCore/core/syncAtomic"
	_ "github.com/DanielRenne/GoCore/core/utils"
	_ "github.com/DanielRenne/GoCore/core/zip"
)

func main() {

}
<commit_msg>Dummy release.<commit_after>package main

import (
	"log"

	_ "github.com/DanielRenne/GoCore/core"
	_ "github.com/DanielRenne/GoCore/core/app"
	_ "github.com/DanielRenne/GoCore/core/app/api"
	_ "github.com/DanielRenne/GoCore/core/appGen"
	_ "github.com/DanielRenne/GoCore/core/atomicTypes"
	_ "github.com/DanielRenne/GoCore/core/channels"
	_ "github.com/DanielRenne/GoCore/core/crypto"
	_ "github.com/DanielRenne/GoCore/core/dbServices"
	_ "github.com/DanielRenne/GoCore/core/dbServices/bolt/stubs"
	_ "github.com/DanielRenne/GoCore/core/dbServices/common/stubs"
	_ "github.com/DanielRenne/GoCore/core/dbServices/mongo/acct"
	_ "github.com/DanielRenne/GoCore/core/dbServices/mongo/stubs"
	_ "github.com/DanielRenne/GoCore/core/extensions"
	_ "github.com/DanielRenne/GoCore/core/fileCache"
	_ "github.com/DanielRenne/GoCore/core/ginServer"
	_ "github.com/DanielRenne/GoCore/core/gitWebHooks"
	_ "github.com/DanielRenne/GoCore/core/httpExtensions"
	_ "github.com/DanielRenne/GoCore/core/logger"
	_ "github.com/DanielRenne/GoCore/core/pubsub"
	_ "github.com/DanielRenne/GoCore/core/serverSettings"
	_ "github.com/DanielRenne/GoCore/core/store"
	_ "github.com/DanielRenne/GoCore/core/syncAtomic"
	_ "github.com/DanielRenne/GoCore/core/utils"
	_ "github.com/DanielRenne/GoCore/core/zip"
)

func main() {
	log.Println("Welcome to GoCore:\n\nThis is a dummy binary meant to import all the shared libraries GoCore apps use so you can import anything you want.")
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"

	"github.com/codegangsta/cli"
	"github.com/hacdias/wpsync/config"
	"github.com/hacdias/wpsync/helpers/dependencies"
	"github.com/hacdias/wpsync/helpers/plugin"
)

func main() {
	app := cli.NewApp()
	app.Name = "wpsync"
	app.Usage = "Sync WordPress SVN with your Git or SVN repository"
	app.Version = "1.1.1"
	app.Authors = []cli.Author{
		cli.Author{
			Name:  "Henrique Dias",
			Email: "hacdias@gmail.com",
		},
	}
	app.Flags = []cli.Flag{
		cli.BoolTFlag{
			Name:  "bower, b",
			Usage: "update bower dependencies",
		},
		cli.BoolTFlag{
			Name:  "composer, c",
			Usage: "update composer dependencies",
		},
		cli.BoolTFlag{
			Name:  "keep, k",
			Usage: "synchronize repositories without changing the version",
		},
		cli.StringFlag{
			Name:  "increase, i",
			Value: "build",
			Usage: "version increase (major.minor.build.revision)",
		},
		cli.StringFlag{
			Name:  "message, m",
			Value: "",
			Usage: "commit message (default is the version number)",
		},
	}
	app.Action = func(c *cli.Context) {
		conf := config.GetConfig()

		if c.IsSet("bower") {
			conf.Bower = c.BoolT("bower")
		}

		if c.IsSet("composer") {
			conf.Composer = c.BoolT("composer")
		}

		if c.IsSet("keep") {
			conf.Keep = c.BoolT("keep")
		}

		if c.IsSet("increase") {
			conf.Increase = c.String("increase")
		}

		if c.IsSet("message") {
			conf.Message = c.String("message")
		}

		if conf.Bower {
			if _, err := os.Stat("bower.json"); err == nil {
				bower := dependencies.Bower{}
				bower.Update()
			}
		}

		if conf.Composer {
			if _, err := os.Stat("composer.json"); err == nil {
				composer := dependencies.Composer{}
				composer.Update()
			}
		}

		plugin := plugin.Plugin{}
		plugin.Config = conf
		plugin.Update()
	}
	app.Commands = []cli.Command{
		{
			Name:    "init",
			Aliases: []string{"i"},
			Usage:   "init the " + config.File + " file",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "link, l",
					Value: "",
					Usage: "the wordpress svn url",
				},
			},
			Action: func(c *cli.Context) {
				if c.String("link") == "" {
					log.Fatal("please define the wordpress svn link, check \"wpsync init -h\" to know more")
				}

				config.Init(c.String("link"))
			},
		},
	}
	app.Run(os.Args)
}
<commit_msg>update sth<commit_after>package main

import (
	"log"
	"os"

	"github.com/codegangsta/cli"
	"github.com/hacdias/wpsync/config"
	"github.com/hacdias/wpsync/helpers/dependencies"
	"github.com/hacdias/wpsync/helpers/plugin"
)

func main() {
	app := cli.NewApp()
	app.Name = "wpsync"
	app.Usage = "Sync WordPress SVN with your Git or SVN repository"
	app.Version = "1.1.1"
	app.Authors = []cli.Author{
		cli.Author{
			Name:  "Henrique Dias",
			Email: "hacdias@gmail.com",
		},
	}
	app.Flags = []cli.Flag{
		cli.BoolTFlag{
			Name:  "bower, b",
			Usage: "update bower dependencies",
		},
		cli.BoolTFlag{
			Name:  "composer, c",
			Usage: "update composer dependencies",
		},
		cli.BoolFlag{
			Name:  "keep, k",
			Usage: "synchronize repositories without changing the version",
		},
		cli.StringFlag{
			Name:  "increase, i",
			Value: "build",
			Usage: "version increase (major.minor.build.revision)",
		},
		cli.StringFlag{
			Name:  "message, m",
			Value: "",
			Usage: "commit message (default is the version number)",
		},
	}
	app.Action = func(c *cli.Context) {
		conf := config.GetConfig()

		if c.IsSet("bower") {
			conf.Bower = c.BoolT("bower")
		}

		if c.IsSet("composer") {
			conf.Composer = c.BoolT("composer")
		}

		conf.Keep = c.Bool("keep")

		if c.IsSet("increase") {
			conf.Increase = c.String("increase")
		}

		if c.IsSet("message") {
			conf.Message = c.String("message")
		}

		if conf.Bower {
			if _, err := os.Stat("bower.json"); err == nil {
				bower := dependencies.Bower{}
				bower.Update()
			}
		}

		if conf.Composer {
			if _, err := os.Stat("composer.json"); err == nil {
				composer := dependencies.Composer{}
				composer.Update()
			}
		}

		plugin := plugin.Plugin{}
		plugin.Config = conf
		plugin.Update()
	}
	app.Commands = []cli.Command{
		{
			Name:    "init",
			Aliases: []string{"i"},
			Usage:   "init the " + config.File + " file",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "link, l",
					Value: "",
					Usage: "the wordpress svn url",
				},
			},
			Action: func(c *cli.Context) {
				if c.String("link") == "" {
					log.Fatal("please define the wordpress svn link, check \"wpsync init -h\" to know more")
				}

				config.Init(c.String("link"))
			},
		},
	}
	app.Run(os.Args)
}
<|endoftext|>


<commit_before>// +build ignore

package main

// This is a simple REPL (read-eval-print loop) for GO.

// An intent (rocky) was also to have something that I can debug in
// the ssa-debugger tortoise/gub.sh. Right now that can't handle the
// unsafe package, pointers, and calls to C code. So that let's out
// go-gnureadline and lineedit.
import (
	"bufio"
	"fmt"
	"go/parser"
	"io"
	"os"
	"reflect"
	"strconv"
	"strings"

	"github.com/rocky/go-repl"
	"github.com/0xfaded/go-interactive"
)

// Simple replacement for GNU readline
func readline(prompt string, in *bufio.Reader) (string, error) {
	fmt.Printf(prompt)
	line, err := in.ReadString('\n')
	if err == nil {
		line = strings.TrimRight(line, "\r\n")
	}
	return line, err
}

// The read-eval-print portion
func REPL(env *interactive.Env, results *([]interface{})) {

	var err error
	exprs := 0
	in := bufio.NewReader(os.Stdin)
	line, err := readline("go> ", in)
	for line != "quit" {
		if err != nil {
			if err == io.EOF { break }
			panic(err)
		}
		ctx := &interactive.Ctx{line}
		if expr, err := parser.ParseExpr(line); err != nil {
			fmt.Printf("parse error: %s\n", err)
		} else if cexpr, errs := interactive.CheckExpr(ctx, expr, env); len(errs) != 0 {
			for _, cerr := range errs {
				fmt.Printf("%v\n", cerr)
			}
		} else if vals, _, err := interactive.EvalExpr(ctx, cexpr, env); err != nil {
			fmt.Printf("eval error: %s\n", err)
		} else if vals == nil {
			fmt.Printf("nil\n")
		} else if len(*vals) == 0 {
			fmt.Printf("void\n")
		} else if len(*vals) == 1 {
			value := (*vals)[0]
			kind := value.Kind().String()
			fmt.Printf("Kind = %v\n", kind)
			typ  := value.Type().String()
			if typ != kind { fmt.Printf("Type = %v\n", typ) }
			if kind == "string" {
				fmt.Printf("results[%d] = %s\n", exprs,
					strconv.QuoteToASCII(value.String()))
			} else {
				fmt.Printf("results[%d] = %v\n", exprs, (value.Interface()))
			}
			exprs  += 1
			*results = append(*results, (*vals)[0].Interface())
		} else {
			sep := "("
			for _, v := range *vals {
				fmt.Printf("%s%v", sep, v.Interface())
			}
			fmt.Printf(")\n")
		}

		line, err = readline("go> ", in)
	}
}

func main() {
	// Set up the environment and then call REPL
	var vars   map[string] reflect.Value = make(map[string] reflect.Value)
	var consts map[string] reflect.Value = make(map[string] reflect.Value)
	var types  map[string] reflect.Type  = make(map[string] reflect.Type)

	var global_funcs map[string] reflect.Value = make(map[string] reflect.Value)
	var global_vars map[string]  reflect.Value = make(map[string] reflect.Value)

	// A place to store result values of expressions entered
	// interactively
	var results []interface{} = make([] interface{}, 0, 10)
	global_vars["results"] = reflect.ValueOf(&results)
	global_vars["arg0"] = reflect.ValueOf(os.Args[0])
	// global_funcs["Result"] = reflect.ValueOf(
	// 	func(i int) interface{} { return results[i] } )

	// What we have from the fmt package.
	var fmt_funcs    map[string] reflect.Value = make(map[string] reflect.Value)
	fmt_funcs["Println"] = reflect.ValueOf(fmt.Println)
	fmt_funcs["Printf"] = reflect.ValueOf(fmt.Printf)

	type Alice struct {
		Bob int
		Secret string
	}

	pkgs := map[string] interactive.Pkg {
			"fmt": &interactive.Env {
				Name:   "fmt",
				Vars:   vars,
				Consts: consts,
				Funcs:  fmt_funcs,
				Types:  types,
				Pkgs:   make(map[string] interactive.Pkg),
			}, "os": &interactive.Env {
				Name:   "os",
				Vars:   map[string] reflect.Value { "Stdout": reflect.ValueOf(&os.Stdout) },
				Consts: make(map[string] reflect.Value),
				Funcs:  make(map[string] reflect.Value),
				Types:  make(map[string] reflect.Type),
				Pkgs:   make(map[string] interactive.Pkg),
			},
		}

	repl.Extract_environment(pkgs)

	env := interactive.Env {
		Name:   ".",
		Vars:   global_vars,
		Consts: make(map[string] reflect.Value),
		Funcs:  global_funcs,
		Types:  map[string] reflect.Type{ "Alice": reflect.TypeOf(Alice{}) },
		Pkgs:   pkgs,
	}

	// Make this truly self-referential
	global_vars["env"] = reflect.ValueOf(&env)

	fmt.Printf(`=== A simple Go eval REPL ===

Results of expression are stored in variable slice "results".
Defined functions are: fmt.Println(), fmt.Printf().

The environment is stored in global variable "env".

Enter expressions to be evaluated at the "go>" prompt.

To see all results, type: "results".

To quit, enter: "quit" or Ctrl-D (EOF).
`)
	// And just when you thought we'd never get around to it...
	REPL(&env, &results)
}
<commit_msg>Now that we have automatic extraction, remove most of the hand-hacked environment that attempted to do the same thing (less well).<commit_after>// +build ignore

package main

// This is a simple REPL (read-eval-print loop) for GO.

// An intent (rocky) was also to have something that I can debug in
// the ssa-debugger tortoise/gub.sh. Right now that can't handle the
// unsafe package, pointers, and calls to C code. So that let's out
// go-gnureadline and lineedit.
import (
	"bufio"
	"fmt"
	"go/parser"
	"io"
	"os"
	"reflect"
	"strconv"
	"strings"

	"github.com/rocky/go-repl"
	"github.com/0xfaded/go-interactive"
)

// Simple replacement for GNU readline
func readline(prompt string, in *bufio.Reader) (string, error) {
	fmt.Printf(prompt)
	line, err := in.ReadString('\n')
	if err == nil {
		line = strings.TrimRight(line, "\r\n")
	}
	return line, err
}

func intro_text() {
	fmt.Printf(`=== A simple Go eval REPL ===

Results of expression are stored in variable slice "results".
The environment is stored in global variable "env".

Enter expressions to be evaluated at the "go>" prompt.

To see all results, type: "results".

To quit, enter: "quit" or Ctrl-D (EOF).
`)

}

// The read-eval-print portion
func REPL(env *interactive.Env, results *([]interface{})) {

	var err error
	exprs := 0
	in := bufio.NewReader(os.Stdin)
	line, err := readline("go> ", in)
	for line != "quit" {
		if err != nil {
			if err == io.EOF { break }
			panic(err)
		}
		ctx := &interactive.Ctx{line}
		if expr, err := parser.ParseExpr(line); err != nil {
			fmt.Printf("parse error: %s\n", err)
		} else if cexpr, errs := interactive.CheckExpr(ctx, expr, env); len(errs) != 0 {
			for _, cerr := range errs {
				fmt.Printf("%v\n", cerr)
			}
		} else if vals, _, err := interactive.EvalExpr(ctx, cexpr, env); err != nil {
			fmt.Printf("eval error: %s\n", err)
		} else if vals == nil {
			fmt.Printf("nil\n")
		} else if len(*vals) == 0 {
			fmt.Printf("void\n")
		} else if len(*vals) == 1 {
			value := (*vals)[0]
			kind := value.Kind().String()
			fmt.Printf("Kind = %v\n", kind)
			typ  := value.Type().String()
			if typ != kind { fmt.Printf("Type = %v\n", typ) }
			if kind == "string" {
				fmt.Printf("results[%d] = %s\n", exprs,
					strconv.QuoteToASCII(value.String()))
			} else {
				fmt.Printf("results[%d] = %v\n", exprs, (value.Interface()))
			}
			exprs  += 1
			*results = append(*results, (*vals)[0].Interface())
		} else {
			sep := "("
			for _, v := range *vals {
				fmt.Printf("%s%v", sep, v.Interface())
			}
			fmt.Printf(")\n")
		}

		line, err = readline("go> ", in)
	}
}

func main() {
	// Set up the environment and then call REPL
	// A place to store result values of expressions entered
	// interactively
	var results []interface{} = make([] interface{}, 0, 10)
	var global_vars map[string]  reflect.Value = make(map[string] reflect.Value)
	global_vars["results"] = reflect.ValueOf(&results)

	var pkgs map[string] interactive.Pkg = make(map[string] interactive.Pkg)
	repl.Extract_environment(pkgs)

	env := interactive.Env {
		Name:   ".",
		Vars:   global_vars,
		Consts: make(map[string] reflect.Value),
		Funcs:  make(map[string] reflect.Value),
		Types:  make(map[string] reflect.Type),
		Pkgs:   pkgs,
	}

	// Make this truly self-referential
	global_vars["env"] = reflect.ValueOf(&env)

	intro_text()

	// And just when you thought we'd never get around to it...
	REPL(&env, &results)
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"

	"github.com/codegangsta/cli"
	"github.com/minio-io/minio/pkg/server"
)

func main() {
	app := cli.NewApp()
	app.Name = "minio"
	app.Usage = ""
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "http-address,a",
			Value: ":8080",
			Usage: "http address to listen on",
		},
		cli.StringFlag{
			Name:  "cert,c",
			Value: "",
			Usage: "cert.pem",
		},
		cli.StringFlag{
			Name:  "key,k",
			Value: "",
			Usage: "key.pem",
		},
		cli.BoolFlag{
			Name:  "tls,t",
			Usage: "http address to listen on",
		},
		cli.StringFlag{
			Name:  "storage-type,s",
			Value: "file",
			Usage: "valid entries: file,inmemory",
		},
	}
	app.Action = func(c *cli.Context) {
		tls := c.Bool("tls")
		storageTypeStr := c.String("storage-type")
		address := c.String("http-address")
		log.Println(address)
		certFile := c.String("cert")
		keyFile := c.String("key")
		storageType := getStorageType(storageTypeStr)
		serverConfig := server.ServerConfig{
			Address:     address,
			Tls:         tls,
			CertFile:    certFile,
			KeyFile:     keyFile,
			StorageType: storageType,
		}
		server.Start(serverConfig)
	}
	app.Run(os.Args)
}

func getStorageType(input string) server.StorageType {
	switch {
	case input == "file":
		return server.FileStorage
	case input == "inmemory":
		return server.InMemoryStorage
	default:
		{
			log.Println("Unknown storage type:", input)
			log.Println("Choosing default storage type as 'file'..")
			return server.FileStorage
		}
	}
}
<commit_msg>Remove redundant --tls flag<commit_after>package main

import (
	"log"
	"os"

	"github.com/codegangsta/cli"
	"github.com/minio-io/minio/pkg/server"
)

func main() {
	app := cli.NewApp()
	app.Name = "minio"
	app.Usage = ""
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "http-address,a",
			Value: ":8080",
			Usage: "http address to listen on",
		},
		cli.StringFlag{
			Name:  "cert,c",
			Value: "",
			Usage: "cert.pem",
		},
		cli.StringFlag{
			Name:  "key,k",
			Value: "",
			Usage: "key.pem",
		},
		cli.StringFlag{
			Name:  "storage-type,s",
			Value: "file",
			Usage: "valid entries: file,inmemory",
		},
	}
	app.Action = func(c *cli.Context) {
		storageTypeStr := c.String("storage-type")
		address := c.String("http-address")
		log.Println(address)
		certFile := c.String("cert")
		keyFile := c.String("key")
		tls := (certFile != "" && keyFile != "")
		storageType := getStorageType(storageTypeStr)
		serverConfig := server.ServerConfig{
			Address:     address,
			Tls:         tls,
			CertFile:    certFile,
			KeyFile:     keyFile,
			StorageType: storageType,
		}
		server.Start(serverConfig)
	}
	app.Run(os.Args)
}

func getStorageType(input string) server.StorageType {
	switch {
	case input == "file":
		return server.FileStorage
	case input == "inmemory":
		return server.InMemoryStorage
	default:
		{
			log.Println("Unknown storage type:", input)
			log.Println("Choosing default storage type as 'file'..")
			return server.FileStorage
		}
	}
}
<|endoftext|>


<commit_before>package main

import "net"
import "fmt"

func getDocker0Network() net.IPNet {
	iface, _ := net.InterfaceByName("docker0")
	addresses, _ := iface.Addrs()
	docker0IP := net.ParseIP(addresses[0].String())

	return net.IPNet{
		IP:   docker0IP,
		Mask: docker0IP.DefaultMask(),
	}
}

func getIps(
	excludeLocalhost bool,
	excludeDockerNetwork bool,
	separator string) []string {

	adresses, _ := net.InterfaceAddrs()
	ips := make([]string, 0)

	docker0Network := getDocker0Network()

	for _, addr := range adresses {
		parsedIP := net.ParseIP(addr.String())

		fmt.Println(addr.String())

		if excludeLocalhost && parsedIP.IsLoopback() {
			continue
		} else if excludeDockerNetwork && docker0Network.Contains(parsedIP) {
			continue
		} else {
			ips = append(ips, parsedIP.String())
		}

		fmt.Println(parsedIP.String())
	}

	return ips
}

func main() {
	fmt.Println(getIps(true, true, ","))
}
<commit_msg>Checkpoint<commit_after>package main

import (
	"fmt"
	"net"
	"strings"
)

func getDocker0Network() net.IPNet {
	iface, _ := net.InterfaceByName("docker0")
	addresses, _ := iface.Addrs()
	docker0IP := net.ParseIP(addresses[0].String())

	return net.IPNet{
		IP:   docker0IP,
		Mask: docker0IP.DefaultMask(),
	}
}

func getIps(
	excludeLocalhost bool,
	excludeDockerNetwork bool,
	onlyipv4 bool,
	onlyipv6 bool) []string {

	adresses, _ := net.InterfaceAddrs()
	ips := make([]string, 0)

	docker0Network := getDocker0Network()

	for _, addr := range adresses {
		parsedIP, _, _ := net.ParseCIDR(addr.String())

		if excludeLocalhost && parsedIP.IsLoopback() {
			continue
		} else if excludeDockerNetwork && docker0Network.Contains(parsedIP) {
			continue
		} else if onlyipv4 && parsedIP.To4() == nil {
			continue
		} else if onlyipv6 && parsedIP.To4() != nil {
			continue
		}

		ips = append(ips, parsedIP.String())
	}

	return ips
}

func formatOutput(ips []string, separator string) string {
	return strings.Join(ips, separator)
}

func main() {
	excludeLocalhost := false
	excludeDockerNetwork := true
	onlyipv4 := true
	onlyipv6 := false
	separator := ","

	ips := getIps(
		excludeLocalhost,
		excludeDockerNetwork,
		onlyipv4,
		onlyipv6,
	)

	output := formatOutput(ips, separator)

	fmt.Println(output)
}
<|endoftext|>


<commit_before>package hush // import "github.com/mndrix/hush"

import (
	"fmt"
	"os"
)

// Main implements the main() function of the hush command line tool.
func Main() {
	if len(os.Args) < 2 {
		usage()
		return
	}

	// handle init command before loading tree
	switch os.Args[1] {
	case "help":
		CmdHelp(os.Stdout)
		return
	case "init":
		err := CmdInit(os.Stderr, os.Stdin)
		if err != nil {
			die("%s", err.Error())
		}
		return
	}

	// load tree for all other commands
	tree, err := LoadTree()
	if os.IsNotExist(err) {
		filename, _ := HushPath()
		fmt.Fprintf(os.Stderr, "hush file does not exist: %s\n", filename)
		fmt.Fprintf(os.Stderr, "Maybe you need to run 'hush init'?\n")
		os.Exit(1)
	}
	if err == nil {
		err = setPassphrase(tree)
	}
	if err != nil {
		die("%s", err.Error())
	}

	// dispatch to command
	switch os.Args[1] {
	case "export": // hush export
		err = CmdExport(os.Stdout, tree)
	case "import":
		var warnings []string
		warnings, err = CmdImport(os.Stdin, tree)
		for _, warning := range warnings {
			warn(warning)
		}
	case "ls":
		if len(os.Args) < 3 {
			tree.Print(os.Stdout)
			return
		}
		err = CmdLs(os.Stdout, tree, os.Args[2])
	case "rm":
		paths := make([]Path, len(os.Args)-2)
		for i := 2; i < len(os.Args); i++ {
			paths[i-2] = NewPath(os.Args[i])
		}
		err = CmdRm(tree, paths)
	case "set":
		if len(os.Args) < 4 {
			die("Usage: hush set path value")
		}
		p := NewPath(os.Args[2])
		v, err := CaptureValue(os.Args[3])
		if err != nil {
			die("%s", err.Error())
		}
		err = CmdSet(os.Stdout, tree, p, v)
	default:
		usage()
	}
	if err != nil {
		die("%s", err.Error())
	}
}

func usage() {
	die("Usage: hush [command [arguments]]")
}

func setPassphrase(t *Tree) error {
	password, err := AskPassword(os.Stderr, "Password")
	if err != nil {
		return err
	}

	return t.SetPassphrase(password)
}

func die(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
	os.Exit(1)
}

func warn(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
}
<commit_msg>Don't shadow err<commit_after>package hush // import "github.com/mndrix/hush"

import (
	"fmt"
	"os"
)

// Main implements the main() function of the hush command line tool.
func Main() {
	if len(os.Args) < 2 {
		usage()
		return
	}

	// handle init command before loading tree
	switch os.Args[1] {
	case "help":
		CmdHelp(os.Stdout)
		return
	case "init":
		err := CmdInit(os.Stderr, os.Stdin)
		if err != nil {
			die("%s", err.Error())
		}
		return
	}

	// load tree for all other commands
	tree, err := LoadTree()
	if os.IsNotExist(err) {
		filename, _ := HushPath()
		fmt.Fprintf(os.Stderr, "hush file does not exist: %s\n", filename)
		fmt.Fprintf(os.Stderr, "Maybe you need to run 'hush init'?\n")
		os.Exit(1)
	}
	if err == nil {
		err = setPassphrase(tree)
	}
	if err != nil {
		die("%s", err.Error())
	}

	// dispatch to command
	switch os.Args[1] {
	case "export": // hush export
		err = CmdExport(os.Stdout, tree)
	case "import":
		var warnings []string
		warnings, err = CmdImport(os.Stdin, tree)
		for _, warning := range warnings {
			warn(warning)
		}
	case "ls":
		if len(os.Args) < 3 {
			tree.Print(os.Stdout)
			return
		}
		err = CmdLs(os.Stdout, tree, os.Args[2])
	case "rm":
		paths := make([]Path, len(os.Args)-2)
		for i := 2; i < len(os.Args); i++ {
			paths[i-2] = NewPath(os.Args[i])
		}
		err = CmdRm(tree, paths)
	case "set":
		if len(os.Args) < 4 {
			die("Usage: hush set path value")
		}
		p := NewPath(os.Args[2])
		var v *Value
		v, err = CaptureValue(os.Args[3])
		if err != nil {
			die("%s", err.Error())
		}
		err = CmdSet(os.Stdout, tree, p, v)
	default:
		usage()
	}
	if err != nil {
		die("%s", err.Error())
	}
}

func usage() {
	die("Usage: hush [command [arguments]]")
}

func setPassphrase(t *Tree) error {
	password, err := AskPassword(os.Stderr, "Password")
	if err != nil {
		return err
	}

	return t.SetPassphrase(password)
}

func die(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
	os.Exit(1)
}

func warn(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
}
<|endoftext|>