<commit_before>package main

import (
    "log"
    "math/rand"
    "time"
)

func main() {
    log.Print("started.")

    // チャネル
    sleep1_finished := make(chan bool)

    go func() {
        // 1秒かかるコマンド
        log.Print("sleep1 started.")
        time.Sleep(1 * time.Second)
        log.Print("sleep1 finished.")
        sleep1_finished <- true
    }()

    // 終わるまで待つ
    <- sleep1_finished

    dice()
}

func dice() {
    log.Printf("%v", random())
}

// http://qiita.com/cubicdaiya/items/819886c57e9d17e4b019
func random()(int) {
    rand.Seed(time.Now().UnixNano())
    return rand.Intn(15)
}
<commit_msg>Update<commit_after>package main

import (
    "log"
    "math/rand"
    "time"
)

func main() {
    log.Print("started.")

    // チャネル
    sleep1_finished := make(chan bool)

    go func() {
        // 1秒かかるコマンド
        log.Print("sleep1 started.")
        time.Sleep(1 * time.Second)
        log.Print("sleep1 finished.")
        sleep1_finished <- true
    }()

    // 終わるまで待つ
    <- sleep1_finished

    dice()
}

func dice() {
    log.Printf("%v", random())
}

// http://qiita.com/cubicdaiya/items/819886c57e9d17e4b019
// 3までの数字をランダムに返す
func random()(int) {
    rand.Seed(time.Now().UnixNano())
    return rand.Intn(4)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"strings"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/google/go-github/github"
)

var isDelete = flag.Bool("delete", false, "delete all tweets before posting")
var logLevel = flag.String("loglevel", "warning", "log level (panic, fatal, error, warn or warning, info, debug)")
var lastPosted int

func updateTwitter(g *Github, t *Twitter) {
	// tweetCutie posts cutie from pull request pull to twitter
	tweetCutie := func(pull *github.Issue) error {
		if pull.Body == nil {
			return nil
		}
		cutie, err := GetCutieFromPull(pull)
		if err != nil {
			switch err {
			case errImageNotFound:

			case errIsScreenshot:
				log.WithFields(log.Fields{"number": *pull.Number, "URL": *pull.HTMLURL}).Warn("Screenshot detected")
				t.Notify(fmt.Sprintf("Screenshot detected: %s", *pull.HTMLURL))
			default:
				log.WithFields(log.Fields{"since": lastPosted + 1}).WithError(err).Error("For pull requests since")
				t.Notify(fmt.Sprintf("Cannot get cutie from pull request %d, %s: %s", *pull.Number, *pull.HTMLURL, err))
				// return err
			}
			return nil
		}
		if cutie != "" {
			log.WithFields(log.Fields{"number": *pull.Number, "URL": *pull.HTMLURL}).Info("Cutie")
			msg := fmt.Sprintf("%s #dockercuties #docker", *pull.HTMLURL)
			if err := t.PostToTwitter(cutie, msg); err != nil {
				t.Notify(fmt.Sprintf("Cannot post tweet: %s", err))
				return err
			}
			lastPosted = *pull.Number
		}
		return nil
	}
	log.WithFields(log.Fields{"number": lastPosted}).Debug("Last posted")
	if lastPosted > 0 {
		if err := g.PullsSinceFunc(lastPosted+1, tweetCutie); err != nil {
			if strings.Contains(err.Error(), "404 Not Found") {
				log.WithFields(log.Fields{"Owner": Owner, "Repo": Repo, "number": lastPosted + 1}).Debug("Issue not found")
				return
			}
			log.WithFields(log.Fields{"since": lastPosted + 1}).WithError(err).Error("For pull requests since")
			t.Notify(fmt.Sprintf("Error for pull requests since %d: %s", lastPosted+1, err))
			return
		}
	} else {
		if err := g.PullsSinceFunc(StartCutiePullReq, tweetCutie); err != nil {
			log.WithFields(log.Fields{"since": StartCutiePullReq}).WithError(err).Error("For pull requests since")
			t.Notify(fmt.Sprintf("Error for pull requests since %d: %s", StartCutiePullReq, err))
			return
		}
	}
}

func main() {
	flag.Parse()
	lvl, err := log.ParseLevel(*logLevel)
	if err != nil {
		log.WithFields(log.Fields{"log level": *logLevel}).WithError(err).Fatal("Cannot parse log level")
	}
	log.SetLevel(lvl)

	tokens, err := LoadTokens()
	log.Info("Tokens are loaded")
	if err != nil {
		log.WithError(err).Fatal("Cannot parse tokens")
		return
	}

	t := NewTwitter(tokens.twitter)
	log.Info("Connect to twitter")
	gh := NewGithub(tokens.github)
	log.Info("Connect to github")

	if *isDelete {
		if err := t.DeleteAllTweets(TwitterUser); err != nil {
			log.WithFields(log.Fields{"User": TwitterUser}).WithError(err).Error("Cannot delete all tweets")
			t.Notify(fmt.Sprintf("Cannot delete all tweets: %s", err))
			return
		}
	}

	// // Single post by number
	// n := 32085
	// if err = gh.PullFunc(n, tweetCutie); err != nil {
	// 	log.WithFields(log.Fields{"number": n}).WithError(err).Error("For pull request")
	// 	return
	// }
	// return

	lastPosted = t.LastPostedPull()

	for range time.Tick(60 * time.Second) {
		updateTwitter(gh, t)
	}
}
<commit_msg>Fix lastPosted to skip error after last screenshot<commit_after>package main

import (
	"flag"
	"fmt"
	"strings"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/google/go-github/github"
)

var isDelete = flag.Bool("delete", false, "delete all tweets before posting")
var logLevel = flag.String("loglevel", "warning", "log level (panic, fatal, error, warn or warning, info, debug)")
var lastPosted int

func updateTwitter(g *Github, t *Twitter) {
	// tweetCutie posts cutie from pull request pull to twitter
	tweetCutie := func(pull *github.Issue) error {
		if pull.Body == nil {
			return nil
		}
		cutie, err := GetCutieFromPull(pull)
		if err != nil {
			switch err {
			case errImageNotFound:

			case errIsScreenshot:
				log.WithFields(log.Fields{"number": *pull.Number, "URL": *pull.HTMLURL}).Warn("Screenshot detected")
				t.Notify(fmt.Sprintf("Screenshot detected: %s", *pull.HTMLURL))
				lastPosted = *pull.Number
			default:
				log.WithFields(log.Fields{"since": lastPosted + 1}).WithError(err).Error("For pull requests since")
				t.Notify(fmt.Sprintf("Cannot get cutie from pull request %d, %s: %s", *pull.Number, *pull.HTMLURL, err))
			}
			return nil
		}
		if cutie != "" {
			log.WithFields(log.Fields{"number": *pull.Number, "URL": *pull.HTMLURL}).Info("Cutie")
			msg := fmt.Sprintf("%s #dockercuties #docker", *pull.HTMLURL)
			if err := t.PostToTwitter(cutie, msg); err != nil {
				t.Notify(fmt.Sprintf("Cannot post tweet: %s", err))
				return err
			}
			lastPosted = *pull.Number
		}
		return nil
	}
	log.WithFields(log.Fields{"number": lastPosted}).Debug("Last posted")
	if lastPosted > 0 {
		if err := g.PullsSinceFunc(lastPosted+1, tweetCutie); err != nil {
			if strings.Contains(err.Error(), "404 Not Found") {
				log.WithFields(log.Fields{"Owner": Owner, "Repo": Repo, "number": lastPosted + 1}).Debug("Issue not found")
				return
			}
			log.WithFields(log.Fields{"since": lastPosted + 1}).WithError(err).Error("For pull requests since")
			t.Notify(fmt.Sprintf("Error for pull requests since %d: %s", lastPosted+1, err))
			return
		}
	} else {
		if err := g.PullsSinceFunc(StartCutiePullReq, tweetCutie); err != nil {
			log.WithFields(log.Fields{"since": StartCutiePullReq}).WithError(err).Error("For pull requests since")
			t.Notify(fmt.Sprintf("Error for pull requests since %d: %s", StartCutiePullReq, err))
			return
		}
	}
}

func main() {
	flag.Parse()
	lvl, err := log.ParseLevel(*logLevel)
	if err != nil {
		log.WithFields(log.Fields{"log level": *logLevel}).WithError(err).Fatal("Cannot parse log level")
	}
	log.SetLevel(lvl)

	tokens, err := LoadTokens()
	log.Info("Tokens are loaded")
	if err != nil {
		log.WithError(err).Fatal("Cannot parse tokens")
		return
	}

	t := NewTwitter(tokens.twitter)
	log.Info("Connect to twitter")
	gh := NewGithub(tokens.github)
	log.Info("Connect to github")

	if *isDelete {
		if err := t.DeleteAllTweets(TwitterUser); err != nil {
			log.WithFields(log.Fields{"User": TwitterUser}).WithError(err).Error("Cannot delete all tweets")
			t.Notify(fmt.Sprintf("Cannot delete all tweets: %s", err))
			return
		}
	}

	// // Single post by number
	// n := 32085
	// if err = gh.PullFunc(n, tweetCutie); err != nil {
	// 	log.WithFields(log.Fields{"number": n}).WithError(err).Error("For pull request")
	// 	return
	// }
	// return

	lastPosted = t.LastPostedPull()

	for range time.Tick(60 * time.Second) {
		updateTwitter(gh, t)
	}
}
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

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

	"github.com/line/line-bot-sdk-go/linebot"
)

var bot *linebot.Client

func main() {
	var err error
	bot, err = linebot.New(os.Getenv("ChannelSecret"), os.Getenv("ChannelAccessToken"))
	log.Println("Bot:", bot, " err:", err)
	http.HandleFunc("/callback", callbackHandler)
	port := os.Getenv("PORT")
	addr := fmt.Sprintf(":%s", port)
	http.ListenAndServe(addr, nil)
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	events, err := bot.ParseRequest(r)

	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}

	for _, event := range events {
		if event.Type == linebot.EventTypeMessage {
			switch message := event.Message.(type) {
			case *linebot.TextMessage:
				if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.ID+":"+message.Text+" OK!")).Do(); err != nil {
					log.Print(err)
				}
			}
		}
	}
}
<commit_msg>Simsimi test<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

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

	"github.com/line/line-bot-sdk-go/linebot"
)

var bot *linebot.Client

func main() {
	var err error
	bot, err = linebot.New(os.Getenv("ChannelSecret"), os.Getenv("ChannelAccessToken"))
	log.Println("Bot:", bot, " err:", err)
	http.HandleFunc("/callback", callbackHandler)
	port := os.Getenv("PORT")
	addr := fmt.Sprintf(":%s", port)
	http.ListenAndServe(addr, nil)
}

func getSimsimi(word string){
	resp, err := http.Get("http://sandbox.api.simsimi.com/request.p?key=1b4f97fa-a422-45f0-8faf-0122ddd2dc5c&lc=id&ft=1.0&text=" + word)
	if err != nil{
		log.Print(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	return string(body)
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	events, err := bot.ParseRequest(r)

	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}

	for _, event := range events {
		if event.Type == linebot.EventTypeMessage {
			switch message := event.Message.(type) {
			case *linebot.TextMessage:
				if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.ID+":"+message.Text+" -> " getSimsimi(message.Text))).Do(); err != nil {
					log.Print(err)
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/ambientsound/pms/console"
	"github.com/ambientsound/pms/input"
	"github.com/ambientsound/pms/input/commands"
	"github.com/ambientsound/pms/options"
	"github.com/ambientsound/pms/pms"
	"github.com/ambientsound/pms/version"
	"github.com/ambientsound/pms/widgets"

	"github.com/jessevdk/go-flags"
)

var buildVersion string = "undefined"

type Options struct {
	Version     bool   `short:"v" long:"version" description:"Print program version"`
	MpdHost     string `long:"host" description:"MPD host (MPD_HOST environment variable)" default:"localhost"`
	MpdPort     string `long:"port" description:"MPD port (MPD_PORT environment variable)" default:"6600"`
	MpdPassword string `long:"password" description:"MPD password"`
}

func main() {
	var timer time.Time
	var opts Options

	version.SetVersion(buildVersion)
	fmt.Printf("%s %s\n", version.LongName(), version.Version())

	remainder, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}
	if len(remainder) > 0 {
		trailing := strings.Join(remainder, " ")
		fmt.Printf("error: trailing characters: %s\n", trailing)
		os.Exit(1)
	}

	if opts.Version {
		os.Exit(0)
	}

	val, ok := os.LookupEnv("MPD_HOST")
	if ok {
		opts.MpdHost = val
	}
	val, ok = os.LookupEnv("MPD_PORT")
	if ok {
		opts.MpdPort = val
	}

	pms := pms.New()

	timer = time.Now()
	ui := widgets.NewUI()
	ui.Start()
	defer ui.Quit()
	console.Log("UI initialized in %s", time.Since(timer).String())

	// Set up the command-line interface
	pms.Interface = input.NewInterface()
	pms.Interface.Register("se", commands.NewSet(pms.Options))
	pms.Interface.Register("set", commands.NewSet(pms.Options))

	lines := strings.Split(options.Defaults, "\n")
	for _, line := range lines {
		err = pms.Interface.Execute(line)
		if err != nil {
			console.Log("Error while reading default configuration: %s", err)
		}
	}

	pms.SetConnectionParams(opts.MpdHost, opts.MpdPort, opts.MpdPassword)
	go pms.LoopConnect()

	go func() {
		for {
			select {
			case <-pms.EventLibrary:
				console.Log("Song library updated in MPD, assigning to UI")
				ui.App.PostFunc(func() {
					ui.Songlist.SetSongList(pms.Library)
					ui.SetDefaultSonglist(pms.Library)
					ui.App.Update()
				})
			case <-pms.EventIndex:
				console.Log("Search index updated, assigning to UI")
				ui.App.PostFunc(func() {
					ui.SetIndex(pms.Index)
				})
			case <-pms.EventPlayer:
				ui.App.PostFunc(func() {
					ui.Playbar.SetPlayerStatus(pms.MpdStatus)
					ui.Playbar.SetSong(pms.CurrentSong)
					ui.App.Update()
				})
			case s := <-ui.EventInputCommand:
				console.Log("Input command received from Multibar: %s", s)
				err = pms.Interface.Execute(s)
				if err != nil {
					console.Log("Error: %s", err)
				}
			}
		}
	}()

	ui.Wait()

	console.Log("Exiting normally.")
}
<commit_msg>Fix linter errors in main module<commit_after>package main

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/ambientsound/pms/console"
	"github.com/ambientsound/pms/input"
	"github.com/ambientsound/pms/input/commands"
	"github.com/ambientsound/pms/options"
	"github.com/ambientsound/pms/pms"
	"github.com/ambientsound/pms/version"
	"github.com/ambientsound/pms/widgets"

	"github.com/jessevdk/go-flags"
)

var buildVersion = "undefined"

type cliOptions struct {
	Version     bool   `short:"v" long:"version" description:"Print program version"`
	MpdHost     string `long:"host" description:"MPD host (MPD_HOST environment variable)" default:"localhost"`
	MpdPort     string `long:"port" description:"MPD port (MPD_PORT environment variable)" default:"6600"`
	MpdPassword string `long:"password" description:"MPD password"`
}

func main() {
	var timer time.Time
	var opts cliOptions

	version.SetVersion(buildVersion)
	fmt.Printf("%s %s\n", version.LongName(), version.Version())

	remainder, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}
	if len(remainder) > 0 {
		trailing := strings.Join(remainder, " ")
		fmt.Printf("error: trailing characters: %s\n", trailing)
		os.Exit(1)
	}

	if opts.Version {
		os.Exit(0)
	}

	val, ok := os.LookupEnv("MPD_HOST")
	if ok {
		opts.MpdHost = val
	}
	val, ok = os.LookupEnv("MPD_PORT")
	if ok {
		opts.MpdPort = val
	}

	pms := pms.New()

	timer = time.Now()
	ui := widgets.NewUI()
	ui.Start()
	defer ui.Quit()
	console.Log("UI initialized in %s", time.Since(timer).String())

	// Set up the command-line interface
	pms.Interface = input.NewInterface()
	pms.Interface.Register("se", commands.NewSet(pms.Options))
	pms.Interface.Register("set", commands.NewSet(pms.Options))

	lines := strings.Split(options.Defaults, "\n")
	for _, line := range lines {
		err = pms.Interface.Execute(line)
		if err != nil {
			console.Log("Error while reading default configuration: %s", err)
		}
	}

	pms.SetConnectionParams(opts.MpdHost, opts.MpdPort, opts.MpdPassword)
	go pms.LoopConnect()

	go func() {
		for {
			select {
			case <-pms.EventLibrary:
				console.Log("Song library updated in MPD, assigning to UI")
				ui.App.PostFunc(func() {
					ui.Songlist.SetSongList(pms.Library)
					ui.SetDefaultSonglist(pms.Library)
					ui.App.Update()
				})
			case <-pms.EventIndex:
				console.Log("Search index updated, assigning to UI")
				ui.App.PostFunc(func() {
					ui.SetIndex(pms.Index)
				})
			case <-pms.EventPlayer:
				ui.App.PostFunc(func() {
					ui.Playbar.SetPlayerStatus(pms.MpdStatus)
					ui.Playbar.SetSong(pms.CurrentSong)
					ui.App.Update()
				})
			case s := <-ui.EventInputCommand:
				console.Log("Input command received from Multibar: %s", s)
				err = pms.Interface.Execute(s)
				if err != nil {
					console.Log("Error: %s", err)
				}
			}
		}
	}()

	ui.Wait()

	console.Log("Exiting normally.")
}
<|endoftext|>


<commit_before>// Cozy Cloud is a personal platform as a service with a focus on data.
// Cozy Cloud can be seen as 4 layers, from inside to outside:
//
// 1. A place to keep your personal data
//
// 2. A core API to handle the data
//
// 3. Your web apps, and also the mobile & desktop clients
//
// 4. A coherent User Experience
//
// It's also a set of values: Simple, Versatile, Yours. These values mean a lot
// for Cozy Cloud in all aspects. From an architectural point, it declines to:
//
// - Simple to deploy and understand, not built as a galaxy of optimized
// microservices managed by kubernetes that only experts can debug.
//
// - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on
// multiple servers by specialized hosting. Users can install apps.
//
// - Yours, you own your data and you control it. If you want to take back your
// data to go elsewhere, you can.
package main

import "github.com/cozy/cozy-stack/cmd"

func main() {
	cmd.Execute()
}
<commit_msg>Handle error when running the root command<commit_after>// Cozy Cloud is a personal platform as a service with a focus on data.
// Cozy Cloud can be seen as 4 layers, from inside to outside:
//
// 1. A place to keep your personal data
//
// 2. A core API to handle the data
//
// 3. Your web apps, and also the mobile & desktop clients
//
// 4. A coherent User Experience
//
// It's also a set of values: Simple, Versatile, Yours. These values mean a lot
// for Cozy Cloud in all aspects. From an architectural point, it declines to:
//
// - Simple to deploy and understand, not built as a galaxy of optimized
// microservices managed by kubernetes that only experts can debug.
//
// - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on
// multiple servers by specialized hosting. Users can install apps.
//
// - Yours, you own your data and you control it. If you want to take back your
// data to go elsewhere, you can.
package main

import (
	"fmt"
	"os"

	"github.com/cozy/cozy-stack/cmd"
)

func main() {
	if err := cmd.RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/lair-framework/api-server/client"
	"github.com/lair-framework/go-lair"
	"github.com/tomsteele/blacksheepwall/bsw"
)

const (
	version = "2.0.0"
	tool    = "blacksheepwall"
	usage   = `
Parses a blacksheepwall JSON file into a lair project.

Usage:
  drone-blacksheepwall <id> <filename>
  export LAIR_ID=<id>; drone-blacksheepwall <filename>
Options:
  -v              show version and exit
  -h              show usage and exit
  -k              allow insecure SSL connections
  -force-ports    disable data protection in the API server for excessive ports
  -tags           a comma separated list of tags to add to every host that is imported
`
)

func main() {
	showVersion := flag.Bool("v", false, "")
	insecureSSL := flag.Bool("k", false, "")
	forcePorts := flag.Bool("force-ports", false, "")
	tags := flag.String("tags", "", "")
	flag.Usage = func() {
		fmt.Println(usage)
	}
	flag.Parse()
	if *showVersion {
		log.Println(version)
		os.Exit(0)
	}
	lairURL := os.Getenv("LAIR_API_SERVER")
	if lairURL == "" {
		log.Fatal("Fatal: Missing LAIR_API_SERVER environment variable")
	}
	lairPID := os.Getenv("LAIR_ID")
	var filename string
	switch len(flag.Args()) {
	case 2:
		lairPID = flag.Arg(0)
		filename = flag.Arg(1)
	case 1:
		filename = flag.Arg(0)
	default:
		log.Fatal("Fatal: Missing required argument")
	}

	u, err := url.Parse(lairURL)
	if err != nil {
		log.Fatalf("Fatal: Error parsing LAIR_API_SERVER URL. Error %s", err.Error())
	}
	if u.User == nil {
		log.Fatal("Fatal: Missing username and/or password")
	}
	user := u.User.Username()
	pass, _ := u.User.Password()
	if user == "" || pass == "" {
		log.Fatal("Fatal: Missing username and/or password")
	}
	c, err := client.New(&client.COptions{
		User:               user,
		Password:           pass,
		Host:               u.Host,
		Scheme:             u.Scheme,
		InsecureSkipVerify: *insecureSSL,
	})
	if err != nil {
		log.Fatalf("Fatal: Error setting up client: Error %s", err.Error())
	}
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatalf("Fatal: Could not open file. Error %s", err.Error())
	}
	hostTags := []string{}
	if *tags != "" {
		hostTags = strings.Split(*tags, ",")
	}
	tagSet := map[string]bool{}
	bResults := bsw.Results{}
	if err := json.Unmarshal(data, &bResults); err != nil {
		log.Fatalf("Fatal: Could not parse JSON. Error %s", err.Error())
	}
	bNotFound := map[string]bool{}

	exproject, err := c.ExportProject(lairPID)
	if err != nil {
		log.Fatalf("Fatal: Unable to export project. Error %s", err.Error())
	}

	project := &lair.Project{
		ID:   lairPID,
		Tool: tool,
		Commands: []lair.Command{lair.Command{
			Tool: tool,
		}},
	}

	for _, result := range bResults {
		found := false
		for i := range exproject.Hosts {
			h := exproject.Hosts[i]
			if result.IP == h.IPv4 {
				exproject.Hosts[i].Hostnames = append(exproject.Hosts[i].Hostnames, result.Hostname)
				exproject.Hosts[i].LastModifiedBy = tool
				found = true
				if _, ok := tagSet[h.IPv4]; !ok {
					tagSet[h.IPv4] = true
					exproject.Hosts[i].Tags = append(exproject.Hosts[i].Tags, hostTags...)
				}
			}
			if !found {
				bNotFound[result.IP] = true
			}
		}
	}

	for _, h := range exproject.Hosts {
		project.Hosts = append(project.Hosts, lair.Host{
			IPv4:           h.IPv4,
			LongIPv4Addr:   h.LongIPv4Addr,
			IsFlagged:      h.IsFlagged,
			LastModifiedBy: h.LastModifiedBy,
			MAC:            h.MAC,
			OS:             h.OS,
			Status:         h.Status,
			StatusMessage:  h.StatusMessage,
			Tags:           hostTags,
			Hostnames:      h.Hostnames,
		})
	}

	res, err := c.ImportProject(&client.DOptions{ForcePorts: *forcePorts}, project)
	if err != nil {
		log.Fatalf("Fatal: Unable to import project. Error %s", err)
	}

	defer res.Body.Close()
	droneRes := &client.Response{}
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalf("Fatal: Error %s", err.Error())
	}
	if err := json.Unmarshal(body, droneRes); err != nil {
		log.Fatalf("Fatal: Could not unmarshal JSON. Error %s", err.Error())
	}
	if droneRes.Status == "Error" {
		log.Fatalf("Fatal: Import failed. Error %s", droneRes.Message)
	}

	if len(bNotFound) > 0 {
		log.Println("Info: The following hosts had hostnames but could not be imported because they do not exist in lair")
	}
	for k := range bNotFound {
		fmt.Println(k)
	}
	log.Println("Success: Operation completed successfully")
}
<commit_msg>updated help info<commit_after>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/lair-framework/api-server/client"
	"github.com/lair-framework/go-lair"
	"github.com/tomsteele/blacksheepwall/bsw"
)

const (
	version = "2.0.0"
	tool    = "blacksheepwall"
	usage   = `
Parses a blacksheepwall JSON file into a lair project.

Usage:
  drone-blacksheepwall [options] <id> <filename>
  export LAIR_ID=<id>; drone-blacksheepwall [options] <filename>
Options:
  -v              show version and exit
  -h              show usage and exit
  -k              allow insecure SSL connections
  -force-ports    disable data protection in the API server for excessive ports
  -tags           a comma separated list of tags to add to every host that is imported
`
)

func main() {
	showVersion := flag.Bool("v", false, "")
	insecureSSL := flag.Bool("k", false, "")
	forcePorts := flag.Bool("force-ports", false, "")
	tags := flag.String("tags", "", "")
	flag.Usage = func() {
		fmt.Println(usage)
	}
	flag.Parse()
	if *showVersion {
		log.Println(version)
		os.Exit(0)
	}
	lairURL := os.Getenv("LAIR_API_SERVER")
	if lairURL == "" {
		log.Fatal("Fatal: Missing LAIR_API_SERVER environment variable")
	}
	lairPID := os.Getenv("LAIR_ID")
	var filename string
	switch len(flag.Args()) {
	case 2:
		lairPID = flag.Arg(0)
		filename = flag.Arg(1)
	case 1:
		filename = flag.Arg(0)
	default:
		log.Fatal("Fatal: Missing required argument")
	}

	u, err := url.Parse(lairURL)
	if err != nil {
		log.Fatalf("Fatal: Error parsing LAIR_API_SERVER URL. Error %s", err.Error())
	}
	if u.User == nil {
		log.Fatal("Fatal: Missing username and/or password")
	}
	user := u.User.Username()
	pass, _ := u.User.Password()
	if user == "" || pass == "" {
		log.Fatal("Fatal: Missing username and/or password")
	}
	c, err := client.New(&client.COptions{
		User:               user,
		Password:           pass,
		Host:               u.Host,
		Scheme:             u.Scheme,
		InsecureSkipVerify: *insecureSSL,
	})
	if err != nil {
		log.Fatalf("Fatal: Error setting up client: Error %s", err.Error())
	}
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatalf("Fatal: Could not open file. Error %s", err.Error())
	}
	hostTags := []string{}
	if *tags != "" {
		hostTags = strings.Split(*tags, ",")
	}
	tagSet := map[string]bool{}
	bResults := bsw.Results{}
	if err := json.Unmarshal(data, &bResults); err != nil {
		log.Fatalf("Fatal: Could not parse JSON. Error %s", err.Error())
	}
	bNotFound := map[string]bool{}

	exproject, err := c.ExportProject(lairPID)
	if err != nil {
		log.Fatalf("Fatal: Unable to export project. Error %s", err.Error())
	}

	project := &lair.Project{
		ID:   lairPID,
		Tool: tool,
		Commands: []lair.Command{lair.Command{
			Tool: tool,
		}},
	}

	for _, result := range bResults {
		found := false
		for i := range exproject.Hosts {
			h := exproject.Hosts[i]
			if result.IP == h.IPv4 {
				exproject.Hosts[i].Hostnames = append(exproject.Hosts[i].Hostnames, result.Hostname)
				exproject.Hosts[i].LastModifiedBy = tool
				found = true
				if _, ok := tagSet[h.IPv4]; !ok {
					tagSet[h.IPv4] = true
					exproject.Hosts[i].Tags = append(exproject.Hosts[i].Tags, hostTags...)
				}
			}
			if !found {
				bNotFound[result.IP] = true
			}
		}
	}

	for _, h := range exproject.Hosts {
		project.Hosts = append(project.Hosts, lair.Host{
			IPv4:           h.IPv4,
			LongIPv4Addr:   h.LongIPv4Addr,
			IsFlagged:      h.IsFlagged,
			LastModifiedBy: h.LastModifiedBy,
			MAC:            h.MAC,
			OS:             h.OS,
			Status:         h.Status,
			StatusMessage:  h.StatusMessage,
			Tags:           hostTags,
			Hostnames:      h.Hostnames,
		})
	}

	res, err := c.ImportProject(&client.DOptions{ForcePorts: *forcePorts}, project)
	if err != nil {
		log.Fatalf("Fatal: Unable to import project. Error %s", err)
	}

	defer res.Body.Close()
	droneRes := &client.Response{}
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalf("Fatal: Error %s", err.Error())
	}
	if err := json.Unmarshal(body, droneRes); err != nil {
		log.Fatalf("Fatal: Could not unmarshal JSON. Error %s", err.Error())
	}
	if droneRes.Status == "Error" {
		log.Fatalf("Fatal: Import failed. Error %s", droneRes.Message)
	}

	if len(bNotFound) > 0 {
		log.Println("Info: The following hosts had hostnames but could not be imported because they do not exist in lair")
	}
	for k := range bNotFound {
		fmt.Println(k)
	}
	log.Println("Success: Operation completed successfully")
}
<|endoftext|>


<commit_before>package main

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

var mu sync.Mutex
var count int

func echoString(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "hello, World!")
}

func counter(w http.ResponseWriter, r *http.Request){
    mu.Lock()
    count++
    fmt.Fprintf(w, "Count %d\n", count)
    mu.Unlock()
}

func echoDetails(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "%s", r.Body);
}

func main() {
    http.HandleFunc("/", echoString)
    http.HandleFunc("/count", counter)

    http.HandleFunc("/details", echoDetails)

    http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, r.URL.Path[1:])
    })

    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request){
        fmt.Fprintf(w, "Hi")
    })

    log.Fatal(http.ListenAndServe(":8081", nil))

}<commit_msg>another small commit<commit_after>package main

import (
    "fmt"
    "log"
    "net/http"
    "sync"
)

var mu sync.Mutex
var count int

func echoString(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "hello, World!")
}

func counter(w http.ResponseWriter, r *http.Request){
    mu.Lock()
    count++
    fmt.Fprintf(w, "Count %d\n", count)
    mu.Unlock()
}

func echoDetails(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "%s", r.Body);
}

func returnJson(w https.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "{ 'message' : 'hello world'}");
}

func main() {
    http.HandleFunc("/", echoString)
    http.HandleFunc("/count", counter)

    http.HandleFunc("/json", returnJson)

    http.HandleFunc("/details", echoDetails)

    http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, r.URL.Path[1:])
    })

    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request){
        fmt.Fprintf(w, "Hi")
    })

    log.Fatal(http.ListenAndServe(":8081", nil))

}<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"runtime"

	"github.com/kleister/kleister-cli/cmd"
	"github.com/kleister/kleister-cli/config"
	"github.com/sanbornm/go-selfupdate/selfupdate"
	"github.com/urfave/cli"
)

var (
	updates = "http://dl.webhippie.de/"
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	app := cli.NewApp()
	app.Name = "kleister-cli"
	app.Version = config.Version
	app.Author = "Thomas Boerger <thomas@webhippie.de>"
	app.Usage = "Manage mod packs for the Technic launcher"

	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:   "server, s",
			Value:  "",
			Usage:  "Kleister API server",
			EnvVar: "KLEISTER_SERVER",
		},
		cli.StringFlag{
			Name:   "token, t",
			Value:  "",
			Usage:  "Kleister API token",
			EnvVar: "KLEISTER_TOKEN",
		},
		cli.BoolTFlag{
			Name:   "update, u",
			Usage:  "Enable auto update",
			EnvVar: "KLEISTER_UPDATE",
		},
	}

	app.Before = func(c *cli.Context) error {
		if c.BoolT("update") {
			if config.VersionDev == "dev" {
				fmt.Fprintf(os.Stderr, "Updates are disabled for development versions.\n")
			} else {
				updater := &selfupdate.Updater{
					CurrentVersion: fmt.Sprintf(
						"%d.%d.%d",
						config.VersionMajor,
						config.VersionMinor,
						config.VersionPatch,
					),
					ApiURL:  updates,
					BinURL:  updates,
					DiffURL: updates,
					Dir:     "updates/",
					CmdName: app.Name,
				}

				go updater.BackgroundRun()
			}
		}

		return nil
	}

	app.Commands = []cli.Command{
		cmd.Pack(),
		cmd.Build(),
		cmd.Mod(),
		cmd.Version(),
		cmd.Minecraft(),
		cmd.Forge(),
		cmd.User(),
		cmd.Key(),
		cmd.Client(),
		cmd.Profile(),
	}

	cli.HelpFlag = cli.BoolFlag{
		Name:  "help, h",
		Usage: "Show the help, so what you see now",
	}

	cli.VersionFlag = cli.BoolFlag{
		Name:  "version, v",
		Usage: "Print the current version of that tool",
	}

	app.Run(os.Args)
}
<commit_msg>Simplified usage info<commit_after>package main

import (
	"fmt"
	"os"
	"runtime"

	"github.com/kleister/kleister-cli/cmd"
	"github.com/kleister/kleister-cli/config"
	"github.com/sanbornm/go-selfupdate/selfupdate"
	"github.com/urfave/cli"
)

var (
	updates = "http://dl.webhippie.de/"
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	app := cli.NewApp()
	app.Name = "kleister-cli"
	app.Version = config.Version
	app.Author = "Thomas Boerger <thomas@webhippie.de>"
	app.Usage = "Manage mod packs for Minecraft"

	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:   "server, s",
			Value:  "",
			Usage:  "Kleister API server",
			EnvVar: "KLEISTER_SERVER",
		},
		cli.StringFlag{
			Name:   "token, t",
			Value:  "",
			Usage:  "Kleister API token",
			EnvVar: "KLEISTER_TOKEN",
		},
		cli.BoolTFlag{
			Name:   "update, u",
			Usage:  "Enable auto update",
			EnvVar: "KLEISTER_UPDATE",
		},
	}

	app.Before = func(c *cli.Context) error {
		if c.BoolT("update") {
			if config.VersionDev == "dev" {
				fmt.Fprintf(os.Stderr, "Updates are disabled for development versions.\n")
			} else {
				updater := &selfupdate.Updater{
					CurrentVersion: fmt.Sprintf(
						"%d.%d.%d",
						config.VersionMajor,
						config.VersionMinor,
						config.VersionPatch,
					),
					ApiURL:  updates,
					BinURL:  updates,
					DiffURL: updates,
					Dir:     "updates/",
					CmdName: app.Name,
				}

				go updater.BackgroundRun()
			}
		}

		return nil
	}

	app.Commands = []cli.Command{
		cmd.Pack(),
		cmd.Build(),
		cmd.Mod(),
		cmd.Version(),
		cmd.Minecraft(),
		cmd.Forge(),
		cmd.User(),
		cmd.Key(),
		cmd.Client(),
		cmd.Profile(),
	}

	cli.HelpFlag = cli.BoolFlag{
		Name:  "help, h",
		Usage: "Show the help, so what you see now",
	}

	cli.VersionFlag = cli.BoolFlag{
		Name:  "version, v",
		Usage: "Print the current version of that tool",
	}

	app.Run(os.Args)
}
<|endoftext|>


<commit_before>package main

import (
	log "github.com/Sirupsen/logrus"
	"github.com/joaodias/hugito-app/handlers"
	"net/http"
)

func main() {
	router := handlers.NewRouter()
	router.Handle("repositories get", handlers.GetRepository)
	router.Handle("repository validate", handlers.ValidateRepository)
	router.Handle("content list", handlers.GetContentList)
	router.Handle("content get", handlers.GetFileContent)
	router.Handle("content create", handlers.CreateContent)
	router.Handle("content update", handlers.UpdateContent)
	router.Handle("content remove", handlers.RemoveContent)
	router.Handle("user get", handlers.GetUser)
	router.Handle("authenticate", handlers.Authenticate)
	http.Handle("/", router)
	log.Info("Go app initialized in port 4000.")
	http.ListenAndServe(":4000", nil)
}
<commit_msg>Remove logrus dependency<commit_after>package main

import (
	"fmt"
	"github.com/joaodias/hugito-app/handlers"
	"net/http"
)

func main() {
	router := handlers.NewRouter()
	router.Handle("repositories get", handlers.GetRepository)
	router.Handle("repository validate", handlers.ValidateRepository)
	router.Handle("content list", handlers.GetContentList)
	router.Handle("content get", handlers.GetFileContent)
	router.Handle("content create", handlers.CreateContent)
	router.Handle("content update", handlers.UpdateContent)
	router.Handle("content remove", handlers.RemoveContent)
	router.Handle("user get", handlers.GetUser)
	router.Handle("authenticate", handlers.Authenticate)
	http.Handle("/", router)
	fmt.Print("Go app initialized in port 4000.")
	http.ListenAndServe(":4000", nil)
}
<|endoftext|>


<commit_before>// Copyright 2016 Jacob Taylor jacob@ablox.io
// License: Apache2 - http://www.apache.org/licenses/LICENSE-2.0
package main

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

func main() {
	fmt.Println("replicat initializing....")
	rand.Seed(int64(time.Now().Nanosecond()))

	SetupCli()

	bootstrapAndServe()
	fmt.Printf("replicat %s online....\n", globalSettings.Name)
	defer fmt.Println("End of line")

	// keep this process running until it is shut down
	for {
		time.Sleep(time.Millisecond * 500)
	}

}
<commit_msg>adding accuracy to the log time and file source<commit_after>// Copyright 2016 Jacob Taylor jacob@ablox.io
// License: Apache2 - http://www.apache.org/licenses/LICENSE-2.0
package main

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

func main() {
	// Set the flags on the logger to get better accuracy
	log.SetFlags(log.LstdFlags | log.Lmicroseconds | log.Lshortfile)

	fmt.Println("replicat initializing....")
	rand.Seed(int64(time.Now().Nanosecond()))

	SetupCli()

	bootstrapAndServe()
	fmt.Printf("replicat %s online....\n", globalSettings.Name)
	defer fmt.Println("End of line")

	// keep this process running until it is shut down
	for {
		time.Sleep(time.Millisecond * 500)
	}

}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"http"
	"io/ioutil"
	"log"
	"opts"
	"os"
	"path"
	"strings"
	"template"
)

var port = opts.Single("p", "port", "the port to use", "8080")
var blogroot = opts.Single("r",
	"blogroot",
	"the root directory for blog data",
	"/usr/share/obsidian")
var showVersion = opts.Flag("", "version", "show version information")
var verbose = opts.Flag("v", "verbose", "give verbose output")

var (
	templateDir string
)

func main() {
	// option setup
	opts.Description = "lightweight http blog server"
	// parse and handle options
	opts.Parse()

	templateDir = path.Join(*blogroot, "templates")

	readTemplates()
	readPosts()
	makeTags()
	makeCategories()
	compileAll()
	startServer()
}

func startServer() {
	log.Stdout("Starting server")
	// set up the extra servers
	http.HandleFunc("/", NotFoundServer)
	// start the server
	err := http.ListenAndServe(":"+*port, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.String())
		panic("Could not start server")
	}
	log.Stdout("Server started!")
}

// The various templates.
var templates = make(map[string]*template.Template)

func readTemplate(name string) *template.Template {
	log.Stdout("Reading template ", name)
	templatePath := path.Join(templateDir, name)
	templateText := readFile(templatePath)
	template, err := template.Parse(templateText, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.String())
		os.Exit(1)
	}
	return template
}

func readTemplates() {
	// read the templates
	log.Stdout("Reading templates")
	flist, err := ioutil.ReadDir(templateDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.String())
		panic("Couldn't read template directory!")
	}
	for _, finfo := range flist {
		fname := strings.Replace(finfo.Name, ".html", "", -1)
		templates[fname] = readTemplate(fname + ".html")
	}
}

type Post struct {
	title    string
	category string
	tags     []string
	content  string
	url      string
}

type Tag struct {
	name  string
	posts []Post
}

type Category struct {
	name  string
	posts []Post
}

var posts = map[string]*Post{}

type PostVisitor struct {
	root string
}

func (v PostVisitor) VisitDir(path string, f *os.FileInfo) bool {
	return true
}

func readPost(content string, path string) *Post {
	groups := strings.Split(content, "\n\n", 2)
	metalines := strings.Split(groups[0], "\n", -1)
	post := &Post{}
	post.content = groups[1]
	post.title = metalines[0]
	post.url = path
	return post
}

func (v PostVisitor) VisitFile(path string, f *os.FileInfo) {
	relPath := strings.Replace(path, v.root, "", 1)
	log.Stdout("Reading post ", relPath)
	// read in the posts
	posts[relPath] = readPost(readFile(path), relPath)
}

func readPosts() {
	log.Stdout("Reading posts")
	postDir := path.Join(*blogroot, "posts")
	walkDir(postDir, PostVisitor{postDir})
}

func makeTags() {
	log.Stdout("Analyzing tags")
}

func makeCategories() {
	log.Stdout("Analyzing categories")
}

func compileAll() {

}

func NotFoundServer(c *http.Conn, req *http.Request) {
	log.Stderr("404 when serving", req.URL.String())
	c.WriteHeader(404)
	fmt.Fprintf(c, "404 not found\n")
}
<commit_msg>empty tags and categories maps<commit_after>package main

import (
	"fmt"
	"http"
	"io/ioutil"
	"log"
	"opts"
	"os"
	"path"
	"strings"
	"template"
)

var port = opts.Single("p", "port", "the port to use", "8080")
var blogroot = opts.Single("r",
	"blogroot",
	"the root directory for blog data",
	"/usr/share/obsidian")
var showVersion = opts.Flag("", "version", "show version information")
var verbose = opts.Flag("v", "verbose", "give verbose output")

var (
	templateDir string
)

func main() {
	// option setup
	opts.Description = "lightweight http blog server"
	// parse and handle options
	opts.Parse()

	templateDir = path.Join(*blogroot, "templates")

	readTemplates()
	readPosts()
	makeTags()
	makeCategories()
	compileAll()
	startServer()
}

func startServer() {
	log.Stdout("Starting server")
	// set up the extra servers
	http.HandleFunc("/", NotFoundServer)
	// start the server
	err := http.ListenAndServe(":"+*port, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.String())
		panic("Could not start server")
	}
	log.Stdout("Server started!")
}

// The various templates.
var templates = make(map[string]*template.Template)

func readTemplate(name string) *template.Template {
	log.Stdout("Reading template ", name)
	templatePath := path.Join(templateDir, name)
	templateText := readFile(templatePath)
	template, err := template.Parse(templateText, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.String())
		os.Exit(1)
	}
	return template
}

func readTemplates() {
	// read the templates
	log.Stdout("Reading templates")
	flist, err := ioutil.ReadDir(templateDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.String())
		panic("Couldn't read template directory!")
	}
	for _, finfo := range flist {
		fname := strings.Replace(finfo.Name, ".html", "", -1)
		templates[fname] = readTemplate(fname + ".html")
	}
}

type Post struct {
	title    string
	category string
	tags     []string
	content  string
	url      string
}

type Tag struct {
	name  string
	posts []Post
}

type Category struct {
	name  string
	posts []Post
}

var posts = map[string]*Post{}
var tags = map[string]*Tag{}
var categories = map[string]*Category{}

type PostVisitor struct {
	root string
}

func (v PostVisitor) VisitDir(path string, f *os.FileInfo) bool {
	return true
}

func readPost(content string, path string) *Post {
	groups := strings.Split(content, "\n\n", 2)
	metalines := strings.Split(groups[0], "\n", -1)
	post := &Post{}
	post.content = groups[1]
	post.title = metalines[0]
	for _, line := range metalines[1:] {
		fmt.Printf(line)
	}
	post.url = path
	return post
}

func (v PostVisitor) VisitFile(path string, f *os.FileInfo) {
	relPath := strings.Replace(path, v.root, "", 1)
	log.Stdout("Reading post ", relPath)
	// read in the posts
	posts[relPath] = readPost(readFile(path), relPath)
}

func readPosts() {
	log.Stdout("Reading posts")
	postDir := path.Join(*blogroot, "posts")
	walkDir(postDir, PostVisitor{postDir})
}

func makeTags() {
	log.Stdout("Analyzing tags")
}

func makeCategories() {
	log.Stdout("Analyzing categories")
}

func compileAll() {

}

func NotFoundServer(c *http.Conn, req *http.Request) {
	log.Stderr("404 when serving", req.URL.String())
	c.WriteHeader(404)
	fmt.Fprintf(c, "404 not found\n")
}
<|endoftext|>


<commit_before>// +build go1.12

package main

import (
	"errors"
	"fmt"
	"os"
	"reflect"
	"strings"

	"code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/command"
	"code.cloudfoundry.org/cli/command/common"
	"code.cloudfoundry.org/cli/command/flag"
	"code.cloudfoundry.org/cli/command/translatableerror"
	plugin_transition "code.cloudfoundry.org/cli/plugin/transition"
	"code.cloudfoundry.org/cli/util/configv3"
	"code.cloudfoundry.org/cli/util/panichandler"
	"code.cloudfoundry.org/cli/util/ui"
	"github.com/jessevdk/go-flags"
	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/ssh"
)

type UI interface {
	DisplayError(err error)
	DisplayWarning(template string, templateValues ...map[string]interface{})
	DisplayText(template string, templateValues ...map[string]interface{})
	FlushDeferred()
}

type DisplayUsage interface {
	DisplayUsage()
}

type TriggerLegacyMain interface {
	LegacyMain()
	error
}

const switchToV2 = -3

var ErrFailed = errors.New("command failed")
var ParseErr = errors.New("incorrect type for arg")

func main() {
	defer panichandler.HandlePanic()
	exitStatus := parse(os.Args[1:], &common.Commands)
	if exitStatus == switchToV2 {
		exitStatus = parse(os.Args[1:], &common.FallbackCommands)
	}
	if exitStatus != 0 {
		os.Exit(exitStatus)
	}
}

func parse(args []string, commandList interface{}) int {
	parser := flags.NewParser(commandList, flags.HelpFlag)
	parser.CommandHandler = executionWrapper
	extraArgs, err := parser.ParseArgs(args)
	if err == nil {
		return 0
	} else if _, ok := err.(translatableerror.V3V2SwitchError); ok {
		return switchToV2
	} else if flagErr, ok := err.(*flags.Error); ok {
		return handleFlagErrorAndCommandHelp(flagErr, parser, extraArgs, args, commandList)
	} else if err == ErrFailed {
		return 1
	} else if err == ParseErr {
		fmt.Println()
		parse([]string{"help", args[0]}, commandList)
		return 1
	} else if exitError, ok := err.(*ssh.ExitError); ok {
		return exitError.ExitStatus()
	}

	fmt.Fprintf(os.Stderr, "Unexpected error: %s\n", err.Error())
	return 1
}

func handleFlagErrorAndCommandHelp(flagErr *flags.Error, parser *flags.Parser, extraArgs []string, originalArgs []string, commandList interface{}) int {
	switch flagErr.Type {
	case flags.ErrHelp, flags.ErrUnknownFlag, flags.ErrExpectedArgument, flags.ErrInvalidChoice:
		_, found := reflect.TypeOf(common.Commands).FieldByNameFunc(
			func(fieldName string) bool {
				field, _ := reflect.TypeOf(common.Commands).FieldByName(fieldName)
				return parser.Active != nil && parser.Active.Name == field.Tag.Get("command")
			},
		)

		if found && flagErr.Type == flags.ErrUnknownFlag && (parser.Active.Name == "set-env" || parser.Active.Name == "v3-set-env") {
			newArgs := []string{}
			for _, arg := range originalArgs {
				if arg[0] == '-' {
					newArgs = append(newArgs, fmt.Sprintf("%s%s", flag.WorkAroundPrefix, arg))
				} else {
					newArgs = append(newArgs, arg)
				}
			}
			parse(newArgs, commandList)
			return 0
		}

		if flagErr.Type == flags.ErrUnknownFlag || flagErr.Type == flags.ErrExpectedArgument || flagErr.Type == flags.ErrInvalidChoice {
			fmt.Fprintf(os.Stderr, "Incorrect Usage: %s\n\n", flagErr.Error())
		}

		var helpErrored int
		if found {
			helpErrored = parse([]string{"help", parser.Active.Name}, commandList)
		} else {
			switch len(extraArgs) {
			case 0:
				helpErrored = parse([]string{"help"}, commandList)
			case 1:
				if !isOption(extraArgs[0]) || (len(originalArgs) > 1 && extraArgs[0] == "-a") {
					helpErrored = parse([]string{"help", extraArgs[0]}, commandList)
				} else {
					helpErrored = parse([]string{"help"}, commandList)
				}
			default:
				if isCommand(extraArgs[0]) {
					helpErrored = parse([]string{"help", extraArgs[0]}, commandList)
				} else {
					helpErrored = parse(extraArgs[1:], commandList)
				}
			}
		}

		if helpErrored > 0 || flagErr.Type == flags.ErrUnknownFlag || flagErr.Type == flags.ErrExpectedArgument || flagErr.Type == flags.ErrInvalidChoice {
			return 1
		}
	case flags.ErrRequired, flags.ErrMarshal:
		fmt.Fprintf(os.Stderr, "Incorrect Usage: %s\n\n", flagErr.Error())
		parse([]string{"help", originalArgs[0]}, commandList)
		return 1
	case flags.ErrUnknownCommand:
		if !isHelpCommand(originalArgs) {
			if isPluginCommand(originalArgs[0]) {
				plugin_transition.RunPlugin()
			} else {
				// TODO Extract handling of unknown commands/suggested  commands out of legacy
				cmd.Main(os.Getenv("CF_TRACE"), os.Args)

			}
		} else {
			helpExitCode := parse([]string{"help", originalArgs[0]}, commandList)
			return helpExitCode
		}
	case flags.ErrCommandRequired:
		if common.Commands.VerboseOrVersion {
			parse([]string{"version"}, commandList)
		} else {
			parse([]string{"help"}, commandList)
		}
	default:
		fmt.Fprintf(os.Stderr, "Unexpected flag error\ntype: %s\nmessage: %s\n", flagErr.Type, flagErr.Error())
	}
	return 0
}

func isPluginCommand(command string) bool {

	config, _ := configv3.LoadConfig()
	for _, metadata := range config.Plugins() {
		for _, pluginCommand := range metadata.Commands {
			if command == pluginCommand.Name || command == pluginCommand.Alias {
				return true
			}
		}
	}
	return false
}

func isHelpCommand(args []string) bool {
	for _, arg := range args {
		if arg == "-h" || arg == "--help" || arg == "--h" {
			return true
		}
	}
	return false
}

func isCommand(s string) bool {
	_, found := reflect.TypeOf(common.Commands).FieldByNameFunc(
		func(fieldName string) bool {
			field, _ := reflect.TypeOf(common.Commands).FieldByName(fieldName)
			return s == field.Tag.Get("command") || s == field.Tag.Get("alias")
		})

	return found
}

func isOption(s string) bool {
	return strings.HasPrefix(s, "-")
}

func executionWrapper(cmd flags.Commander, args []string) error {
	cfConfig, configErr := configv3.LoadConfig(configv3.FlagOverride{
		Verbose: common.Commands.VerboseOrVersion,
	})
	if configErr != nil {
		if _, ok := configErr.(translatableerror.EmptyConfigError); !ok {
			return configErr
		}
	}

	commandUI, err := ui.NewUI(cfConfig)
	if err != nil {
		return err
	}
	defer commandUI.FlushDeferred()

	err = preventExtraArgs(args)
	if err != nil {
		return handleError(err, commandUI)
	}

	err = cfConfig.CreatePluginHome()
	if err != nil {
		return handleError(err, commandUI)
	}

	defer func() {
		configWriteErr := cfConfig.WriteConfig()
		if configWriteErr != nil {
			fmt.Fprintf(os.Stderr, "Error writing config: %s", configWriteErr.Error())
		}
	}()

	if extendedCmd, ok := cmd.(command.ExtendedCommander); ok {
		log.SetOutput(os.Stderr)
		log.SetLevel(log.Level(cfConfig.LogLevel()))

		err = extendedCmd.Setup(cfConfig, commandUI)
		if err != nil {
			return handleError(err, commandUI)
		}

		return handleError(extendedCmd.Execute(args), commandUI)
	}

	return fmt.Errorf("command does not conform to ExtendedCommander")
}

func handleError(passedErr error, commandUI UI) error {
	if passedErr == nil {
		return nil
	}

	translatedErr := translatableerror.ConvertToTranslatableError(passedErr)

	switch typedErr := translatedErr.(type) {
	case translatableerror.V3V2SwitchError:
		log.Info("Received a V3V2SwitchError - switch to the V2 version of the command")
		return passedErr
	case TriggerLegacyMain:
		if typedErr.Error() != "" {
			commandUI.DisplayWarning("")
			commandUI.DisplayWarning(typedErr.Error())
		}
		cmd.Main(os.Getenv("CF_TRACE"), os.Args)
	case *ssh.ExitError:
		exitStatus := typedErr.ExitStatus()
		if sig := typedErr.Signal(); sig != "" {
			commandUI.DisplayText("Process terminated by signal: {{.Signal}}. Exited with {{.ExitCode}}", map[string]interface{}{
				"Signal":   sig,
				"ExitCode": exitStatus,
			})
		}
		return passedErr
	}

	commandUI.DisplayError(translatedErr)

	if _, ok := translatedErr.(DisplayUsage); ok {
		return ParseErr
	}

	return ErrFailed
}
<commit_msg>Fix lint error regarding error handling.<commit_after>// +build go1.12

package main

import (
	"errors"
	"fmt"
	"os"
	"reflect"
	"strings"

	"code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/command"
	"code.cloudfoundry.org/cli/command/common"
	"code.cloudfoundry.org/cli/command/flag"
	"code.cloudfoundry.org/cli/command/translatableerror"
	plugin_transition "code.cloudfoundry.org/cli/plugin/transition"
	"code.cloudfoundry.org/cli/util/configv3"
	"code.cloudfoundry.org/cli/util/panichandler"
	"code.cloudfoundry.org/cli/util/ui"
	"github.com/jessevdk/go-flags"
	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/ssh"
)

type UI interface {
	DisplayError(err error)
	DisplayWarning(template string, templateValues ...map[string]interface{})
	DisplayText(template string, templateValues ...map[string]interface{})
	FlushDeferred()
}

type DisplayUsage interface {
	DisplayUsage()
}

type TriggerLegacyMain interface {
	LegacyMain()
	error
}

const switchToV2 = -3

var ErrFailed = errors.New("command failed")
var ParseErr = errors.New("incorrect type for arg")

func main() {
	defer panichandler.HandlePanic()
	exitStatus := parse(os.Args[1:], &common.Commands)
	if exitStatus == switchToV2 {
		exitStatus = parse(os.Args[1:], &common.FallbackCommands)
	}
	if exitStatus != 0 {
		os.Exit(exitStatus)
	}
}

func parse(args []string, commandList interface{}) int {
	parser := flags.NewParser(commandList, flags.HelpFlag)
	parser.CommandHandler = executionWrapper
	extraArgs, err := parser.ParseArgs(args)
	if err == nil {
		return 0
	} else if _, ok := err.(translatableerror.V3V2SwitchError); ok {
		return switchToV2
	} else if flagErr, ok := err.(*flags.Error); ok {
		return handleFlagErrorAndCommandHelp(flagErr, parser, extraArgs, args, commandList)
	} else if err == ErrFailed {
		return 1
	} else if err == ParseErr {
		fmt.Println()
		parse([]string{"help", args[0]}, commandList)
		return 1
	} else if exitError, ok := err.(*ssh.ExitError); ok {
		return exitError.ExitStatus()
	}

	fmt.Fprintf(os.Stderr, "Unexpected error: %s\n", err.Error())
	return 1
}

func handleFlagErrorAndCommandHelp(flagErr *flags.Error, parser *flags.Parser, extraArgs []string, originalArgs []string, commandList interface{}) int {
	switch flagErr.Type {
	case flags.ErrHelp, flags.ErrUnknownFlag, flags.ErrExpectedArgument, flags.ErrInvalidChoice:
		_, found := reflect.TypeOf(common.Commands).FieldByNameFunc(
			func(fieldName string) bool {
				field, _ := reflect.TypeOf(common.Commands).FieldByName(fieldName)
				return parser.Active != nil && parser.Active.Name == field.Tag.Get("command")
			},
		)

		if found && flagErr.Type == flags.ErrUnknownFlag && (parser.Active.Name == "set-env" || parser.Active.Name == "v3-set-env") {
			newArgs := []string{}
			for _, arg := range originalArgs {
				if arg[0] == '-' {
					newArgs = append(newArgs, fmt.Sprintf("%s%s", flag.WorkAroundPrefix, arg))
				} else {
					newArgs = append(newArgs, arg)
				}
			}
			parse(newArgs, commandList)
			return 0
		}

		if flagErr.Type == flags.ErrUnknownFlag || flagErr.Type == flags.ErrExpectedArgument || flagErr.Type == flags.ErrInvalidChoice {
			fmt.Fprintf(os.Stderr, "Incorrect Usage: %s\n\n", flagErr.Error())
		}

		var helpErrored int
		if found {
			helpErrored = parse([]string{"help", parser.Active.Name}, commandList)
		} else {
			switch len(extraArgs) {
			case 0:
				helpErrored = parse([]string{"help"}, commandList)
			case 1:
				if !isOption(extraArgs[0]) || (len(originalArgs) > 1 && extraArgs[0] == "-a") {
					helpErrored = parse([]string{"help", extraArgs[0]}, commandList)
				} else {
					helpErrored = parse([]string{"help"}, commandList)
				}
			default:
				if isCommand(extraArgs[0]) {
					helpErrored = parse([]string{"help", extraArgs[0]}, commandList)
				} else {
					helpErrored = parse(extraArgs[1:], commandList)
				}
			}
		}

		if helpErrored > 0 || flagErr.Type == flags.ErrUnknownFlag || flagErr.Type == flags.ErrExpectedArgument || flagErr.Type == flags.ErrInvalidChoice {
			return 1
		}
	case flags.ErrRequired, flags.ErrMarshal:
		fmt.Fprintf(os.Stderr, "Incorrect Usage: %s\n\n", flagErr.Error())
		parse([]string{"help", originalArgs[0]}, commandList)
		return 1
	case flags.ErrUnknownCommand:
		if !isHelpCommand(originalArgs) {
			config, configErr := configv3.LoadConfig()
			if configErr != nil {
				if _, ok := configErr.(translatableerror.EmptyConfigError); !ok {

					fmt.Fprintf(os.Stderr, "Empty Config, failed to load plugins")
					return 1
				}
			}

			if isPluginCommand(originalArgs[0], config.Plugins()) {
				plugin_transition.RunPlugin()
			} else {
				// TODO Extract handling of unknown commands/suggested  commands out of legacy
				cmd.Main(os.Getenv("CF_TRACE"), os.Args)

			}
		} else {
			helpExitCode := parse([]string{"help", originalArgs[0]}, commandList)
			return helpExitCode
		}
	case flags.ErrCommandRequired:
		if common.Commands.VerboseOrVersion {
			parse([]string{"version"}, commandList)
		} else {
			parse([]string{"help"}, commandList)
		}
	default:
		fmt.Fprintf(os.Stderr, "Unexpected flag error\ntype: %s\nmessage: %s\n", flagErr.Type, flagErr.Error())
	}
	return 0
}

func isPluginCommand(command string, plugins []configv3.Plugin) bool {

	for _, metadata := range plugins {
		for _, pluginCommand := range metadata.Commands {
			if command == pluginCommand.Name || command == pluginCommand.Alias {
				return true
			}
		}
	}
	return false
}

func isHelpCommand(args []string) bool {
	for _, arg := range args {
		if arg == "-h" || arg == "--help" || arg == "--h" {
			return true
		}
	}
	return false
}

func isCommand(s string) bool {
	_, found := reflect.TypeOf(common.Commands).FieldByNameFunc(
		func(fieldName string) bool {
			field, _ := reflect.TypeOf(common.Commands).FieldByName(fieldName)
			return s == field.Tag.Get("command") || s == field.Tag.Get("alias")
		})

	return found
}

func isOption(s string) bool {
	return strings.HasPrefix(s, "-")
}

func executionWrapper(cmd flags.Commander, args []string) error {
	cfConfig, configErr := configv3.LoadConfig(configv3.FlagOverride{
		Verbose: common.Commands.VerboseOrVersion,
	})
	if configErr != nil {
		if _, ok := configErr.(translatableerror.EmptyConfigError); !ok {
			return configErr
		}
	}

	commandUI, err := ui.NewUI(cfConfig)
	if err != nil {
		return err
	}
	defer commandUI.FlushDeferred()

	err = preventExtraArgs(args)
	if err != nil {
		return handleError(err, commandUI)
	}

	err = cfConfig.CreatePluginHome()
	if err != nil {
		return handleError(err, commandUI)
	}

	defer func() {
		configWriteErr := cfConfig.WriteConfig()
		if configWriteErr != nil {
			fmt.Fprintf(os.Stderr, "Error writing config: %s", configWriteErr.Error())
		}
	}()

	if extendedCmd, ok := cmd.(command.ExtendedCommander); ok {
		log.SetOutput(os.Stderr)
		log.SetLevel(log.Level(cfConfig.LogLevel()))

		err = extendedCmd.Setup(cfConfig, commandUI)
		if err != nil {
			return handleError(err, commandUI)
		}

		return handleError(extendedCmd.Execute(args), commandUI)
	}

	return fmt.Errorf("command does not conform to ExtendedCommander")
}

func handleError(passedErr error, commandUI UI) error {
	if passedErr == nil {
		return nil
	}

	translatedErr := translatableerror.ConvertToTranslatableError(passedErr)

	switch typedErr := translatedErr.(type) {
	case translatableerror.V3V2SwitchError:
		log.Info("Received a V3V2SwitchError - switch to the V2 version of the command")
		return passedErr
	case TriggerLegacyMain:
		if typedErr.Error() != "" {
			commandUI.DisplayWarning("")
			commandUI.DisplayWarning(typedErr.Error())
		}
		cmd.Main(os.Getenv("CF_TRACE"), os.Args)
	case *ssh.ExitError:
		exitStatus := typedErr.ExitStatus()
		if sig := typedErr.Signal(); sig != "" {
			commandUI.DisplayText("Process terminated by signal: {{.Signal}}. Exited with {{.ExitCode}}", map[string]interface{}{
				"Signal":   sig,
				"ExitCode": exitStatus,
			})
		}
		return passedErr
	}

	commandUI.DisplayError(translatedErr)

	if _, ok := translatedErr.(DisplayUsage); ok {
		return ParseErr
	}

	return ErrFailed
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"flag"
	"fmt"

	"github.com/Tinker-Ware/digital-ocean-service/infrastructure"
	"github.com/Tinker-Ware/digital-ocean-service/interfaces"
	"github.com/Tinker-Ware/digital-ocean-service/usecases"
	"github.com/codegangsta/negroni"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

const defaultPath = "/etc/digital-ocean-service.conf"

var confFilePath = flag.String("conf", defaultPath, "Custom path for configuration file")

func main() {

	flag.Parse()

	config, err := infrastructure.GetConfiguration(*confFilePath)
	if err != nil {
		fmt.Println(err.Error())
		panic("Cannot parse configuration")
	}

	doInteractor := usecases.DOInteractor{}

	handler := interfaces.WebServiceHandler{
		Interactor:  doInteractor,
		ID:          config.ClientID,
		Secret:      config.ClientSecret,
		Scopes:      config.Scopes,
		RedirectURI: config.RedirectURI,
		APIHost:     config.APIHost,
	}

	headers := handlers.AllowedHeaders([]string{"Accept", "Content-Type", "Authorization"})
	origins := handlers.AllowedOrigins([]string{"http://localhost", "http://provision.tinkerware.io", "https://provision.tinkerware.io"})

	r := mux.NewRouter()

	subrouter := r.PathPrefix("/api/v1/cloud").Subrouter()

	subrouter.HandleFunc("/digital_ocean/", handler.Login)
	subrouter.HandleFunc("/digital_ocean/oauth", handler.DOCallback).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/keys", handler.ShowKeys).Methods("GET")
	subrouter.HandleFunc("/digital_ocean/keys", handler.CreateKey).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/instances", handler.CreateDroplet).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/instances", handler.ListDroplets).Methods("GET")
	subrouter.HandleFunc("/digital_ocean/instance/{instanceID}", handler.GetInstance).Methods("GET")

	n := negroni.Classic()
	n.UseHandler(handlers.CORS(headers, origins)(r))

	port := bytes.Buffer{}

	port.WriteString(":")
	port.WriteString(config.Port)

	n.Run(port.String())

}
<commit_msg>Add the route which will use the adapter<commit_after>package main

import (
	"bytes"
	"flag"
	"fmt"
	"net/http"

	"github.com/Tinker-Ware/digital-ocean-service/infrastructure"
	"github.com/Tinker-Ware/digital-ocean-service/interfaces"
	"github.com/Tinker-Ware/digital-ocean-service/usecases"
	"github.com/codegangsta/negroni"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

const defaultPath = "/etc/digital-ocean-service.conf"

var confFilePath = flag.String("conf", defaultPath, "Custom path for configuration file")

func main() {

	flag.Parse()

	config, err := infrastructure.GetConfiguration(*confFilePath)
	if err != nil {
		fmt.Println(err.Error())
		panic("Cannot parse configuration")
	}

	doInteractor := usecases.DOInteractor{}

	handler := interfaces.WebServiceHandler{
		Interactor:  doInteractor,
		ID:          config.ClientID,
		Secret:      config.ClientSecret,
		Scopes:      config.Scopes,
		RedirectURI: config.RedirectURI,
		APIHost:     config.APIHost,
	}

	headers := handlers.AllowedHeaders([]string{"Accept", "Content-Type", "Authorization"})
	origins := handlers.AllowedOrigins([]string{"http://localhost", "http://provision.tinkerware.io", "https://provision.tinkerware.io"})

	r := mux.NewRouter()

	subrouter := r.PathPrefix("/api/v1/cloud").Subrouter()

	subrouter.HandleFunc("/digital_ocean/", handler.Login)
	subrouter.HandleFunc("/digital_ocean/oauth", handler.DOCallback).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/keys", handler.ShowKeys).Methods("GET")
	subrouter.HandleFunc("/digital_ocean/keys", handler.CreateKey).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/instances", handler.CreateDroplet).Methods("POST")
	subrouter.HandleFunc("/digital_ocean/instances", handler.ListDroplets).Methods("GET")
	subrouter.HandleFunc("/digital_ocean/instance/{instanceID}", handler.GetInstance).Methods("GET")
	subrouter.Handle("/digital_ocean/keys", interfaces.Adapt(http.HandlerFunc(handler.CreateKey), interfaces.GetToken(config.APIHost, config.Salt))).Methods("POST")

	n := negroni.Classic()
	n.UseHandler(handlers.CORS(headers, origins)(r))

	port := bytes.Buffer{}

	port.WriteString(":")
	port.WriteString(config.Port)

	n.Run(port.String())

}
<|endoftext|>


<commit_before>package main

import (
	"crypto/sha256"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/lxc/lxd"
	"gopkg.in/fsnotify.v0"
	"gopkg.in/yaml.v2"
)

// Global variables
var lxdDaemon *lxd.Client
var config serverConfig

type serverConfig struct {
	Container string   `yaml:"container"`
	Image     string   `yaml:"image"`
	Profiles  []string `yaml:"profiles"`

	Feedback        bool `yaml:"feedback"`
	FeedbackTimeout int  `yaml:"feedback_timeout"`

	QuotaCPU       int `yaml:"quota_cpu"`
	QuotaDisk      int `yaml:"quota_disk"`
	QuotaProcesses int `yaml:"quota_processes"`
	QuotaRAM       int `yaml:"quota_ram"`
	QuotaSessions  int `yaml:"quota_sessions"`
	QuotaTime      int `yaml:"quota_time"`

	ServerAddr           string   `yaml:"server_addr"`
	ServerBannedIPs      []string `yaml:"server_banned_ips"`
	ServerConsoleOnly    bool     `yaml:"server_console_only"`
	ServerContainersMax  int      `yaml:"server_containers_max"`
	ServerIPv6Only       bool     `yaml:"server_ipv6_only"`
	ServerMaintenance    bool     `yaml:"server_maintenance"`
	ServerStatisticsKeys []string `yaml:"server_statistics_keys"`
	ServerTerms          string   `yaml:"server_terms"`

	serverTermsHash string
}

type statusCode int

const (
	serverOperational statusCode = 0
	serverMaintenance statusCode = 1

	containerStarted      statusCode = 0
	containerInvalidTerms statusCode = 1
	containerServerFull   statusCode = 2
	containerQuotaReached statusCode = 3
	containerUserBanned   statusCode = 4
	containerUnknownError statusCode = 5
)

func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	err := run()
	if err != nil {
		fmt.Printf("error: %s\n", err)
		os.Exit(1)
	}
}

func parseConfig() error {
	data, err := ioutil.ReadFile("lxd-demo.yaml")
	if os.IsNotExist(err) {
		return fmt.Errorf("The configuration file (lxd-demo.yaml) doesn't exist.")
	} else if err != nil {
		return fmt.Errorf("Unable to read the configuration: %s", err)
	}

	err = yaml.Unmarshal(data, &config)
	if err != nil {
		return fmt.Errorf("Unable to parse the configuration: %s", err)
	}

	if config.ServerAddr == "" {
		config.ServerAddr = ":8080"
	}

	config.ServerTerms = strings.TrimRight(config.ServerTerms, "\n")
	hash := sha256.New()
	io.WriteString(hash, config.ServerTerms)
	config.serverTermsHash = fmt.Sprintf("%x", hash.Sum(nil))

	if config.Container == "" && config.Image == "" {
		return fmt.Errorf("No container or image specified in configuration")
	}

	return nil
}

func run() error {
	var err error

	// Setup configuration
	err = parseConfig()
	if err != nil {
		return err
	}

	// Watch for configuration changes
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return fmt.Errorf("Unable to setup fsnotify: %s", err)
	}

	err = watcher.Watch(".")
	if err != nil {
		return fmt.Errorf("Unable to setup fsnotify watch: %s", err)
	}

	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				if ev.Name != "./lxd-demo.yaml" {
					continue
				}

				if !ev.IsModify() {
					continue
				}

				fmt.Printf("Reloading configuration\n")
				err := parseConfig()
				if err != nil {
					fmt.Printf("Failed to parse configuration: %s\n", err)
				}
			case err := <-watcher.Error:
				fmt.Printf("Inotify error: %s\n", err)
			}
		}
	}()

	// Connect to the LXD daemon
	lxdDaemon, err = lxd.NewClient(&lxd.DefaultConfig, "local")
	if err != nil {
		return fmt.Errorf("Unable to connect to LXD: %s", err)
	}

	// Setup the database
	err = dbSetup()
	if err != nil {
		return fmt.Errorf("Failed to setup the database: %s", err)
	}

	// Restore cleanup handler for existing containers
	containers, err := dbActive()
	if err != nil {
		return fmt.Errorf("Unable to read current containers: %s", err)
	}

	for _, entry := range containers {
		containerID := int64(entry[0].(int))
		containerName := entry[1].(string)
		containerExpiry := int64(entry[2].(int))

		duration := containerExpiry - time.Now().Unix()
		timeDuration, err := time.ParseDuration(fmt.Sprintf("%ds", duration))
		if err != nil || duration <= 0 {
			lxdForceDelete(lxdDaemon, containerName)
			dbExpire(containerID)
			continue
		}

		time.AfterFunc(timeDuration, func() {
			lxdForceDelete(lxdDaemon, containerName)
			dbExpire(containerID)
		})
	}

	// Setup the HTTP server
	r := mux.NewRouter()
	r.Handle("/", http.RedirectHandler("/static", http.StatusMovedPermanently))
	r.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir("static/"))))
	r.HandleFunc("/1.0", restStatusHandler)
	r.HandleFunc("/1.0/console", restConsoleHandler)
	r.HandleFunc("/1.0/feedback", restFeedbackHandler)
	r.HandleFunc("/1.0/info", restInfoHandler)
	r.HandleFunc("/1.0/start", restStartHandler)
	r.HandleFunc("/1.0/statistics", restStatisticsHandler)
	r.HandleFunc("/1.0/terms", restTermsHandler)

	err = http.ListenAndServe(config.ServerAddr, r)
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>Deal with the daemon not being online yet<commit_after>package main

import (
	"crypto/sha256"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/lxc/lxd"
	"gopkg.in/fsnotify.v0"
	"gopkg.in/yaml.v2"
)

// Global variables
var lxdDaemon *lxd.Client
var config serverConfig

type serverConfig struct {
	Container string   `yaml:"container"`
	Image     string   `yaml:"image"`
	Profiles  []string `yaml:"profiles"`

	Feedback        bool `yaml:"feedback"`
	FeedbackTimeout int  `yaml:"feedback_timeout"`

	QuotaCPU       int `yaml:"quota_cpu"`
	QuotaDisk      int `yaml:"quota_disk"`
	QuotaProcesses int `yaml:"quota_processes"`
	QuotaRAM       int `yaml:"quota_ram"`
	QuotaSessions  int `yaml:"quota_sessions"`
	QuotaTime      int `yaml:"quota_time"`

	ServerAddr           string   `yaml:"server_addr"`
	ServerBannedIPs      []string `yaml:"server_banned_ips"`
	ServerConsoleOnly    bool     `yaml:"server_console_only"`
	ServerContainersMax  int      `yaml:"server_containers_max"`
	ServerIPv6Only       bool     `yaml:"server_ipv6_only"`
	ServerMaintenance    bool     `yaml:"server_maintenance"`
	ServerStatisticsKeys []string `yaml:"server_statistics_keys"`
	ServerTerms          string   `yaml:"server_terms"`

	serverTermsHash string
}

type statusCode int

const (
	serverOperational statusCode = 0
	serverMaintenance statusCode = 1

	containerStarted      statusCode = 0
	containerInvalidTerms statusCode = 1
	containerServerFull   statusCode = 2
	containerQuotaReached statusCode = 3
	containerUserBanned   statusCode = 4
	containerUnknownError statusCode = 5
)

func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	err := run()
	if err != nil {
		fmt.Printf("error: %s\n", err)
		os.Exit(1)
	}
}

func parseConfig() error {
	data, err := ioutil.ReadFile("lxd-demo.yaml")
	if os.IsNotExist(err) {
		return fmt.Errorf("The configuration file (lxd-demo.yaml) doesn't exist.")
	} else if err != nil {
		return fmt.Errorf("Unable to read the configuration: %s", err)
	}

	err = yaml.Unmarshal(data, &config)
	if err != nil {
		return fmt.Errorf("Unable to parse the configuration: %s", err)
	}

	if config.ServerAddr == "" {
		config.ServerAddr = ":8080"
	}

	config.ServerTerms = strings.TrimRight(config.ServerTerms, "\n")
	hash := sha256.New()
	io.WriteString(hash, config.ServerTerms)
	config.serverTermsHash = fmt.Sprintf("%x", hash.Sum(nil))

	if config.Container == "" && config.Image == "" {
		return fmt.Errorf("No container or image specified in configuration")
	}

	return nil
}

func run() error {
	var err error

	// Setup configuration
	err = parseConfig()
	if err != nil {
		return err
	}

	// Watch for configuration changes
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return fmt.Errorf("Unable to setup fsnotify: %s", err)
	}

	err = watcher.Watch(".")
	if err != nil {
		return fmt.Errorf("Unable to setup fsnotify watch: %s", err)
	}

	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				if ev.Name != "./lxd-demo.yaml" {
					continue
				}

				if !ev.IsModify() {
					continue
				}

				fmt.Printf("Reloading configuration\n")
				err := parseConfig()
				if err != nil {
					fmt.Printf("Failed to parse configuration: %s\n", err)
				}
			case err := <-watcher.Error:
				fmt.Printf("Inotify error: %s\n", err)
			}
		}
	}()

	// Connect to the LXD daemon
	warning := false
	for {
		lxdDaemon, err = lxd.NewClient(&lxd.DefaultConfig, "local")
		if err == nil {
			break
		}

		if !warning {
			fmt.Printf("Waiting for the LXD server to come online.\n")
			warning = true
		}
		time.Sleep(time.Second)
	}

	if warning {
		fmt.Printf("LXD is now available. Daemon starting.\n")
	}

	// Setup the database
	err = dbSetup()
	if err != nil {
		return fmt.Errorf("Failed to setup the database: %s", err)
	}

	// Restore cleanup handler for existing containers
	containers, err := dbActive()
	if err != nil {
		return fmt.Errorf("Unable to read current containers: %s", err)
	}

	for _, entry := range containers {
		containerID := int64(entry[0].(int))
		containerName := entry[1].(string)
		containerExpiry := int64(entry[2].(int))

		duration := containerExpiry - time.Now().Unix()
		timeDuration, err := time.ParseDuration(fmt.Sprintf("%ds", duration))
		if err != nil || duration <= 0 {
			lxdForceDelete(lxdDaemon, containerName)
			dbExpire(containerID)
			continue
		}

		time.AfterFunc(timeDuration, func() {
			lxdForceDelete(lxdDaemon, containerName)
			dbExpire(containerID)
		})
	}

	// Setup the HTTP server
	r := mux.NewRouter()
	r.Handle("/", http.RedirectHandler("/static", http.StatusMovedPermanently))
	r.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir("static/"))))
	r.HandleFunc("/1.0", restStatusHandler)
	r.HandleFunc("/1.0/console", restConsoleHandler)
	r.HandleFunc("/1.0/feedback", restFeedbackHandler)
	r.HandleFunc("/1.0/info", restInfoHandler)
	r.HandleFunc("/1.0/start", restStartHandler)
	r.HandleFunc("/1.0/statistics", restStatisticsHandler)
	r.HandleFunc("/1.0/terms", restTermsHandler)

	err = http.ListenAndServe(config.ServerAddr, r)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/user"
	"path"
	"strconv"
	"strings"
	"syscall"
)

var usage string = "setuidgid: usage: setuidgid username program [arg...]"

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

func main() {

	if len(os.Args) <= 2 {
		fmt.Print(usage)
		os.Exit(100)
	}

	username := os.Args[1]
	program := os.Args[2]
	pargv := os.Args[2:]

	user, err := user.Lookup(username)
	checkError(err)

	uid, err := strconv.Atoi(user.Uid)
	checkError(err)
	gid, err := strconv.Atoi(user.Gid)
	checkError(err)

	err = syscall.Setgid(gid)
	checkError(err)
	err = syscall.Setuid(uid)
	checkError(err)

	if path.IsAbs(program) {
		err := syscall.Exec(program, pargv, os.Environ())
		checkError(err)
	}

	for _, p := range strings.Split(os.Getenv("PATH"), ":") {
		absPath := path.Join(p, program)
		err = syscall.Exec(absPath, pargv, os.Environ())
	}

	checkError(err)
}
<commit_msg>Better error messages<commit_after>package main

import (
	"fmt"
	"os"
	"os/user"
	"path"
	"strconv"
	"strings"
	"syscall"
)

var usage string = "setuidgid: usage: setuidgid username program [arg...]"

func checkError(err error) {
	if err != nil {
		fmt.Printf("setuidgid: fatal: %v\n", err)
		os.Exit(111)
	}
}

func main() {

	if len(os.Args) <= 2 {
		fmt.Print(usage)
		os.Exit(100)
	}

	username := os.Args[1]
	program := os.Args[2]
	pargv := os.Args[2:]

	user, err := user.Lookup(username)
	checkError(err)

	uid, err := strconv.Atoi(user.Uid)
	checkError(err)
	gid, err := strconv.Atoi(user.Gid)
	checkError(err)

	err = syscall.Setgid(gid)
	checkError(err)
	err = syscall.Setuid(uid)
	checkError(err)

	if path.IsAbs(program) {
		err := syscall.Exec(program, pargv, os.Environ())
		checkError(err)
	}

	for _, p := range strings.Split(os.Getenv("PATH"), ":") {
		absPath := path.Join(p, program)
		err = syscall.Exec(absPath, pargv, os.Environ())
	}

	checkError(err)
}
<|endoftext|>


<commit_before>package qtypes

import (
	"time"
	"github.com/qnib/qframe-utils"
)

type QMsg struct {
	Type        string        `json:"type"`
	Source      string        `json:"source"`
	SourceID    uint64        `json:"source_id"`
	Host        string        `json:"host"`
	Msg         string        `json:"short_message"`
	Time        time.Time     `json:"time"`
	TimeNano    int64         `json:"time_nano"`
	Level       int           `json:"level"` //https://en.wikipedia.org/wiki/Syslog#Severity_level
	Data 	    interface{}
}

func NewQMsg(typ, source string) QMsg {
	now := time.Now()
	return QMsg{
		Type: typ,
		Level: 6,
		Source: source,
		SourceID: qutils.GetGID(),
		Time: now,
		TimeNano: now.UnixNano(),
	}
}

func (qm *QMsg) TimeString() (lout string) {
	return qm.Time.Format("2006-01-02T15:04:05.999999")

}

func (qm *QMsg) LogString() (lout string) {
	switch qm.Level {
	case 0:
		lout = "EMERG"
	case 1:
		lout = "ALERT"
	case 2:
		lout = "CRIT"
	case 3:
		lout = "ERROR"
	case 4:
		lout = "WARN"
	case 5:
		lout = "NOTICE"
	case 6:
		lout = "INFO"
	case 7:
		lout = "DEBUG"
	}
	return
}
<commit_msg>Add KV to QMsg<commit_after>package qtypes

import (
	"time"
	"github.com/qnib/qframe-utils"
)

type QMsg struct {
	Type        string        		`json:"type"`
	Source      string        		`json:"source"`
	SourceID    uint64        		`json:"source_id"`
	Host        string        		`json:"host"`
	Msg         string        		`json:"short_message"`
	Time        time.Time    	 	`json:"time"`
	TimeNano    int64        	 	`json:"time_nano"`
	Level       int          	 	`json:"level"` //https://en.wikipedia.org/wiki/Syslog#Severity_level
	KV          map[string]string	`json:"kv"`
	Data 	    interface{}			`json:"data"`
}

func NewQMsg(typ, source string) QMsg {
	now := time.Now()
	return QMsg{
		Type: typ,
		Level: 6,
		Source: source,
		SourceID: qutils.GetGID(),
		Time: now,
		TimeNano: now.UnixNano(),
	}
}

func (qm *QMsg) TimeString() (lout string) {
	return qm.Time.Format("2006-01-02T15:04:05.999999")

}

func (qm *QMsg) LogString() (lout string) {
	switch qm.Level {
	case 0:
		lout = "EMERG"
	case 1:
		lout = "ALERT"
	case 2:
		lout = "CRIT"
	case 3:
		lout = "ERROR"
	case 4:
		lout = "WARN"
	case 5:
		lout = "NOTICE"
	case 6:
		lout = "INFO"
	case 7:
		lout = "DEBUG"
	}
	return
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/ovaskevich/TxtRoulette/server"
	"log"
	"net/http"
	"os"
)

func main() {
	// Read the args.
	if len(os.Args) != 2 {
		log.Fatal("usage: server.go port")
	}
	port := ":" + os.Args[1]

	// Make sure environment variables are set.
	if len(os.Getenv("TWILIO_APIUSR")) >= 0 || len(os.Getenv("TWILIO_APIKEY")) >= 0 {
		log.Fatal("Please set your TWILIO_APIUSR and TWILIO_APIKEY environment variables.")
	}

	// Start the server.
	fmt.Printf("Starting TxtRoulette server on port %s...\n", port)
	http.HandleFunc("/receive/", server.Receive)
	log.Fatal(http.ListenAndServe(port, nil))
}
<commit_msg>Add check for empty environment variables and fix mutex<commit_after>package main

import (
	"fmt"
	"github.com/ovaskevich/TxtRoulette/server"
	"log"
	"net/http"
	"os"
)

func main() {
	// Read the args.
	if len(os.Args) != 2 {
		log.Fatal("usage: server.go port")
	}
	port := ":" + os.Args[1]

	// Make sure environment variables are set.
	if len(os.Getenv("TWILIO_APIUSR")) == 0 || len(os.Getenv("TWILIO_APIKEY")) == 0 {
		log.Fatal("Please set your TWILIO_APIUSR and TWILIO_APIKEY environment variables.")
	}

	// Start the server.
	fmt.Printf("Starting TxtRoulette server on port %s...\n", port)
	http.HandleFunc("/receive/", server.Receive)
	log.Fatal(http.ListenAndServe(port, nil))
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"log"

	"github.com/geckoboard/zendesk_dataset/conf"
	"github.com/geckoboard/zendesk_dataset/zendesk"
)

var configPath = flag.String("config", "./geckoboard_zendesk.conf", "Path to your geckoboard zendesk configuration")

func main() {
	flag.Parse()

	config, err := conf.LoadConfig(*configPath)

	if err != nil {
		log.Fatalf("ERRO: Problem with the config: %s\n", err)
	}

	if len(config.Zendesk.Reports) == 0 {
		log.Fatal("ERRO: You have no reports setup in your config under zendesk")
	}

	zendesk.HandleReports(config)
	log.Println("Completed processing all reports...")
}
<commit_msg>Call error interface method Error() to return string<commit_after>package main

import (
	"flag"
	"log"

	"github.com/geckoboard/zendesk_dataset/conf"
	"github.com/geckoboard/zendesk_dataset/zendesk"
)

var configPath = flag.String("config", "./geckoboard_zendesk.conf", "Path to your geckoboard zendesk configuration")

func main() {
	flag.Parse()

	config, err := conf.LoadConfig(*configPath)

	if err != nil {
		log.Fatalf("ERRO: Problem with the config: %s\n", err.Error())
	}

	if len(config.Zendesk.Reports) == 0 {
		log.Fatal("ERRO: You have no reports setup in your config under zendesk")
	}

	zendesk.HandleReports(config)
	log.Println("Completed processing all reports...")
}
<|endoftext|>


<commit_before>package main

import (
	"image"
	"os"
	"time"

	_ "image/jpeg"
	_ "image/png"

	"github.com/nsf/termbox-go"
)

func draw(img image.Image) {
	// Get terminal size and cursor width/height ratio
	width, height, whratio := canvasSize()

	bounds := img.Bounds()
	imgW, imgH := bounds.Dx(), bounds.Dy()

	imgScale := scale(imgW, imgH, width, height, whratio)

	// Resize canvas to fit scaled image
	width, height = int(float64(imgW)/imgScale), int(float64(imgH)/(imgScale*whratio))

	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			// Calculate average color for the corresponding image rectangle
			// fitting in this cell. We use a half-block trick, wherein the
			// lower half of the cell displays the character ▄, effectively
			// doubling the resolution of the canvas.
			startX, startY, endX, endY := imgArea(x, y, imgScale, whratio)

			r, g, b := avgRGB(img, startX, startY, endX, (startY+endY)/2)
			colorUp := termbox.Attribute(termColor(r, g, b))

			r, g, b = avgRGB(img, startX, (startY+endY)/2, endX, endY)
			colorDown := termbox.Attribute(termColor(r, g, b))

			termbox.SetCell(x, y, '▄', colorDown, colorUp)
		}
	}
	termbox.Flush()
}

func main() {
	img, err := load(os.Args[len(os.Args)-1])
	if err != nil {
		panic(err)
	}

	err = termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()
	termbox.SetOutputMode(termbox.Output256)

	draw(img)
loop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			if ev.Key == termbox.KeyEsc {
				break loop
			}
		case termbox.EventResize:
			draw(img)
		default:
			time.Sleep(10 * time.Millisecond)
		}
	}
}
<commit_msg>Argument validation<commit_after>package main

import (
	"fmt"
	"image"
	"os"
	"time"

	_ "image/jpeg"
	_ "image/png"

	"github.com/nsf/termbox-go"
)

func draw(img image.Image) {
	// Get terminal size and cursor width/height ratio
	width, height, whratio := canvasSize()

	bounds := img.Bounds()
	imgW, imgH := bounds.Dx(), bounds.Dy()

	imgScale := scale(imgW, imgH, width, height, whratio)

	// Resize canvas to fit scaled image
	width, height = int(float64(imgW)/imgScale), int(float64(imgH)/(imgScale*whratio))

	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			// Calculate average color for the corresponding image rectangle
			// fitting in this cell. We use a half-block trick, wherein the
			// lower half of the cell displays the character ▄, effectively
			// doubling the resolution of the canvas.
			startX, startY, endX, endY := imgArea(x, y, imgScale, whratio)

			r, g, b := avgRGB(img, startX, startY, endX, (startY+endY)/2)
			colorUp := termbox.Attribute(termColor(r, g, b))

			r, g, b = avgRGB(img, startX, (startY+endY)/2, endX, endY)
			colorDown := termbox.Attribute(termColor(r, g, b))

			termbox.SetCell(x, y, '▄', colorDown, colorUp)
		}
	}
	termbox.Flush()
}

func main() {
	if len(os.Args) != 2 {
		fmt.Printf("Usage: %s <filename>\n\n", os.Args[0])
		fmt.Println("Close the image with <ESC>.")
		os.Exit(1)
	}

	img, err := load(os.Args[len(os.Args)-1])
	if err != nil {
		panic(err)
	}

	err = termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()
	termbox.SetOutputMode(termbox.Output256)

	draw(img)
loop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:
			if ev.Key == termbox.KeyEsc {
				break loop
			}
		case termbox.EventResize:
			draw(img)
		default:
			time.Sleep(10 * time.Millisecond)
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"
	"os/exec"
	"strings"

	"gopkg.in/gin-gonic/gin.v1"
)

func main() {
	router := gin.Default()

	router.LoadHTMLGlob("resources/templates/*")
	router.Static("/static", "resources/static")

	router.GET("/", index)
	router.GET("/index", index)

	router.Run("localhost:8080")
}

func index(c *gin.Context) {
	tmux_path, _ := c.Get("bin")
	if tmux_path == nil {
		tmux_path, _ = exec.LookPath("tmux")
	}

	sessions_cmd := exec.Command("tmux", "list-sessions")
	out, _ := sessions_cmd.CombinedOutput()
	sessions := strings.TrimSpace(string(out))

	c.HTML(http.StatusOK, "index.html", gin.H{
		"title":     "tmux control panel",
		"tmux_path": tmux_path,
		"sessions":  sessions,
	})
}
<commit_msg>list of sessions<commit_after>package main

import (
	"net/http"
	"os/exec"
	"strings"

	"gopkg.in/gin-gonic/gin.v1"
)

func main() {
	router := gin.Default()

	router.LoadHTMLGlob("resources/templates/*")
	router.Static("/static", "resources/static")

	router.GET("/", index)
	router.GET("/index", index)

	router.Run("localhost:8080")
}

func index(c *gin.Context) {
	tmux_path, _ := c.Get("bin")
	if tmux_path == nil {
		tmux_path, _ = exec.LookPath("tmux")
	}

	sessions_cmd := exec.Command("tmux", "list-sessions")
	out, _ := sessions_cmd.CombinedOutput()
	sessions := strings.Split(strings.TrimSpace(string(out)), "\n")

	c.HTML(http.StatusOK, "index.html", gin.H{
		"title":     "tmux control panel",
		"tmux_path": tmux_path,
		"sessions":  sessions,
	})
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"net"
	"net/http"
	"os"
	"runtime"
	"strconv"
	"strings"

	"github.com/PuerkitoBio/throttled"
	"github.com/PuerkitoBio/throttled/store"
	"github.com/Sirupsen/logrus"
	"github.com/bmizerany/pat"
	"github.com/bradfitz/http2"
	"github.com/codegangsta/negroni"
	"github.com/gorilla/securecookie"
	"github.com/mattbostock/leavediary/handler"
	"github.com/mattbostock/leavediary/middleware/negroni_logrus"
	"github.com/mattbostock/leavediary/middleware/sessions"
	"github.com/mattbostock/leavediary/model"
	"github.com/unrolled/secure"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/github"
)

const (
	assetsPath  = "assets"
	defaultAddr = "localhost:3000"
	sessionName = "leavediary_session"
)

var (
	config = &struct {
		addr               string
		allowedHosts       []string
		cookieHashKey      []byte
		debug              bool
		dbDialect          string
		dbDataSource       string
		gitHubClientID     string
		gitHubClientSecret string
		rateLimitPerMin    uint8
		tlsCert            string
		tlsKey             string
	}{
		addr:               os.Getenv("ADDR"),
		cookieHashKey:      []byte(os.Getenv("COOKIE_KEY")),
		dbDialect:          os.Getenv("DB_DIALECT"),
		dbDataSource:       os.Getenv("DB_DATASOURCE"),
		debug:              os.Getenv("DEBUG") != "",
		gitHubClientID:     os.Getenv("GITHUB_CLIENT_ID"),
		gitHubClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
		tlsCert:            os.Getenv("TLS_CERT"),
		tlsKey:             os.Getenv("TLS_KEY"),
	}

	mux     = pat.New()
	log     = logrus.New()
	version = ""
)

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	if config.debug {
		log.Level = logrus.DebugLevel
	}

	if config.addr == "" {
		config.addr = defaultAddr
	}

	rate, _ := strconv.ParseUint(os.Getenv("RATE_LIMIT_PER_MIN"), 10, 8)
	config.rateLimitPerMin = uint8(rate)

	if rate == 0 {
		config.rateLimitPerMin = 240
	}
}

func main() {
	if version == "" {
		log.Fatalln(errMakeFileNotUsed)
	}

	v := flag.Bool("version", false, "prints current version")
	flag.Parse()

	if *v {
		fmt.Println(version)
		os.Exit(0)
	}

	if os.Getenv("ALLOWED_HOSTS") == "" {
		config.allowedHosts = nil
	} else {
		config.allowedHosts = strings.Split(os.Getenv("ALLOWED_HOSTS"), ",")
	}

	if len(config.cookieHashKey) == 0 {
		log.Warningln(errNoCookieHashKey)
		config.cookieHashKey = securecookie.GenerateRandomKey(32)
	}
	if len(config.cookieHashKey) != 32 {
		// additonal check as securecookie.GenerateRandomKey() does not return errors
		log.Fatalf(errCookieHashKeyWrongLength, len(config.cookieHashKey))
	}

	if config.gitHubClientID == "" || config.gitHubClientSecret == "" {
		log.Fatalf(errNoGitHubCredentials)
	}

	if config.dbDialect == "" && config.dbDataSource == "" {
		config.dbDialect = "sqlite3"
		config.dbDataSource = ":memory:"
	}

	handler.SetVersion(version)

	handler.SetOauthConfig(&oauth2.Config{
		ClientID:     config.gitHubClientID,
		ClientSecret: config.gitHubClientSecret,
		Endpoint:     github.Endpoint,
		Scopes:       []string{"user:email"},
	})

	model.SetLogger(log)
	model.InitDB(config.dbDialect, config.dbDataSource)

	sessions.SetLogger(log)
	handler.SetLogger(log)

	sessionManager := sessions.New(sessionName, config.cookieHashKey)
	handler.SetSessionManager(sessionManager)

	secureOpts := secure.Options{
		AllowedHosts:          config.allowedHosts,
		BrowserXssFilter:      true,
		ContentSecurityPolicy: "default-src 'self'; script-src 'self' 'sha256-BWV1eSks2QM8blQZAbrSRSwqg3VFfmJ2d6r7yBVBXGY='; style-src 'self' 'unsafe-inline'; img-src 'self' 'data:'",
		FrameDeny:             true,
		STSIncludeSubdomains:  true,
		STSSeconds:            365 * 24 * 60 * 60,
	}
	secureMiddleware := secure.New(secureOpts)

	n := negroni.New()
	n.Use(negroniLogrus.New(log)) // logger must be first middleware
	n.Use(negroni.NewRecovery())
	n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))
	n.Use(negroni.NewStatic(http.Dir(assetsPath)))
	n.UseHandler(sessionManager)
	n.UseHandler(mux)
	registerRoutes()

	// throttle requests by remote IP though X-Forwarded-For could be spoofed
	varyHost := func(r *http.Request) string {
		host, _, _ := net.SplitHostPort(r.RemoteAddr)
		return host + r.Header.Get("X-Forwarded-For")
	}

	t := throttled.RateLimit(throttled.PerMin(config.rateLimitPerMin), &throttled.VaryBy{Custom: varyHost}, store.NewMemStore(1000))
	t.DeniedHandler = http.HandlerFunc(handler.TooManyRequests)
	log.Infof("Throttling requests at %d per minute per remote IP address", config.rateLimitPerMin)
	h := t.Throttle(n)

	log.Infof("Listening on %s", config.addr)

	if config.allowedHosts != nil {
		log.Infof("Allowed HTTP hosts: %q", config.allowedHosts)
	} else {
		log.Warningln(errAllHostsEnabled)
	}

	c := &tls.Config{MinVersion: tls.VersionTLS10} // disable SSLv3, prevent POODLE attack
	s := &http.Server{Addr: config.addr, Handler: h, TLSConfig: c}

	if config.tlsCert == "" && config.tlsKey == "" {
		log.Warningln(errNoTLSCertificate)
		log.Fatal(s.ListenAndServe())
	} else {
		http2.ConfigureServer(s, nil)
		log.Infoln("TLS-only; HTTP/2 enabled")
		log.Fatal(s.ListenAndServeTLS(config.tlsCert, config.tlsKey))
	}
}

const (
	errAllHostsEnabled = "Accepting connections for all HTTP hosts. Consider setting the ALLOWED_HOSTS environment variable."

	errCookieHashKeyWrongLength = "COOKIE_KEY environment variable must be 32 characters long. Length provided: %d"

	errMakeFileNotUsed = "Makefile was not used when compiling binary, run 'make' to re-compile"

	errNoCookieHashKey = "No cookie hash key supplied. You should set the COOKIE_KEY " +
		"environment variable in a production environment. Falling back to use a temporary key " +
		"which will persist only for the current running process."

	errNoGitHubCredentials = "No GitHub Oauth credentials supplied. Set both GITHUB_CLIENT_ID and " +
		"GITHUB_CLIENT_SECRET environment variables."

	errNoTLSCertificate = "No TLS certficiate supplied. Consider setting TLS_CERT " +
		"and TLS_KEY environment variables to enable TLS. LeaveDiary will not work unless you " +
		"are using TLS upstream."
)
<commit_msg>Fix Content Security Policy for data URI images<commit_after>package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"net"
	"net/http"
	"os"
	"runtime"
	"strconv"
	"strings"

	"github.com/PuerkitoBio/throttled"
	"github.com/PuerkitoBio/throttled/store"
	"github.com/Sirupsen/logrus"
	"github.com/bmizerany/pat"
	"github.com/bradfitz/http2"
	"github.com/codegangsta/negroni"
	"github.com/gorilla/securecookie"
	"github.com/mattbostock/leavediary/handler"
	"github.com/mattbostock/leavediary/middleware/negroni_logrus"
	"github.com/mattbostock/leavediary/middleware/sessions"
	"github.com/mattbostock/leavediary/model"
	"github.com/unrolled/secure"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/github"
)

const (
	assetsPath  = "assets"
	defaultAddr = "localhost:3000"
	sessionName = "leavediary_session"
)

var (
	config = &struct {
		addr               string
		allowedHosts       []string
		cookieHashKey      []byte
		debug              bool
		dbDialect          string
		dbDataSource       string
		gitHubClientID     string
		gitHubClientSecret string
		rateLimitPerMin    uint8
		tlsCert            string
		tlsKey             string
	}{
		addr:               os.Getenv("ADDR"),
		cookieHashKey:      []byte(os.Getenv("COOKIE_KEY")),
		dbDialect:          os.Getenv("DB_DIALECT"),
		dbDataSource:       os.Getenv("DB_DATASOURCE"),
		debug:              os.Getenv("DEBUG") != "",
		gitHubClientID:     os.Getenv("GITHUB_CLIENT_ID"),
		gitHubClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
		tlsCert:            os.Getenv("TLS_CERT"),
		tlsKey:             os.Getenv("TLS_KEY"),
	}

	mux     = pat.New()
	log     = logrus.New()
	version = ""
)

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	if config.debug {
		log.Level = logrus.DebugLevel
	}

	if config.addr == "" {
		config.addr = defaultAddr
	}

	rate, _ := strconv.ParseUint(os.Getenv("RATE_LIMIT_PER_MIN"), 10, 8)
	config.rateLimitPerMin = uint8(rate)

	if rate == 0 {
		config.rateLimitPerMin = 240
	}
}

func main() {
	if version == "" {
		log.Fatalln(errMakeFileNotUsed)
	}

	v := flag.Bool("version", false, "prints current version")
	flag.Parse()

	if *v {
		fmt.Println(version)
		os.Exit(0)
	}

	if os.Getenv("ALLOWED_HOSTS") == "" {
		config.allowedHosts = nil
	} else {
		config.allowedHosts = strings.Split(os.Getenv("ALLOWED_HOSTS"), ",")
	}

	if len(config.cookieHashKey) == 0 {
		log.Warningln(errNoCookieHashKey)
		config.cookieHashKey = securecookie.GenerateRandomKey(32)
	}
	if len(config.cookieHashKey) != 32 {
		// additonal check as securecookie.GenerateRandomKey() does not return errors
		log.Fatalf(errCookieHashKeyWrongLength, len(config.cookieHashKey))
	}

	if config.gitHubClientID == "" || config.gitHubClientSecret == "" {
		log.Fatalf(errNoGitHubCredentials)
	}

	if config.dbDialect == "" && config.dbDataSource == "" {
		config.dbDialect = "sqlite3"
		config.dbDataSource = ":memory:"
	}

	handler.SetVersion(version)

	handler.SetOauthConfig(&oauth2.Config{
		ClientID:     config.gitHubClientID,
		ClientSecret: config.gitHubClientSecret,
		Endpoint:     github.Endpoint,
		Scopes:       []string{"user:email"},
	})

	model.SetLogger(log)
	model.InitDB(config.dbDialect, config.dbDataSource)

	sessions.SetLogger(log)
	handler.SetLogger(log)

	sessionManager := sessions.New(sessionName, config.cookieHashKey)
	handler.SetSessionManager(sessionManager)

	secureOpts := secure.Options{
		AllowedHosts:          config.allowedHosts,
		BrowserXssFilter:      true,
		ContentSecurityPolicy: "default-src 'self'; script-src 'self' 'sha256-BWV1eSks2QM8blQZAbrSRSwqg3VFfmJ2d6r7yBVBXGY='; style-src 'self' 'unsafe-inline'; img-src 'self' data:",
		FrameDeny:             true,
		STSIncludeSubdomains:  true,
		STSSeconds:            365 * 24 * 60 * 60,
	}
	secureMiddleware := secure.New(secureOpts)

	n := negroni.New()
	n.Use(negroniLogrus.New(log)) // logger must be first middleware
	n.Use(negroni.NewRecovery())
	n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))
	n.Use(negroni.NewStatic(http.Dir(assetsPath)))
	n.UseHandler(sessionManager)
	n.UseHandler(mux)
	registerRoutes()

	// throttle requests by remote IP though X-Forwarded-For could be spoofed
	varyHost := func(r *http.Request) string {
		host, _, _ := net.SplitHostPort(r.RemoteAddr)
		return host + r.Header.Get("X-Forwarded-For")
	}

	t := throttled.RateLimit(throttled.PerMin(config.rateLimitPerMin), &throttled.VaryBy{Custom: varyHost}, store.NewMemStore(1000))
	t.DeniedHandler = http.HandlerFunc(handler.TooManyRequests)
	log.Infof("Throttling requests at %d per minute per remote IP address", config.rateLimitPerMin)
	h := t.Throttle(n)

	log.Infof("Listening on %s", config.addr)

	if config.allowedHosts != nil {
		log.Infof("Allowed HTTP hosts: %q", config.allowedHosts)
	} else {
		log.Warningln(errAllHostsEnabled)
	}

	c := &tls.Config{MinVersion: tls.VersionTLS10} // disable SSLv3, prevent POODLE attack
	s := &http.Server{Addr: config.addr, Handler: h, TLSConfig: c}

	if config.tlsCert == "" && config.tlsKey == "" {
		log.Warningln(errNoTLSCertificate)
		log.Fatal(s.ListenAndServe())
	} else {
		http2.ConfigureServer(s, nil)
		log.Infoln("TLS-only; HTTP/2 enabled")
		log.Fatal(s.ListenAndServeTLS(config.tlsCert, config.tlsKey))
	}
}

const (
	errAllHostsEnabled = "Accepting connections for all HTTP hosts. Consider setting the ALLOWED_HOSTS environment variable."

	errCookieHashKeyWrongLength = "COOKIE_KEY environment variable must be 32 characters long. Length provided: %d"

	errMakeFileNotUsed = "Makefile was not used when compiling binary, run 'make' to re-compile"

	errNoCookieHashKey = "No cookie hash key supplied. You should set the COOKIE_KEY " +
		"environment variable in a production environment. Falling back to use a temporary key " +
		"which will persist only for the current running process."

	errNoGitHubCredentials = "No GitHub Oauth credentials supplied. Set both GITHUB_CLIENT_ID and " +
		"GITHUB_CLIENT_SECRET environment variables."

	errNoTLSCertificate = "No TLS certficiate supplied. Consider setting TLS_CERT " +
		"and TLS_KEY environment variables to enable TLS. LeaveDiary will not work unless you " +
		"are using TLS upstream."
)
<|endoftext|>