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

/*
	Implements boilerplate code for all controllers
*/
package controllerbase

import (
	"runtime"

	"github.com/astaxie/beego"
	"github.com/goinggo/beego-mgo/app/services"
	"github.com/goinggo/beego-mgo/utilities/mongo"
	"github.com/goinggo/tracelog"
)

//** TYPES

type (
	// BaseController composes all required types and behavior
	BaseController struct {
		beego.Controller
		services.Service
	}
)

//** INTERCEPT FUNCTIONS

// Prepare is called prior to the controller method
func (this *BaseController) Prepare() {
	this.UserId = "unknown" // TODO: Deal With This Later
	tracelog.TRACE(this.UserId, "Before", "UserId[%s] Path[%s]", this.UserId, this.Ctx.Request.URL.Path)

	var err error
	this.MongoSession, err = mongo.CopyMonotonicSession(this.UserId)
	if err != nil {
		tracelog.ERRORf(err, this.UserId, "Before", this.Ctx.Request.URL.Path)
		this.Abort("500")
	}
}

// Finish is called once the controller method completes
func (this *BaseController) Finish() {
	defer func() {
		if this.MongoSession != nil {
			mongo.CloseSession(this.UserId, this.MongoSession)
			this.MongoSession = nil
		}
	}()

	tracelog.COMPLETEDf(this.UserId, "Finish", this.Ctx.Request.URL.Path)
}

//** CATCHING PANICS

// CatchPanic is used to catch any Panic and log exceptions. Returns a 500 as the response
func CatchPanic(controller *BaseController, functionName string) {
	if r := recover(); r != nil {
		if r != "500" {
			buf := make([]byte, 10000)
			runtime.Stack(buf, false)

			tracelog.WARN(controller.Service.UserId, functionName, "PANIC Defered [%v] : Stack Trace : %v", r, string(buf))

			controller.Abort("500")
		}
	}
}
<commit_msg>Handling Exceptions<commit_after>// Copyright 2013 Ardan Studios. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE handle.

/*
	Implements boilerplate code for all controllers
*/
package controllerbase

import (
	"runtime"

	"github.com/astaxie/beego"
	"github.com/goinggo/beego-mgo/app/services"
	"github.com/goinggo/beego-mgo/utilities/mongo"
	"github.com/goinggo/tracelog"
)

//** TYPES

type (
	// BaseController composes all required types and behavior
	BaseController struct {
		beego.Controller
		services.Service
	}
)

//** INTERCEPT FUNCTIONS

// Prepare is called prior to the controller method
func (this *BaseController) Prepare() {
	this.UserId = "unknown" // TODO: Deal With This Later
	tracelog.TRACE(this.UserId, "Before", "UserId[%s] Path[%s]", this.UserId, this.Ctx.Request.URL.Path)

	var err error
	this.MongoSession, err = mongo.CopyMonotonicSession(this.UserId)
	if err != nil {
		tracelog.ERRORf(err, this.UserId, "Before", this.Ctx.Request.URL.Path)
		this.Ctx.Redirect(500, "/")
	}
}

// Finish is called once the controller method completes
func (this *BaseController) Finish() {
	defer func() {
		if this.MongoSession != nil {
			mongo.CloseSession(this.UserId, this.MongoSession)
			this.MongoSession = nil
		}
	}()

	tracelog.COMPLETEDf(this.UserId, "Finish", this.Ctx.Request.URL.Path)
}

//** CATCHING PANICS

// CatchPanic is used to catch any Panic and log exceptions. Returns a 500 as the response
func CatchPanic(controller *BaseController, functionName string) {
	if r := recover(); r != nil {
		if r != "500" {
			buf := make([]byte, 10000)
			runtime.Stack(buf, false)

			tracelog.WARN(controller.Service.UserId, functionName, "PANIC Defered [%v] : Stack Trace : %v", r, string(buf))

			controller.Ctx.Redirect(500, "/")
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/nguyenthenguyen/docx"
	"time"
)

func createDoc(t time.Time) {
	r, err := docx.ReadDocxFile("./Agenda.docx")
	if err != nil {
		panic(err)
	}

	prettyPrintDate := AgendaMonthDayYear(t)
	dateWithPeriods := AgendaDate(t)
	roles := GetRoles(DateWithSlashes(t))

	docx1 := r.Editable()
	fileName := "./" + dateWithPeriods + ".docx"

	docx1.Replace("Date", prettyPrintDate, -1)
	docx1.Replace("president", roles.boardMembers.president, -1)
	docx1.Replace("vpe", roles.boardMembers.vpe, -1)
	docx1.Replace("vpm", roles.boardMembers.vpm, -1)
	docx1.Replace("vppr", roles.boardMembers.vppr, -1)
	docx1.Replace("secretary", roles.boardMembers.secretary, -1)
	docx1.Replace("treasurer", roles.boardMembers.treasurer, -1)
	docx1.Replace("saa", roles.boardMembers.saa, -1)
	docx1.Replace("toastmaster", roles.toastmaster, -1)
	docx1.Replace("generalEval", roles.ge, -1)
	docx1.Replace("timer", roles.timer, -1)
	docx1.Replace("ah-counter", roles.ahCounter, -1)
	docx1.Replace("grammarian", roles.grammarian, -1)
	docx1.Replace("evaluator1", roles.eval1, -1)
	docx1.Replace("speaker1FirstLastName", roles.speaker1, -1)
	docx1.Replace("firstName1", roles.speaker1FirstName, -1)
	docx1.Replace("speaker1Manual", roles.speaker1Manual, -1)
	docx1.Replace("speaker1Speech", roles.speaker1Speech, -1)
	docx1.Replace("evaluator2", roles.eval2, -1)
	docx1.Replace("speaker2FirstLastName", roles.speaker2, -1)
	docx1.Replace("firstName2", roles.speaker2FirstName, -1)
	docx1.Replace("speaker2Manual", roles.speaker2Manual, -1)
	fmt.Println("speaker2FirstLastName", roles.speaker2)
	fmt.Println("speaker2Manual", roles.speaker2Speech)
	docx1.Replace("speaker2Speech", roles.speaker2Speech, -1)
	docx1.Replace("evaluator3", roles.eval3, -1)
	docx1.Replace("speaker3FirstLastName", roles.speaker3, -1)
	docx1.Replace("firstName3", roles.speaker3FirstName, -1)
	docx1.Replace("speaker3Manual", roles.speaker3Manual, -1)
	docx1.Replace("speaker3Speech", roles.speaker3Speech, -1)
	docx1.Replace("evaluator4", roles.eval4, -1)
	docx1.Replace("speaker4FirstLastName", roles.speaker4, -1)
	docx1.Replace("firstName4", roles.speaker4FirstName, -1)
	docx1.Replace("speaker4Manual", roles.speaker4Manual, -1)
	docx1.Replace("speaker4Speech", roles.speaker4Speech, -1)
	docx1.Replace("tTMaster", roles.tableTopicsMaster, -1)

	docx1.WriteToFile(fileName)
	r.Close()
}

func main() {
	d := time.Now()
	t := getNextTuesday(d)

	fmt.Println("Press <Enter> to generate an agenda for", AgendaMonthDayYear(t))
	fmt.Println("or type a new date with the format 'MM/DD/YYYY' and press <Enter>.")

	/*
	 *  Get Input
	 *  func TrimSpace(s string) string	clean up input
	 *  Verify correct string or enter
	 *
	 */

	createDoc(t)
}
<commit_msg>removed debug line.<commit_after>package main

import (
	"fmt"
	"github.com/nguyenthenguyen/docx"
	"time"
)

func createDoc(t time.Time) {
	r, err := docx.ReadDocxFile("./Agenda.docx")
	if err != nil {
		panic(err)
	}

	prettyPrintDate := AgendaMonthDayYear(t)
	dateWithPeriods := AgendaDate(t)
	roles := GetRoles(DateWithSlashes(t))

	docx1 := r.Editable()
	fileName := "./" + dateWithPeriods + ".docx"

	docx1.Replace("Date", prettyPrintDate, -1)
	docx1.Replace("president", roles.boardMembers.president, -1)
	docx1.Replace("vpe", roles.boardMembers.vpe, -1)
	docx1.Replace("vpm", roles.boardMembers.vpm, -1)
	docx1.Replace("vppr", roles.boardMembers.vppr, -1)
	docx1.Replace("secretary", roles.boardMembers.secretary, -1)
	docx1.Replace("treasurer", roles.boardMembers.treasurer, -1)
	docx1.Replace("saa", roles.boardMembers.saa, -1)
	docx1.Replace("toastmaster", roles.toastmaster, -1)
	docx1.Replace("generalEval", roles.ge, -1)
	docx1.Replace("timer", roles.timer, -1)
	docx1.Replace("ah-counter", roles.ahCounter, -1)
	docx1.Replace("grammarian", roles.grammarian, -1)
	docx1.Replace("evaluator1", roles.eval1, -1)
	docx1.Replace("speaker1FirstLastName", roles.speaker1, -1)
	docx1.Replace("firstName1", roles.speaker1FirstName, -1)
	docx1.Replace("speaker1Manual", roles.speaker1Manual, -1)
	docx1.Replace("speaker1Speech", roles.speaker1Speech, -1)
	docx1.Replace("evaluator2", roles.eval2, -1)
	docx1.Replace("speaker2FirstLastName", roles.speaker2, -1)
	docx1.Replace("firstName2", roles.speaker2FirstName, -1)
	docx1.Replace("speaker2Manual", roles.speaker2Manual, -1)
	docx1.Replace("speaker2Speech", roles.speaker2Speech, -1)
	docx1.Replace("evaluator3", roles.eval3, -1)
	docx1.Replace("speaker3FirstLastName", roles.speaker3, -1)
	docx1.Replace("firstName3", roles.speaker3FirstName, -1)
	docx1.Replace("speaker3Manual", roles.speaker3Manual, -1)
	docx1.Replace("speaker3Speech", roles.speaker3Speech, -1)
	docx1.Replace("evaluator4", roles.eval4, -1)
	docx1.Replace("speaker4FirstLastName", roles.speaker4, -1)
	docx1.Replace("firstName4", roles.speaker4FirstName, -1)
	docx1.Replace("speaker4Manual", roles.speaker4Manual, -1)
	docx1.Replace("speaker4Speech", roles.speaker4Speech, -1)
	docx1.Replace("tTMaster", roles.tableTopicsMaster, -1)

	docx1.WriteToFile(fileName)
	r.Close()
}

func main() {
	d := time.Now()
	t := getNextTuesday(d)

	fmt.Println("Press <Enter> to generate an agenda for", AgendaMonthDayYear(t))
	fmt.Println("or type a new date with the format 'MM/DD/YYYY' and press <Enter>.")

	/*
	 *  Get Input
	 *  func TrimSpace(s string) string	clean up input
	 *  Verify correct string or enter
	 *
	 */

	createDoc(t)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/exec"
	"os/signal"
	"regexp"
	"strings"

	"github.com/ninjasphere/gatt"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/support"
)

var log = logger.GetLogger("driver-go-blecombined")
var fpDriver *FlowerPowerDriver
var wpDriver *WaypointDriver
var tagDriver *BLETagDriver
var client *gatt.Client //kill me
var sent = false

func main() {

	log.Infof("BLE Driver Starting")

	// reset BLE layer
	out, err := exec.Command("/opt/ninjablocks/bin/sphere-ble-reset status").Output()
	if err != nil {
		log.Errorf(fmt.Sprintf("error: while checking status of BLE connection: %s. ignoring reset logic.", err))
	} else {
		log.Errorf("error: detected case where BLE stack could not be started properly. signalling need for reset...")
		out, err = exec.Command("/opt/ninjablocks/bin/sphere-ble-reset signal-reset").Output()
		if err == nil {
			log.Errorf("signalling successful. blocking until stopped by reset logic.")
			support.WaitUntilSignal()
		} else {
			log.Errorf("signalling unsuccessful. continuing without waiting.")
		}
	}

	// use hciconfig to the get the mac address
	out, err = exec.Command("hciconfig").Output()
	if err != nil {
		log.Errorf(fmt.Sprintf("Error: %s", err))
	}
	re := regexp.MustCompile("([0-9A-F]{2}\\:{0,1}){6}")
	mac := strings.Replace(re.FindString(string(out)), ":", "", -1)
	log.Infof("The local mac is %s\n", mac)

	client = &gatt.Client{
		StateChange: func(newState string) {
			log.Infof("Client state change: %s", newState)
		},
	}

	fpDriver, err = NewFlowerPowerDriver(client)
	if err != nil {
		log.Errorf("Failed to create FlowerPower driver: ", err)
	}

	wpDriver, err = NewWaypointDriver(client)
	if err != nil {
		log.FatalError(err, "Failed to create waypoint driver")
	}

	tagDriver, err = NewBLETagDriver(client)
	if err != nil {
		log.FatalError(err, "Failed to create BLE Tag driver")
	}

	client.Advertisement = handleAdvertisement

	client.Rssi = func(address string, name string, rssi int8) {
		//log.Printf("Rssi update address:%s rssi:%d", address, rssi)
		wpDriver.sendRssi(strings.Replace(address, ":", "", -1), name, mac, rssi, true)
		//spew.Dump(device);
	}

	log.Infof("Starting client scan")
	err = client.Start()
	if err != nil {
		log.FatalError(err, "Failed to start client")
	}

	err = client.StartScanning(true)
	if err != nil {
		log.FatalError(err, "Failed to start scanning")
	}

	//----------------------------------------------------------------------------------------

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)

	// Block until a signal is received.
	s := <-c
	fmt.Println("Got signal:", s)
}

func handleAdvertisement(device *gatt.DiscoveredDevice) {

	if device.Advertisement.LocalName == "NinjaSphereWaypoint" {
		log.Infof("Found waypoint %s", device.Address)
		wpDriver.handleSphereWaypoint(device)
	}

	for uuid := range device.Advertisement.ServiceUuids {
		if uuid == flowerPowerServiceUuid {
			if fpDriver.announcedFlowerPowers[device.Address] {
				return
			}
			log.Infof("Found Flower Power %s", device.Address)
			err := NewFlowerPower(fpDriver, device)
			if err != nil {
				log.Errorf("Error creating FlowerPower device ", err)
			}
		}
	}

	// look for tags which are CLOSE to the sphere!!
	for uuid := range device.Advertisement.ServiceUuids {
		if uuid == stickNFindServiceUuid {
			if device.Rssi > minRSSI {
				err := NewBLETag(tagDriver, device)
				if err != nil {
					log.Errorf("Error creating BLE Tag device ", err)
				}
			}
		}
	}
}
<commit_msg>fix: use separate arguments to exec.Command.<commit_after>package main

import (
	"fmt"
	"os"
	"os/exec"
	"os/signal"
	"regexp"
	"strings"

	"github.com/ninjasphere/gatt"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/support"
)

var log = logger.GetLogger("driver-go-blecombined")
var fpDriver *FlowerPowerDriver
var wpDriver *WaypointDriver
var tagDriver *BLETagDriver
var client *gatt.Client //kill me
var sent = false

func main() {

	log.Infof("BLE Driver Starting")

	// reset BLE layer
	out, err := exec.Command("/opt/ninjablocks/bin/sphere-ble-reset", "status").Output()
	if err != nil {
		log.Errorf(fmt.Sprintf("error: while checking status of BLE connection: %s. ignoring reset logic.", err))
	} else {
		log.Errorf("error: detected case where BLE stack could not be started properly. signalling need for reset...")
		out, err = exec.Command("/opt/ninjablocks/bin/sphere-ble-reset", "signal-reset").Output()
		if err == nil {
			log.Errorf("signalling successful. blocking until stopped by reset logic.")
			support.WaitUntilSignal()
		} else {
			log.Errorf("signalling unsuccessful. continuing without waiting.")
		}
	}

	// use hciconfig to the get the mac address
	out, err = exec.Command("hciconfig").Output()
	if err != nil {
		log.Errorf(fmt.Sprintf("Error: %s", err))
	}
	re := regexp.MustCompile("([0-9A-F]{2}\\:{0,1}){6}")
	mac := strings.Replace(re.FindString(string(out)), ":", "", -1)
	log.Infof("The local mac is %s\n", mac)

	client = &gatt.Client{
		StateChange: func(newState string) {
			log.Infof("Client state change: %s", newState)
		},
	}

	fpDriver, err = NewFlowerPowerDriver(client)
	if err != nil {
		log.Errorf("Failed to create FlowerPower driver: ", err)
	}

	wpDriver, err = NewWaypointDriver(client)
	if err != nil {
		log.FatalError(err, "Failed to create waypoint driver")
	}

	tagDriver, err = NewBLETagDriver(client)
	if err != nil {
		log.FatalError(err, "Failed to create BLE Tag driver")
	}

	client.Advertisement = handleAdvertisement

	client.Rssi = func(address string, name string, rssi int8) {
		//log.Printf("Rssi update address:%s rssi:%d", address, rssi)
		wpDriver.sendRssi(strings.Replace(address, ":", "", -1), name, mac, rssi, true)
		//spew.Dump(device);
	}

	log.Infof("Starting client scan")
	err = client.Start()
	if err != nil {
		log.FatalError(err, "Failed to start client")
	}

	err = client.StartScanning(true)
	if err != nil {
		log.FatalError(err, "Failed to start scanning")
	}

	//----------------------------------------------------------------------------------------

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)

	// Block until a signal is received.
	s := <-c
	fmt.Println("Got signal:", s)
}

func handleAdvertisement(device *gatt.DiscoveredDevice) {

	if device.Advertisement.LocalName == "NinjaSphereWaypoint" {
		log.Infof("Found waypoint %s", device.Address)
		wpDriver.handleSphereWaypoint(device)
	}

	for uuid := range device.Advertisement.ServiceUuids {
		if uuid == flowerPowerServiceUuid {
			if fpDriver.announcedFlowerPowers[device.Address] {
				return
			}
			log.Infof("Found Flower Power %s", device.Address)
			err := NewFlowerPower(fpDriver, device)
			if err != nil {
				log.Errorf("Error creating FlowerPower device ", err)
			}
		}
	}

	// look for tags which are CLOSE to the sphere!!
	for uuid := range device.Advertisement.ServiceUuids {
		if uuid == stickNFindServiceUuid {
			if device.Rssi > minRSSI {
				err := NewBLETag(tagDriver, device)
				if err != nil {
					log.Errorf("Error creating BLE Tag device ", err)
				}
			}
		}
	}
}
<|endoftext|>


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

package storage

import (
	zklib "github.com/samuel/go-zookeeper/zk"

	"github.com/control-center/serviced/coordinator/client"
	"github.com/control-center/serviced/coordinator/client/zookeeper"
	"github.com/control-center/serviced/domain/host"
	"github.com/control-center/serviced/zzk"
	"github.com/zenoss/glog"

	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"testing"
	"time"
)

func TestClient(t *testing.T) {
	zookeeper.EnsureZkFatjar()
	basePath := ""
	tc, err := zklib.StartTestCluster(1, nil, nil)
	if err != nil {
		t.Fatalf("could not start test zk cluster: %s", err)
	}
	defer os.RemoveAll(tc.Path)
	defer tc.Stop()
	time.Sleep(time.Second)

	servers := []string{fmt.Sprintf("127.0.0.1:%d", tc.Servers[0].Port)}

	dsnBytes, err := json.Marshal(zookeeper.DSN{Servers: servers, Timeout: time.Second * 15})
	if err != nil {
		t.Fatal("unexpected error creating zk DSN: %s", err)
	}
	dsn := string(dsnBytes)
	zClient, err := client.New("zookeeper", dsn, basePath, nil)

	zzk.InitializeLocalClient(zClient)

	conn, err := zzk.GetLocalConnection("/")
	if err != nil {
		t.Fatal("unexpected error getting connection")
	}

	h := host.New()
	h.ID = "nodeID"
	h.IPAddr = "192.168.1.5"
	h.PoolID = "default1"
	defer func(old func(string, os.FileMode) error) {
		mkdirAll = old
	}(mkdirAll)
	dir, err := ioutil.TempDir("", "serviced_var_")
	if err != nil {
		t.Fatalf("could not create tempdir: %s", err)
	}
	defer os.RemoveAll(dir)
	c, err := NewClient(h, dir)
	if err != nil {
		t.Fatalf("unexpected error creating client: %s", err)
	}
	defer c.Close()
	time.Sleep(time.Second * 5)

	// therefore, we need to check that the client was added under the pool from root
	nodePath := fmt.Sprintf("/storage/clients/%s", h.IPAddr)
	glog.Infof("about to check for %s", nodePath)
	if exists, err := conn.Exists(nodePath); err != nil {
		t.Fatalf("did not expect error checking for existence of %s: %s", nodePath, err)
	} else {
		if !exists {
			t.Fatalf("could not find %s", nodePath)
		}
	}
}
<commit_msg>Skipping test for now<commit_after>// Copyright 2014 The Serviced Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package storage

import (
	zklib "github.com/samuel/go-zookeeper/zk"

	"github.com/control-center/serviced/coordinator/client"
	"github.com/control-center/serviced/coordinator/client/zookeeper"
	"github.com/control-center/serviced/domain/host"
	"github.com/control-center/serviced/zzk"
	"github.com/zenoss/glog"

	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"testing"
	"time"
)

func TestClient(t *testing.T) {
	t.Skipf("Test cluster is not set up properly")
	zookeeper.EnsureZkFatjar()
	basePath := ""
	tc, err := zklib.StartTestCluster(1, nil, nil)
	if err != nil {
		t.Fatalf("could not start test zk cluster: %s", err)
	}
	defer os.RemoveAll(tc.Path)
	defer tc.Stop()
	time.Sleep(time.Second)

	servers := []string{fmt.Sprintf("127.0.0.1:%d", tc.Servers[0].Port)}

	dsnBytes, err := json.Marshal(zookeeper.DSN{Servers: servers, Timeout: time.Second * 15})
	if err != nil {
		t.Fatal("unexpected error creating zk DSN: %s", err)
	}
	dsn := string(dsnBytes)
	zClient, err := client.New("zookeeper", dsn, basePath, nil)

	zzk.InitializeLocalClient(zClient)

	conn, err := zzk.GetLocalConnection("/")
	if err != nil {
		t.Fatal("unexpected error getting connection")
	}

	h := host.New()
	h.ID = "nodeID"
	h.IPAddr = "192.168.1.5"
	h.PoolID = "default1"
	defer func(old func(string, os.FileMode) error) {
		mkdirAll = old
	}(mkdirAll)
	dir, err := ioutil.TempDir("", "serviced_var_")
	if err != nil {
		t.Fatalf("could not create tempdir: %s", err)
	}
	defer os.RemoveAll(dir)
	c, err := NewClient(h, dir)
	if err != nil {
		t.Fatalf("unexpected error creating client: %s", err)
	}
	defer c.Close()
	time.Sleep(time.Second * 5)

	// therefore, we need to check that the client was added under the pool from root
	nodePath := fmt.Sprintf("/storage/clients/%s", h.IPAddr)
	glog.Infof("about to check for %s", nodePath)
	if exists, err := conn.Exists(nodePath); err != nil {
		t.Fatalf("did not expect error checking for existence of %s: %s", nodePath, err)
	} else {
		if !exists {
			t.Fatalf("could not find %s", nodePath)
		}
	}
}
<|endoftext|>


<commit_before>package main

import "fmt"
import "github.com/PMoneda/dianadb/compress"

func main() {
	fmt.Println("Hello BoletoApi")
	compress.Zip([]byte("Ola"))

}
<commit_msg>:construction: Adiciona structs dos bancos<commit_after>package main

import "fmt"
import "github.com/PMoneda/dianadb/compress"

// BB
type bbObj struct {
	convenio   convenioBb
	boleto     boletoBb
	pagador    pagadorBb
	controleBb controleBb
}

type boletoBb struct {
	codigoModalidadeTitulo               int
	dataEmissaoTitulo                    string
	dataVencimentoTitulo                 string
	valorOriginalTitulo                  int64
	codigoTipoDesconto                   int16
	codigoTipoJuroMora                   int16
	codigoTipoMulta                      int16
	codigoAceiteTitulo                   string
	codigoTipoTitulo                     int
	indicadorPermissaoRecebimentoParcial string
	textoNumeroTituloCliente             string
}

type pagadorBb struct {
	codigoTipoInscricaoPagador   int16
	numeroInscricaoPagadorNúmero int
	nomePagador                  string
	textoEnderecoPagador         string
	numeroCepPagador             int
	nomeMunicipioPagador         string
	nomeBairroPagador            string
	siglaUfPagador               string
}

type controleBb struct {
	codigoChaveUsuario         string // PIC X(08) WTF?
	codigoTipoCanalSolicitacao int
}

type convenioBb struct {
	numeroConvenio         int
	numeroCarteira         int
	numeroVariacaoCarteira int
}

// Caixa
type caixaObj struct {
	unidade             string
	identificadorOrigem string
	nossoNumero         int64
	tipoEspecie         string // talvez não seja obrigatório
}

// Santander
type santanderObj struct {
	dados     dadosSantander
	expiracao int
	sistema   string
}

type dadosSantander struct {
	convenioSantander convenioSantander
	pagadorSantander  pagadorSantander
	tituloSantander   tituloSantander
	mensagem          string
}

type convenioSantander struct {
	codBanco    string
	codConvenio string
}

type pagadorSantander struct {
	tpDoc    int
	numDoc   int64
	nome     string
	endereco string
	bairro   string
	cidade   string
	uf       string
	cep      int
}

type tituloSantander struct {
	nossoNumero        int64
	seuNumero          string
	dataVencimento     string
	dataEmissao        string
	especie            string
	valorNominal       int64
	pcMulta            int
	qtDiasMulta        int
	pcJuro             int
	tpDesc             int
	valorDesconto      int64
	dataLimiteDesconto string
	valorAbatimento    int64
	tpProtesto         int
	qtDiasProtesto     int
	tituloQtDiasBaixa  int
}

func main() {
	fmt.Println("Hello BoletoApi")
	compress.Zip([]byte("Ola"))

}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
	"sync"

	"github.com/kisielk/errcheck/errcheck"
	"golang.org/x/tools/go/packages"
)

const (
	exitCodeOk int = iota
	exitUncheckedError
	exitFatalError
)

type ignoreFlag map[string]*regexp.Regexp

// global flags
var (
	abspath bool
	verbose bool
)

func (f ignoreFlag) String() string {
	pairs := make([]string, 0, len(f))
	for pkg, re := range f {
		prefix := ""
		if pkg != "" {
			prefix = pkg + ":"
		}
		pairs = append(pairs, prefix+re.String())
	}
	return fmt.Sprintf("%q", strings.Join(pairs, ","))
}

func (f ignoreFlag) Set(s string) error {
	if s == "" {
		return nil
	}
	for _, pair := range strings.Split(s, ",") {
		colonIndex := strings.Index(pair, ":")
		var pkg, re string
		if colonIndex == -1 {
			pkg = ""
			re = pair
		} else {
			pkg = pair[:colonIndex]
			re = pair[colonIndex+1:]
		}
		regex, err := regexp.Compile(re)
		if err != nil {
			return err
		}
		f[pkg] = regex
	}
	return nil
}

type tagsFlag []string

func (f *tagsFlag) String() string {
	return fmt.Sprintf("%q", strings.Join(*f, ","))
}

func (f *tagsFlag) Set(s string) error {
	if s == "" {
		return nil
	}
	tags := strings.FieldsFunc(s, func(c rune) bool {
		return c == ' ' || c == ','
	})
	for _, tag := range tags {
		if tag != "" {
			*f = append(*f, tag)
		}
	}
	return nil
}

func reportResult(e *errcheck.Result) {
	wd, err := os.Getwd()
	if err != nil {
		wd = ""
	}
	for _, uncheckedError := range e.Errors {
		pos := uncheckedError.Pos.String()
		if !abspath {
			newPos, err := filepath.Rel(wd, pos)
			if err == nil {
				pos = newPos
			}
		}

		if verbose && uncheckedError.FuncName != "" {
			fmt.Printf("%s:\t%s\t%s\n", pos, uncheckedError.FuncName, uncheckedError.Line)
		} else {
			fmt.Printf("%s:\t%s\n", pos, uncheckedError.Line)
		}
	}
}

func logf(msg string, args ...interface{}) {
	if verbose {
		fmt.Fprintf(os.Stderr, msg+"\n", args...)
	}
}

func mainCmd(args []string) int {
	var checker errcheck.Checker
	paths, err := parseFlags(&checker, args)
	if err != exitCodeOk {
		return err
	}

	if err := checkPaths(&checker, paths...); err != nil {
		if e, ok := err.(*errcheck.Result); ok {
			reportResult(e)
			return exitUncheckedError
		} else if err == errcheck.ErrNoGoFiles {
			fmt.Fprintln(os.Stderr, err)
			return exitCodeOk
		}
		fmt.Fprintf(os.Stderr, "error: failed to check packages: %s\n", err)
		return exitFatalError
	}
	return exitCodeOk
}

func checkPaths(c *errcheck.Checker, paths ...string) error {
	pkgs, err := c.LoadPackages(paths...)
	if err != nil {
		return err
	}
	// Check for errors in the initial packages.
	work := make(chan *packages.Package, len(pkgs))
	for _, pkg := range pkgs {
		if len(pkg.Errors) > 0 {
			return fmt.Errorf("errors while loading package %s: %v", pkg.ID, pkg.Errors)
		}
		work <- pkg
	}
	close(work)

	var wg sync.WaitGroup
	u := &errcheck.Result{}
	for i := 0; i < runtime.NumCPU(); i++ {
		wg.Add(1)

		go func() {
			defer wg.Done()
			for pkg := range work {
				logf("checking %s", pkg.Types.Path())
				u.Append(c.CheckPackage(pkg))
			}
		}()
	}

	wg.Wait()
	if u.Len() > 0 {
		return u.Unique()
	}
	return nil
}

func parseFlags(checker *errcheck.Checker, args []string) ([]string, int) {
	flags := flag.NewFlagSet(args[0], flag.ContinueOnError)

	var checkAsserts, checkBlanks bool

	flags.BoolVar(&checkBlanks, "blank", false, "if true, check for errors assigned to blank identifier")
	flags.BoolVar(&checkAsserts, "asserts", false, "if true, check for ignored type assertion results")
	flags.BoolVar(&checker.Exclusions.TestFiles, "ignoretests", false, "if true, checking of _test.go files is disabled")
	flags.BoolVar(&checker.Exclusions.GeneratedFiles, "ignoregenerated", false, "if true, checking of files with generated code is disabled")
	flags.BoolVar(&verbose, "verbose", false, "produce more verbose logging")

	flags.BoolVar(&abspath, "abspath", false, "print absolute paths to files")

	tags := tagsFlag{}
	flags.Var(&tags, "tags", "comma or space-separated list of build tags to include")
	ignorePkg := flags.String("ignorepkg", "", "comma-separated list of package paths to ignore")
	ignore := ignoreFlag(map[string]*regexp.Regexp{})
	flags.Var(ignore, "ignore", "[deprecated] comma-separated list of pairs of the form pkg:regex\n"+
		"            the regex is used to ignore names within pkg.")

	var excludeFile string
	flags.StringVar(&excludeFile, "exclude", "", "Path to a file containing a list of functions to exclude from checking")

	var excludeOnly bool
	flags.BoolVar(&excludeOnly, "excludeonly", false, "Use only excludes from -exclude file")

	if err := flags.Parse(args[1:]); err != nil {
		return nil, exitFatalError
	}

	checker.Exclusions.BlankAssignments = !checkBlanks
	checker.Exclusions.TypeAssertions = !checkAsserts

	if !excludeOnly {
		checker.Exclusions.Symbols = append(checker.Exclusions.Symbols, errcheck.DefaultExcludedSymbols...)
	}

	if excludeFile != "" {
		excludes, err := readExcludes(excludeFile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not read exclude file: %v\n", err)
			return nil, exitFatalError
		}
		checker.Exclusions.Symbols = append(checker.Exclusions.Symbols, excludes...)
	}

	checker.Tags = tags
	for _, pkg := range strings.Split(*ignorePkg, ",") {
		if pkg != "" {
			checker.Exclusions.Packages = append(checker.Exclusions.Packages, pkg)
		}
	}

	checker.Exclusions.SymbolRegexpsByPackage = ignore

	paths := flags.Args()
	if len(paths) == 0 {
		paths = []string{"."}
	}

	return paths, exitCodeOk
}

// readExcludes reads an excludes file, a newline delimited file that lists
// patterns for which to allow unchecked errors.
func readExcludes(path string) ([]string, error) {
	var excludes []string

	buf, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	scanner := bufio.NewScanner(bytes.NewReader(buf))

	for scanner.Scan() {
		name := scanner.Text()
		// Skip comments and empty lines.
		if strings.HasPrefix(name, "//") || name == "" {
			continue
		}
		excludes = append(excludes, name)
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return excludes, nil
}

func main() {
	os.Exit(mainCmd(os.Args))
}
<commit_msg>Refactor main.checkPaths a bit<commit_after>package main

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
	"sync"

	"github.com/kisielk/errcheck/errcheck"
	"golang.org/x/tools/go/packages"
)

const (
	exitCodeOk int = iota
	exitUncheckedError
	exitFatalError
)

type ignoreFlag map[string]*regexp.Regexp

// global flags
var (
	abspath bool
	verbose bool
)

func (f ignoreFlag) String() string {
	pairs := make([]string, 0, len(f))
	for pkg, re := range f {
		prefix := ""
		if pkg != "" {
			prefix = pkg + ":"
		}
		pairs = append(pairs, prefix+re.String())
	}
	return fmt.Sprintf("%q", strings.Join(pairs, ","))
}

func (f ignoreFlag) Set(s string) error {
	if s == "" {
		return nil
	}
	for _, pair := range strings.Split(s, ",") {
		colonIndex := strings.Index(pair, ":")
		var pkg, re string
		if colonIndex == -1 {
			pkg = ""
			re = pair
		} else {
			pkg = pair[:colonIndex]
			re = pair[colonIndex+1:]
		}
		regex, err := regexp.Compile(re)
		if err != nil {
			return err
		}
		f[pkg] = regex
	}
	return nil
}

type tagsFlag []string

func (f *tagsFlag) String() string {
	return fmt.Sprintf("%q", strings.Join(*f, ","))
}

func (f *tagsFlag) Set(s string) error {
	if s == "" {
		return nil
	}
	tags := strings.FieldsFunc(s, func(c rune) bool {
		return c == ' ' || c == ','
	})
	for _, tag := range tags {
		if tag != "" {
			*f = append(*f, tag)
		}
	}
	return nil
}

func reportResult(e *errcheck.Result) {
	wd, err := os.Getwd()
	if err != nil {
		wd = ""
	}
	for _, uncheckedError := range e.Errors {
		pos := uncheckedError.Pos.String()
		if !abspath {
			newPos, err := filepath.Rel(wd, pos)
			if err == nil {
				pos = newPos
			}
		}

		if verbose && uncheckedError.FuncName != "" {
			fmt.Printf("%s:\t%s\t%s\n", pos, uncheckedError.FuncName, uncheckedError.Line)
		} else {
			fmt.Printf("%s:\t%s\n", pos, uncheckedError.Line)
		}
	}
}

func logf(msg string, args ...interface{}) {
	if verbose {
		fmt.Fprintf(os.Stderr, msg+"\n", args...)
	}
}

func mainCmd(args []string) int {
	var checker errcheck.Checker
	paths, rc := parseFlags(&checker, args)
	if rc != exitCodeOk {
		return rc
	}

	result, err := checkPaths(&checker, paths...)
	if err != nil {
		if err == errcheck.ErrNoGoFiles {
			fmt.Fprintln(os.Stderr, err)
			return exitCodeOk
		}
		fmt.Fprintf(os.Stderr, "error: failed to check packages: %s\n", err)
		return exitFatalError
	}
	if result.Len() > 0 {
		reportResult(result)
		return exitUncheckedError
	}
	return exitCodeOk
}

func checkPaths(c *errcheck.Checker, paths ...string) (*errcheck.Result, error) {
	pkgs, err := c.LoadPackages(paths...)
	if err != nil {
		return nil, err
	}
	// Check for errors in the initial packages.
	work := make(chan *packages.Package, len(pkgs))
	for _, pkg := range pkgs {
		if len(pkg.Errors) > 0 {
			return nil, fmt.Errorf("errors while loading package %s: %v", pkg.ID, pkg.Errors)
		}
		work <- pkg
	}
	close(work)

	var wg sync.WaitGroup
	result := &errcheck.Result{}
	for i := 0; i < runtime.NumCPU(); i++ {
		wg.Add(1)

		go func() {
			defer wg.Done()
			for pkg := range work {
				logf("checking %s", pkg.Types.Path())
				result.Append(c.CheckPackage(pkg))
			}
		}()
	}

	wg.Wait()
	return result.Unique(), nil
}

func parseFlags(checker *errcheck.Checker, args []string) ([]string, int) {
	flags := flag.NewFlagSet(args[0], flag.ContinueOnError)

	var checkAsserts, checkBlanks bool

	flags.BoolVar(&checkBlanks, "blank", false, "if true, check for errors assigned to blank identifier")
	flags.BoolVar(&checkAsserts, "asserts", false, "if true, check for ignored type assertion results")
	flags.BoolVar(&checker.Exclusions.TestFiles, "ignoretests", false, "if true, checking of _test.go files is disabled")
	flags.BoolVar(&checker.Exclusions.GeneratedFiles, "ignoregenerated", false, "if true, checking of files with generated code is disabled")
	flags.BoolVar(&verbose, "verbose", false, "produce more verbose logging")

	flags.BoolVar(&abspath, "abspath", false, "print absolute paths to files")

	tags := tagsFlag{}
	flags.Var(&tags, "tags", "comma or space-separated list of build tags to include")
	ignorePkg := flags.String("ignorepkg", "", "comma-separated list of package paths to ignore")
	ignore := ignoreFlag(map[string]*regexp.Regexp{})
	flags.Var(ignore, "ignore", "[deprecated] comma-separated list of pairs of the form pkg:regex\n"+
		"            the regex is used to ignore names within pkg.")

	var excludeFile string
	flags.StringVar(&excludeFile, "exclude", "", "Path to a file containing a list of functions to exclude from checking")

	var excludeOnly bool
	flags.BoolVar(&excludeOnly, "excludeonly", false, "Use only excludes from -exclude file")

	if err := flags.Parse(args[1:]); err != nil {
		return nil, exitFatalError
	}

	checker.Exclusions.BlankAssignments = !checkBlanks
	checker.Exclusions.TypeAssertions = !checkAsserts

	if !excludeOnly {
		checker.Exclusions.Symbols = append(checker.Exclusions.Symbols, errcheck.DefaultExcludedSymbols...)
	}

	if excludeFile != "" {
		excludes, err := readExcludes(excludeFile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not read exclude file: %v\n", err)
			return nil, exitFatalError
		}
		checker.Exclusions.Symbols = append(checker.Exclusions.Symbols, excludes...)
	}

	checker.Tags = tags
	for _, pkg := range strings.Split(*ignorePkg, ",") {
		if pkg != "" {
			checker.Exclusions.Packages = append(checker.Exclusions.Packages, pkg)
		}
	}

	checker.Exclusions.SymbolRegexpsByPackage = ignore

	paths := flags.Args()
	if len(paths) == 0 {
		paths = []string{"."}
	}

	return paths, exitCodeOk
}

// readExcludes reads an excludes file, a newline delimited file that lists
// patterns for which to allow unchecked errors.
func readExcludes(path string) ([]string, error) {
	var excludes []string

	buf, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	scanner := bufio.NewScanner(bytes.NewReader(buf))

	for scanner.Scan() {
		name := scanner.Text()
		// Skip comments and empty lines.
		if strings.HasPrefix(name, "//") || name == "" {
			continue
		}
		excludes = append(excludes, name)
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return excludes, nil
}

func main() {
	os.Exit(mainCmd(os.Args))
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path"
	"strings"

	"github.com/drone/drone-plugin-go/plugin"
)

type Npm struct {
	Username   string `json:"username"`
	Password   string `json:"password"`
	Email      string `json:"email"`
	Registry   string `json:"registry"`
	Folder     string `json:"folder"`
	AlwaysAuth bool   `json:"always_auth"`
}

type NpmPackage struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

func main() {
	repo := plugin.Repo{}
	build := plugin.Build{}
	workspace := plugin.Workspace{}
	vargs := Npm{}

	plugin.Param("build", &build)
	plugin.Param("repo", &repo)
	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)

	// parse the parameters
	if err := plugin.Parse(); err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	// check for required parameters
	if len(vargs.Username) == 0 {
		fmt.Println("Username not provided")
		os.Exit(1)
	}

	if len(vargs.Password) == 0 {
		fmt.Println("Password not provided")
		os.Exit(1)
	}

	if len(vargs.Email) == 0 {
		fmt.Println("Email not provided")
		os.Exit(1)
	}

	// set defaults
	var globalRegistry bool

	if len(vargs.Registry) == 0 {
		vargs.Registry = "https://registry.npmjs.org"
		globalRegistry = true
	} else {
		globalRegistry = false
	}

	// get the package info
	var packagePath string

	if len(vargs.Folder) == 0 {
		packagePath = path.Join(workspace.Path)
	} else {
		packagePath = path.Join(workspace.Path, vargs.Folder)
	}

	packageFile := path.Join(packagePath, "package.json")

	npmPackage, err := readPackageFile(packageFile)

	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	// see if the package should be published
	publish, err := shouldPublishPackage(vargs, npmPackage)

	if publish {
		fmt.Println("Attempting to publish package")

		// write the npmrc file
		npmrcPath := path.Join(packagePath, ".npmrc")
		err := writeNpmrcFile(vargs, npmrcPath)

		if err != nil {
			fmt.Println(err.Error())
			os.Exit(1)
		}

		var cmds []*exec.Cmd

		// write registry command
		if !globalRegistry {
			cmds = append(cmds, registryCommand(vargs))
		}

		// write auth command
		if vargs.AlwaysAuth {
			cmds = append(cmds, alwaysAuthCommand())
		}

		// write the publish command
		cmds = append(cmds, publishCommand())

		// run the commands
		for _, cmd := range cmds {
			cmd.Dir = packagePath
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			trace(cmd)
			err := cmd.Run()
			if err != nil {
				os.Exit(1)
			}
		}
	} else {
		fmt.Println("Package already published")
	}
}

/// Reads the package file at the given path
func readPackageFile(path string) (*NpmPackage, error) {
	// read the file
	file, err := ioutil.ReadFile(path)

	if err != nil {
		return nil, err
	}

	// unmarshal the json data
	npmPackage := NpmPackage{}
	err = json.Unmarshal(file, &npmPackage)

	if err != nil {
		return nil, err
	}

	// make sure values are present
	if len(npmPackage.Name) == 0 {
		return nil, errors.New("No package name present")
	}

	if len(npmPackage.Version) == 0 {
		return nil, errors.New("No package version present")
	}

	return &npmPackage, nil
}

/// Determines if the package should be published
func shouldPublishPackage(vargs Npm, npmPackage *NpmPackage) (bool, error) {
	// get the url for the package
	packageUrl := fmt.Sprintf("%s/%s/%s", vargs.Registry, npmPackage.Name, npmPackage.Version)
	fmt.Printf("Requesting %s\n", packageUrl)

	// create a request for the package
	req, err := http.NewRequest("GET", packageUrl, nil)

	if err != nil {
		return false, err
	}

	// set authentication if needed
	// NPM uses basic http auth
	if vargs.AlwaysAuth {
		req.SetBasicAuth(vargs.Username, vargs.Password)
	}

	// get the response
	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return false, err
	}

	defer resp.Body.Close()

	// look for a 404 to see if the package should be published
	if resp.StatusCode != http.StatusNotFound {
		return false, nil
	} else {
		return true, nil
	}
}

/// Writes the npmrc file
func writeNpmrcFile(vargs Npm, path string) error {
	// get the base64 encoded string
	authString := fmt.Sprintf("%s:%s", vargs.Username, vargs.Password)
	encoded := base64.StdEncoding.EncodeToString([]byte(authString))

	// create the file contents
	contents := fmt.Sprintf("_auth = %s\nemail = %s", encoded, vargs.Email)

	// write the file
	return ioutil.WriteFile(path, []byte(contents), 0644)
}

// Sets the npm registry
func registryCommand(vargs Npm) *exec.Cmd {
	return exec.Command("npm", "config", "set", "registry", vargs.Registry)
}

// Sets the always off flag
func alwaysAuthCommand() *exec.Cmd {
	return exec.Command("npm", "config", "set", "always-auth", "true")
}

// Publishes the package
func publishCommand() *exec.Cmd {
	return exec.Command("npm", "publish")
}

// Trace writes each command to standard error (preceded by a ‘$ ’) before it
// is executed. Used for debugging your build.
func trace(cmd *exec.Cmd) {
	fmt.Println("$", strings.Join(cmd.Args, " "))
}
<commit_msg>add .npmrc to the user home directory so that it doesn't get published<commit_after>package main

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path"
	"strings"

	"github.com/drone/drone-go/drone"
	"github.com/drone/drone-go/plugin"
)

type Npm struct {
	Username   string `json:"username"`
	Password   string `json:"password"`
	Email      string `json:"email"`
	Registry   string `json:"registry"`
	Folder     string `json:"folder"`
	AlwaysAuth bool   `json:"always_auth"`
}

type NpmPackage struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

func main() {
	repo := drone.Repo{}
	build := drone.Build{}
	workspace := drone.Workspace{}
	vargs := Npm{}

	plugin.Param("build", &build)
	plugin.Param("repo", &repo)
	plugin.Param("workspace", &workspace)
	plugin.Param("vargs", &vargs)

	// parse the parameters
	if err := plugin.Parse(); err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	// check for required parameters
	if len(vargs.Username) == 0 {
		fmt.Println("Username not provided")
		os.Exit(1)
	}

	if len(vargs.Password) == 0 {
		fmt.Println("Password not provided")
		os.Exit(1)
	}

	if len(vargs.Email) == 0 {
		fmt.Println("Email not provided")
		os.Exit(1)
	}

	// set defaults
	var globalRegistry bool

	if len(vargs.Registry) == 0 {
		vargs.Registry = "https://registry.npmjs.org"
		globalRegistry = true
	} else {
		globalRegistry = false
	}

	// get the package info
	var packagePath string

	if len(vargs.Folder) == 0 {
		packagePath = path.Join(workspace.Path)
	} else {
		packagePath = path.Join(workspace.Path, vargs.Folder)
	}

	packageFile := path.Join(packagePath, "package.json")

	npmPackage, err := readPackageFile(packageFile)

	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	// see if the package should be published
	publish, err := shouldPublishPackage(vargs, npmPackage)

	if publish {
		fmt.Println("Attempting to publish package")

		// write the npmrc file
		err := writeNpmrcFile(vargs)

		if err != nil {
			fmt.Println(err.Error())
			os.Exit(1)
		}

		var cmds []*exec.Cmd

		// write registry command
		if !globalRegistry {
			cmds = append(cmds, registryCommand(vargs))
		}

		// write auth command
		if vargs.AlwaysAuth {
			cmds = append(cmds, alwaysAuthCommand())
		}

		// write the publish command
		cmds = append(cmds, publishCommand())

		// run the commands
		for _, cmd := range cmds {
			cmd.Dir = packagePath
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			trace(cmd)
			err := cmd.Run()
			if err != nil {
				os.Exit(1)
			}
		}
	} else {
		fmt.Println("Package already published")
	}
}

/// Reads the package file at the given path
func readPackageFile(path string) (*NpmPackage, error) {
	// read the file
	file, err := ioutil.ReadFile(path)

	if err != nil {
		return nil, err
	}

	// unmarshal the json data
	npmPackage := NpmPackage{}
	err = json.Unmarshal(file, &npmPackage)

	if err != nil {
		return nil, err
	}

	// make sure values are present
	if len(npmPackage.Name) == 0 {
		return nil, errors.New("No package name present")
	}

	if len(npmPackage.Version) == 0 {
		return nil, errors.New("No package version present")
	}

	return &npmPackage, nil
}

/// Determines if the package should be published
func shouldPublishPackage(vargs Npm, npmPackage *NpmPackage) (bool, error) {
	// get the url for the package
	packageUrl := fmt.Sprintf("%s/%s/%s", vargs.Registry, npmPackage.Name, npmPackage.Version)
	fmt.Printf("Requesting %s\n", packageUrl)

	// create a request for the package
	req, err := http.NewRequest("GET", packageUrl, nil)

	if err != nil {
		return false, err
	}

	// set authentication if needed
	// NPM uses basic http auth
	if vargs.AlwaysAuth {
		req.SetBasicAuth(vargs.Username, vargs.Password)
	}

	// get the response
	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		return false, err
	}

	defer resp.Body.Close()

	// look for a 404 to see if the package should be published
	if resp.StatusCode != http.StatusNotFound {
		return false, nil
	} else {
		return true, nil
	}
}

/// Writes the npmrc file
func writeNpmrcFile(vargs Npm) error {

	// get the base64 encoded string
	authString := fmt.Sprintf("%s:%s", vargs.Username, vargs.Password)
	encoded := base64.StdEncoding.EncodeToString([]byte(authString))

	// create the file contents
	contents := fmt.Sprintf("_auth = %s\nemail = %s", encoded, vargs.Email)

	// write the file
	return ioutil.WriteFile("/root/.npmrc", []byte(contents), 0644)
}

// Sets the npm registry
func registryCommand(vargs Npm) *exec.Cmd {
	return exec.Command("npm", "config", "set", "registry", vargs.Registry)
}

// Sets the always off flag
func alwaysAuthCommand() *exec.Cmd {
	return exec.Command("npm", "config", "set", "always-auth", "true")
}

// Publishes the package
func publishCommand() *exec.Cmd {
	return exec.Command("npm", "publish")
}

// Trace writes each command to standard error (preceded by a ‘$ ’) before it
// is executed. Used for debugging your build.
func trace(cmd *exec.Cmd) {
	fmt.Println("$", strings.Join(cmd.Args, " "))
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"sync"
)

func main() {
	// Call realMain so that defers work properly, since os.Exit won't
	// call defers.
	os.Exit(realMain())
}

func realMain() int {
	var outputTpl string
	var parallel int
	flags := flag.NewFlagSet("gox", flag.ExitOnError)
	flags.Usage = func() { printUsage() }
	flags.StringVar(&outputTpl, "output", "{{.Dir}}_{{.OS}}_{{.Arch}}", "output path")
	flags.IntVar(&parallel, "parallel", -1, "parallelization factor")
	if err := flags.Parse(os.Args[1:]); err != nil {
		flags.Usage()
		return 1
	}

	if _, err := exec.LookPath("go"); err != nil {
		fmt.Fprintf(os.Stderr, "go executable must be on the PATH\n")
		return 1
	}

	version, err := GoVersion()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error reading Go version: %s", err)
		return 1
	}

	// Determine the packages that we want to compile. We have to be sure
	// to turn any absolute paths into relative paths so that they work
	// properly with `go list`.
	packages := flags.Args()
	if len(packages) == 0 {
		packages = []string{"."}
	}

	// Determine what amount of parallelism we want
	if parallel <= 0 {
		parallel = runtime.NumCPU()
	}
	fmt.Printf("Number of parallel builds: %d\n", parallel)

	// Get the packages that are in the given paths
	mainDirs, err := GoMainDirs(packages)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error reading packages: %s", err)
		return 1
	}

	// Determine the platforms we're building for
	platforms := SupportedPlatforms(version)

	// Build in parallel!
	var errorLock sync.Mutex
	var wg sync.WaitGroup
	errors := make([]string, 0)
	semaphore := make(chan int, parallel)
	for _, platform := range platforms {
		for _, path := range mainDirs {
			// Start the goroutine that will do the actual build
			wg.Add(1)
			go func(path string, platform Platform) {
				defer wg.Done()
				semaphore <- 1
				fmt.Printf("--> %s: %s\n", platform.String(), path)
				if err := GoCrossCompile(path, platform, outputTpl); err != nil {
					errorLock.Lock()
					defer errorLock.Unlock()
					errors = append(errors,
						fmt.Sprintf("%s error: %s", platform.String(), err))
				}
				<-semaphore
			}(path, platform)
		}
	}
	wg.Wait()

	if len(errors) > 0 {
		fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errors))
		for _, err := range errors {
			fmt.Fprintf(os.Stderr, "--> %s\n", err)
		}
		return 1
	}

	return 0
}

func printUsage() {
	fmt.Fprintf(os.Stderr, helpText)
}

const helpText = `Usage: gox [options] [packages]

  Gox cross-compiles Go applications in parallel.

Options:

  -output="foo"       Output path template. See below for more info.
  -parallel=-1        Amount of parallelism, defaults to number of CPUs.

Output path template:

  The output path for the compiled binaries is specified with the
  "-output" flag. The value is a string that is a Go text template.
  The default value is "{{.Dir}}_{{.OS}}_{{.Arch}}". The variables and
  their values should be self-explanatory.

`
<commit_msg>Comments on main.go<commit_after>package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"sync"
)

func main() {
	// Call realMain so that defers work properly, since os.Exit won't
	// call defers.
	os.Exit(realMain())
}

func realMain() int {
	var outputTpl string
	var parallel int
	flags := flag.NewFlagSet("gox", flag.ExitOnError)
	flags.Usage = func() { printUsage() }
	flags.StringVar(&outputTpl, "output", "{{.Dir}}_{{.OS}}_{{.Arch}}", "output path")
	flags.IntVar(&parallel, "parallel", -1, "parallelization factor")
	if err := flags.Parse(os.Args[1:]); err != nil {
		flags.Usage()
		return 1
	}

	if _, err := exec.LookPath("go"); err != nil {
		fmt.Fprintf(os.Stderr, "go executable must be on the PATH\n")
		return 1
	}

	version, err := GoVersion()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error reading Go version: %s", err)
		return 1
	}

	// Determine the packages that we want to compile. Default to the
	// current directory if none are specified.
	packages := flags.Args()
	if len(packages) == 0 {
		packages = []string{"."}
	}

	// Determine what amount of parallelism we want Default to the current
	// number of CPUs is <= 0 is specified.
	if parallel <= 0 {
		parallel = runtime.NumCPU()
	}
	fmt.Printf("Number of parallel builds: %d\n", parallel)

	// Get the packages that are in the given paths
	mainDirs, err := GoMainDirs(packages)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error reading packages: %s", err)
		return 1
	}

	// Determine the platforms we're building for
	platforms := SupportedPlatforms(version)

	// Build in parallel!
	var errorLock sync.Mutex
	var wg sync.WaitGroup
	errors := make([]string, 0)
	semaphore := make(chan int, parallel)
	for _, platform := range platforms {
		for _, path := range mainDirs {
			// Start the goroutine that will do the actual build
			wg.Add(1)
			go func(path string, platform Platform) {
				defer wg.Done()
				semaphore <- 1
				fmt.Printf("--> %s: %s\n", platform.String(), path)
				if err := GoCrossCompile(path, platform, outputTpl); err != nil {
					errorLock.Lock()
					defer errorLock.Unlock()
					errors = append(errors,
						fmt.Sprintf("%s error: %s", platform.String(), err))
				}
				<-semaphore
			}(path, platform)
		}
	}
	wg.Wait()

	if len(errors) > 0 {
		fmt.Fprintf(os.Stderr, "\n%d errors occurred:\n", len(errors))
		for _, err := range errors {
			fmt.Fprintf(os.Stderr, "--> %s\n", err)
		}
		return 1
	}

	return 0
}

func printUsage() {
	fmt.Fprintf(os.Stderr, helpText)
}

const helpText = `Usage: gox [options] [packages]

  Gox cross-compiles Go applications in parallel.

Options:

  -output="foo"       Output path template. See below for more info.
  -parallel=-1        Amount of parallelism, defaults to number of CPUs.

Output path template:

  The output path for the compiled binaries is specified with the
  "-output" flag. The value is a string that is a Go text template.
  The default value is "{{.Dir}}_{{.OS}}_{{.Arch}}". The variables and
  their values should be self-explanatory.

`
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/robdimsdale/wl"
	wl_logger "github.com/robdimsdale/wl/logger"
	wl_oauth "github.com/robdimsdale/wl/oauth"
)

func main() {
	client := wl_oauth.NewClient(
		os.Getenv("WL_ACCESS_TOKEN"),
		os.Getenv("WL_CLIENT_ID"),
		wl.APIURL,
		wl_logger.NewLogger(wl_logger.INFO),
	)

	root, err := client.Root()
	if err != nil {
		log.Fatal(err)
	}

	myID := root.UserID

	tasks, err := client.Tasks()
	if err != nil {
		log.Fatal(err)
	}

	filtered := []wl.Task{}

	for _, task := range tasks {
		// Remove completed tasks
		if task.Completed {
			continue
		}

		// Remove tasks assigned to someone else
		if task.AssigneeID != uint(0) && task.AssigneeID != myID {
			continue
		}

		// Include tasks assigned to me or starred
		if task.AssigneeID == myID || task.Starred {
			filtered = append(filtered, task)
			continue
		}

		// Include overdue tasks
		if !task.DueDate.IsZero() && time.Now().After(task.DueDate) {
			filtered = append(filtered, task)
		}

	}

	if len(filtered) == 0 {
		return
	}

	fmt.Printf("✅ %v\n", len(filtered))

	for _, task := range filtered {
		fmt.Println(task.Title)
	}
}
<commit_msg>Pretty list/task formatting<commit_after>package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/robdimsdale/wl"
	wl_logger "github.com/robdimsdale/wl/logger"
	wl_oauth "github.com/robdimsdale/wl/oauth"
)

func main() {
	client := wl_oauth.NewClient(
		os.Getenv("WL_ACCESS_TOKEN"),
		os.Getenv("WL_CLIENT_ID"),
		wl.APIURL,
		wl_logger.NewLogger(wl_logger.INFO),
	)

	root, err := client.Root()
	if err != nil {
		log.Fatal(err)
	}

	myID := root.UserID

	lists, err := client.Lists()
	if err != nil {
		log.Fatal(err)
	}

	tasks, err := client.Tasks()
	if err != nil {
		log.Fatal(err)
	}

	filtered := []wl.Task{}

	for _, task := range tasks {
		// Remove completed tasks
		if task.Completed {
			continue
		}

		// Remove tasks assigned to someone else
		if task.AssigneeID != uint(0) && task.AssigneeID != myID {
			continue
		}

		// Include tasks assigned to me or starred
		if task.AssigneeID == myID || task.Starred {
			filtered = append(filtered, task)
			continue
		}

		// Include overdue tasks
		if !task.DueDate.IsZero() && time.Now().After(task.DueDate) {
			filtered = append(filtered, task)
		}

	}

	if len(filtered) == 0 {
		return
	}

	fmt.Printf("✅ %v\n", len(filtered))

	var lastList uint

	for _, task := range filtered {
		// Print the list header
		if lastList != task.ListID {
			for _, list := range lists {
				if list.ID == task.ListID {
					fmt.Printf("\n%s\n\n", list.Title)
					lastList = list.ID
					break
				}
			}
		}

		fmt.Printf("  %s\n", task.Title)
	}

	fmt.Println()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/rancher/convoy/api"
	"github.com/rancher/convoy/client"
	"os"
)

const (
	// version of Convoy
	VERSION = "0.4.2"
)

func cleanup() {
	if r := recover(); r != nil {
		api.ResponseLogAndError(r)
		os.Exit(1)
	}
}

func main() {
	defer cleanup()

	cli := client.NewCli(VERSION)
	err := cli.Run(os.Args)
	if err != nil {
		panic(fmt.Errorf("Error when executing command: %v", err))
	}
}
<commit_msg>Update version to v0.4.3-dev<commit_after>package main

import (
	"fmt"
	"github.com/rancher/convoy/api"
	"github.com/rancher/convoy/client"
	"os"
)

const (
	// version of Convoy
	VERSION = "0.4.3-dev"
)

func cleanup() {
	if r := recover(); r != nil {
		api.ResponseLogAndError(r)
		os.Exit(1)
	}
}

func main() {
	defer cleanup()

	cli := client.NewCli(VERSION)
	err := cli.Run(os.Args)
	if err != nil {
		panic(fmt.Errorf("Error when executing command: %v", err))
	}
}
<|endoftext|>


<commit_before>// Package main defines a command line interface for the sqlboiler package
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/kat-co/vala"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var (
	cmdState  *State
	cmdConfig *Config
)

func main() {
	var err error

	viper.SetConfigName("sqlboiler")

	configHome := os.Getenv("XDG_CONFIG_HOME")
	homePath := os.Getenv("HOME")
	wd, err := os.Getwd()
	if err != nil {
		wd = "./"
	}

	configPaths := []string{wd}
	if len(configHome) > 0 {
		configPaths = append(configPaths, filepath.Join(configHome, "sqlboiler"))
	} else {
		configPaths = append(configPaths, filepath.Join(homePath, ".config/sqlboiler"))
	}

	for _, p := range configPaths {
		viper.AddConfigPath(p)
	}

	// Find and read config, ignore errors because we'll fall back to defaults
	// and other validation mechanisms
	_ = viper.ReadInConfig()

	// Set up the cobra root command
	var rootCmd = &cobra.Command{
		Use:   "sqlboiler [flags] <driver>",
		Short: "SQL Boiler generates boilerplate structs and statements",
		Long: "SQL Boiler generates boilerplate structs and statements from template files.\n" +
			`Complete documentation is available at http://github.com/nullbio/sqlboiler`,
		Example:       `sqlboiler -o models -p models postgres`,
		PreRunE:       preRun,
		RunE:          run,
		PostRunE:      postRun,
		SilenceErrors: true,
		SilenceUsage:  true,
	}

	// Set up the cobra root command flags
	rootCmd.PersistentFlags().StringSliceP("tables", "t", nil, "Tables to generate models for, all tables if empty")
	rootCmd.PersistentFlags().StringP("output", "o", "models", "The name of the folder to output to")
	rootCmd.PersistentFlags().StringP("pkgname", "p", "models", "The name you wish to assign to your generated package")

	viper.SetDefault("postgres.ssl_mode", "required")
	viper.BindPFlags(rootCmd.PersistentFlags())

	if err := rootCmd.Execute(); err != nil {
		if e, ok := err.(commandFailure); ok {
			rootCmd.Help()
			fmt.Printf("\n%s\n", string(e))
			return
		}

		fmt.Printf("\n%+v\n", err)
		os.Exit(1)
	}
}

type commandFailure string

func (c commandFailure) Error() string {
	return string(c)
}

func preRun(cmd *cobra.Command, args []string) error {
	var err error

	if len(args) == 0 {
		return commandFailure("must provide a driver name")
	}

	cmdConfig = &Config{
		DriverName: args[0],
		OutFolder:  viper.GetString("output"),
		PkgName:    viper.GetString("pkgname"),
	}

	// BUG: https://github.com/spf13/viper/issues/200
	// Look up the value of TableNames directly from PFlags in Cobra if we
	// detect a malformed value coming out of viper.
	// Once the bug is fixed we'll be able to move this into the init above
	cmdConfig.TableNames = viper.GetStringSlice("tables")
	if len(cmdConfig.TableNames) == 1 && strings.HasPrefix(cmdConfig.TableNames[0], "[") {
		cmdConfig.TableNames, err = cmd.PersistentFlags().GetStringSlice("tables")
		if err != nil {
			return err
		}
	}

	if viper.IsSet("postgres.dbname") {
		cmdConfig.Postgres = PostgresConfig{
			User:    viper.GetString("postgres.user"),
			Pass:    viper.GetString("postgres.pass"),
			Host:    viper.GetString("postgres.host"),
			Port:    viper.GetInt("postgres.port"),
			DBName:  viper.GetString("postgres.dbname"),
			SSLMode: viper.GetString("postgres.sslmode"),
		}

		// Set the default SSLMode value
		if cmdConfig.Postgres.SSLMode == "" {
			viper.Set("postgres.sslmode", "require")
			cmdConfig.Postgres.SSLMode = viper.GetString("postgres.sslmode")
		}

		err = vala.BeginValidation().Validate(
			vala.StringNotEmpty(cmdConfig.Postgres.User, "postgres.user"),
			vala.StringNotEmpty(cmdConfig.Postgres.Pass, "postgres.pass"),
			vala.StringNotEmpty(cmdConfig.Postgres.Host, "postgres.host"),
			vala.Not(vala.Equals(cmdConfig.Postgres.Port, 0, "postgres.port")),
			vala.StringNotEmpty(cmdConfig.Postgres.DBName, "postgres.dbname"),
			vala.StringNotEmpty(cmdConfig.Postgres.SSLMode, "postgres.sslmode"),
		).Check()

		if err != nil {
			return commandFailure(err.Error())
		}
	}

	cmdState, err = New(cmdConfig)
	return err
}

func run(cmd *cobra.Command, args []string) error {
	return cmdState.Run(true)
}

func postRun(cmd *cobra.Command, args []string) error {
	return cmdState.Cleanup()
}
<commit_msg>Cobra package update broke something<commit_after>// Package main defines a command line interface for the sqlboiler package
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/kat-co/vala"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var (
	cmdState  *State
	cmdConfig *Config
)

func main() {
	var err error

	viper.SetConfigName("sqlboiler")

	configHome := os.Getenv("XDG_CONFIG_HOME")
	homePath := os.Getenv("HOME")
	wd, err := os.Getwd()
	if err != nil {
		wd = "./"
	}

	configPaths := []string{wd}
	if len(configHome) > 0 {
		configPaths = append(configPaths, filepath.Join(configHome, "sqlboiler"))
	} else {
		configPaths = append(configPaths, filepath.Join(homePath, ".config/sqlboiler"))
	}

	for _, p := range configPaths {
		viper.AddConfigPath(p)
	}

	// Find and read config, ignore errors because we'll fall back to defaults
	// and other validation mechanisms
	_ = viper.ReadInConfig()

	// Set up the cobra root command
	var rootCmd = &cobra.Command{
		Use:   "sqlboiler [flags] <driver>",
		Short: "SQL Boiler generates boilerplate structs and statements",
		Long: "SQL Boiler generates boilerplate structs and statements from template files.\n" +
			`Complete documentation is available at http://github.com/nullbio/sqlboiler`,
		Example:       `sqlboiler -o models -p models postgres`,
		PreRunE:       preRun,
		RunE:          run,
		PostRunE:      postRun,
		SilenceErrors: true,
		SilenceUsage:  true,
	}

	// Set up the cobra root command flags
	rootCmd.PersistentFlags().StringSliceP("tables", "t", nil, "Tables to generate models for, all tables if empty")
	rootCmd.PersistentFlags().StringP("output", "o", "models", "The name of the folder to output to")
	rootCmd.PersistentFlags().StringP("pkgname", "p", "models", "The name you wish to assign to your generated package")

	viper.SetDefault("postgres.ssl_mode", "required")
	viper.BindPFlags(rootCmd.PersistentFlags())

	if err := rootCmd.Execute(); err != nil {
		if e, ok := err.(commandFailure); ok {
			rootCmd.HelpFunc()
			fmt.Printf("\n%s\n", string(e))
			return
		}

		fmt.Printf("\n%+v\n", err)
		os.Exit(1)
	}
}

type commandFailure string

func (c commandFailure) Error() string {
	return string(c)
}

func preRun(cmd *cobra.Command, args []string) error {
	var err error

	if len(args) == 0 {
		return commandFailure("must provide a driver name")
	}

	cmdConfig = &Config{
		DriverName: args[0],
		OutFolder:  viper.GetString("output"),
		PkgName:    viper.GetString("pkgname"),
	}

	// BUG: https://github.com/spf13/viper/issues/200
	// Look up the value of TableNames directly from PFlags in Cobra if we
	// detect a malformed value coming out of viper.
	// Once the bug is fixed we'll be able to move this into the init above
	cmdConfig.TableNames = viper.GetStringSlice("tables")
	if len(cmdConfig.TableNames) == 1 && strings.HasPrefix(cmdConfig.TableNames[0], "[") {
		cmdConfig.TableNames, err = cmd.PersistentFlags().GetStringSlice("tables")
		if err != nil {
			return err
		}
	}

	if viper.IsSet("postgres.dbname") {
		cmdConfig.Postgres = PostgresConfig{
			User:    viper.GetString("postgres.user"),
			Pass:    viper.GetString("postgres.pass"),
			Host:    viper.GetString("postgres.host"),
			Port:    viper.GetInt("postgres.port"),
			DBName:  viper.GetString("postgres.dbname"),
			SSLMode: viper.GetString("postgres.sslmode"),
		}

		// Set the default SSLMode value
		if cmdConfig.Postgres.SSLMode == "" {
			viper.Set("postgres.sslmode", "require")
			cmdConfig.Postgres.SSLMode = viper.GetString("postgres.sslmode")
		}

		err = vala.BeginValidation().Validate(
			vala.StringNotEmpty(cmdConfig.Postgres.User, "postgres.user"),
			vala.StringNotEmpty(cmdConfig.Postgres.Pass, "postgres.pass"),
			vala.StringNotEmpty(cmdConfig.Postgres.Host, "postgres.host"),
			vala.Not(vala.Equals(cmdConfig.Postgres.Port, 0, "postgres.port")),
			vala.StringNotEmpty(cmdConfig.Postgres.DBName, "postgres.dbname"),
			vala.StringNotEmpty(cmdConfig.Postgres.SSLMode, "postgres.sslmode"),
		).Check()

		if err != nil {
			return commandFailure(err.Error())
		}
	}

	cmdState, err = New(cmdConfig)
	return err
}

func run(cmd *cobra.Command, args []string) error {
	return cmdState.Run(true)
}

func postRun(cmd *cobra.Command, args []string) error {
	return cmdState.Cleanup()
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"log"
	"math/big"
	"os"
	"time"
)

// view remote certificate
// echo |openssl s_client -connect host:443 2>/dev/null | openssl x509 -text
// view and test certificates localy
// openssl x509 -in ca.pem -text
// openssl verify -verbose -CAfile ca.pem client.pem
func main() {
	ca := createCertificateTemplate(true, []byte{1, 2, 3, 4, 5, 6}, []string{}, "SE", "test", "WebCA", "")

	caPriv, _ := rsa.GenerateKey(rand.Reader, 1024) // use small key so generation is fast
	caPub := &caPriv.PublicKey
	writePrivateKeyToPemFile(caPriv, "ca_private_key.pem")
	writePublicKeyToPemFile(caPub, "ca_public_key.pem")
	caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, caPub, caPriv)
	if err != nil {
		log.Println("create ca failed", err)
		return
	}
	writePemToFile(caBytes, "ca.pem")

	client := createCertificateTemplate(false, []byte{1, 6}, []string{"www.foo.se", "www.bar.se"}, "SE", "test", "web", "www.baz.se")
	clientPriv, _ := rsa.GenerateKey(rand.Reader, 1024)
	clientPub := &clientPriv.PublicKey
	writePrivateKeyToPemFile(clientPriv, "client_private_key.pem")
	writePublicKeyToPemFile(clientPub, "client_public_key.pem")
	clientBytes, err := x509.CreateCertificate(rand.Reader, client, ca, clientPub, caPriv)
	if err != nil {
		log.Println("create client failed", err)
		return
	}
	writePemToFile(clientBytes, "client.pem")

}

func createCertificateTemplate(ca bool, subjectKey []byte, dnsName []string, country, org, orgUnit, cn string) *x509.Certificate {
	extKeyUsage := getExtKeyUsage(ca)
	keyUsage := getKeyUsage(ca)

	cert := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			Country:            []string{country},
			Organization:       []string{org},
			OrganizationalUnit: []string{orgUnit},
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().AddDate(1, 0, 0),
		SubjectKeyId:          subjectKey,
		BasicConstraintsValid: true,
		IsCA:        ca,
		ExtKeyUsage: extKeyUsage,
		KeyUsage:    keyUsage,
	}

	if !ca {
		cert.Subject.CommonName = cn
		cert.DNSNames = dnsName
	}
	return cert
}

func getKeyUsage(ca bool) x509.KeyUsage {
	if ca {
		return x509.KeyUsageCRLSign | x509.KeyUsageCertSign
	}
	return x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature
}

func getExtKeyUsage(ca bool) []x509.ExtKeyUsage {
	if ca {
		return []x509.ExtKeyUsage{}
	}
	return []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
}

func writePrivateKeyToPemFile(key *rsa.PrivateKey, fileName string) {
	keyFile, err := os.Create(fileName)
	defer keyFile.Close()
	if err != nil {
		log.Fatalf("Failed to open %s for writing private key: %s\n", fileName, err)
	}
	pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	log.Printf("wrote private key %s to file\n", fileName)
}

func writePublicKeyToPemFile(key *rsa.PublicKey, fileName string) {
	keyFile, err := os.Create(fileName)
	defer keyFile.Close()
	if err != nil {
		log.Fatalf("Failed to open %s for writing public key: %s\n", fileName, err)
	}
	pubKey, _ := x509.MarshalPKIXPublicKey(key)
	pem.Encode(keyFile, &pem.Block{Type: "RSA PUBLIC KEY", Bytes: pubKey})
	log.Printf("wrote public key %s to file\n", fileName)
}

func writePemToFile(b []byte, fileName string) {
	certFile, err := os.Create(fileName)
	defer certFile.Close()
	if err != nil {
		log.Fatalf("Failed to open %s for writing cerificate: %s\n", fileName, err)
	}
	pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: b})
	log.Printf("wrote certificate %s to file\n", fileName)
}
<commit_msg>added intermediate ca so ca->inter->client, also check that client can be verified<commit_after>package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"log"
	"math/big"
	"os"
	"time"
)

// view remote certificate
// echo |openssl s_client -connect host:443 2>/dev/null | openssl x509 -text
// view and test certificates localy
// openssl x509 -in ca.pem -text
// openssl verify -verbose -CAfile ca.pem client.pem
func main() {
	ca := createCertificateTemplate(true, []byte{1, 2, 3, 4, 5, 6}, []string{}, "SE", "test", "WebCA", "")

	caPriv, _ := rsa.GenerateKey(rand.Reader, 1024) // use small key so generation is fast
	caPub := &caPriv.PublicKey
	writePrivateKeyToPemFile(caPriv, "ca_private_key.pem")
	writePublicKeyToPemFile(caPub, "ca_public_key.pem")
	caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, caPub, caPriv)
	if err != nil {
		log.Println("create ca failed", err)
		return
	}
	writePemToFile(caBytes, "ca.pem")
	// test to use a certificate that is not allowed to sign as a sign certificate, checkCertificate must fail
	//interCa := createCertificateTemplate(false, []byte{1, 2, 6}, []string{}, "SE", "test", "webInterCA", "")
	interCa := createCertificateTemplate(true, []byte{1, 2, 6}, []string{}, "SE", "test", "webInterCA", "")
	interCaPriv, _ := rsa.GenerateKey(rand.Reader, 1024)
	interCaPub := &interCaPriv.PublicKey
	writePrivateKeyToPemFile(interCaPriv, "interCa_private_key.pem")
	writePublicKeyToPemFile(interCaPub, "interCa_public_key.pem")
	interCaBytes, err := x509.CreateCertificate(rand.Reader, interCa, ca, interCaPub, caPriv)
	if err != nil {
		log.Println("create interCa failed", err)
		return
	}
	writePemToFile(interCaBytes, "interCa.pem")

	client := createCertificateTemplate(false, []byte{1, 6}, []string{"www.foo.se", "www.bar.se"}, "SE", "test", "web", "www.baz.se")
	clientPriv, _ := rsa.GenerateKey(rand.Reader, 1024)
	clientPub := &clientPriv.PublicKey
	writePrivateKeyToPemFile(clientPriv, "client_private_key.pem")
	writePublicKeyToPemFile(clientPub, "client_public_key.pem")
	clientBytes, err := x509.CreateCertificate(rand.Reader, client, interCa, clientPub, interCaPriv)
	if err != nil {
		log.Println("create client failed", err)
		return
	}
	writePemToFile(clientBytes, "client.pem")
	checkCertificate(caBytes, interCaBytes, clientBytes)
}

func createCertificateTemplate(ca bool, subjectKey []byte, dnsName []string, country, org, orgUnit, cn string) *x509.Certificate {
	extKeyUsage := getExtKeyUsage(ca)
	keyUsage := getKeyUsage(ca)

	cert := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			Country:            []string{country},
			Organization:       []string{org},
			OrganizationalUnit: []string{orgUnit},
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().AddDate(1, 0, 0),
		SubjectKeyId:          subjectKey,
		BasicConstraintsValid: true,
		SignatureAlgorithm:    x509.SHA256WithRSA,
		IsCA:                  ca,
		ExtKeyUsage:           extKeyUsage,
		KeyUsage:              keyUsage,
	}

	if !ca {
		cert.Subject.CommonName = cn
		cert.DNSNames = dnsName
	}
	return cert
}

func checkCertificate(caBytes, interCaBytes, clientBytes []byte) {
	rootPool := x509.NewCertPool()
	rootCert, _ := x509.ParseCertificate(caBytes)
	rootPool.AddCert(rootCert)
	interCaPool := x509.NewCertPool()
	interCerts, _ := x509.ParseCertificates(interCaBytes)
	for _, cert := range interCerts {
		interCaPool.AddCert(cert)
	}
	opts := x509.VerifyOptions{Roots: rootPool, Intermediates: interCaPool}
	clientCert, _ := x509.ParseCertificate(clientBytes)
	_, certErr := clientCert.Verify(opts)
	if certErr != nil {
		log.Println(certErr)
		os.Exit(1)
	}
	log.Println("Certificates verify: OK")
}
func getKeyUsage(ca bool) x509.KeyUsage {
	if ca {
		return x509.KeyUsageCRLSign | x509.KeyUsageCertSign
	}
	return x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature
}

func getExtKeyUsage(ca bool) []x509.ExtKeyUsage {
	if ca {
		return []x509.ExtKeyUsage{}
	}
	return []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
}

func writePrivateKeyToPemFile(key *rsa.PrivateKey, fileName string) {
	keyFile, err := os.Create(fileName)
	defer keyFile.Close()
	if err != nil {
		log.Fatalf("Failed to open %s for writing private key: %s\n", fileName, err)
	}
	pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	log.Printf("wrote private key %s to file\n", fileName)
}

func writePublicKeyToPemFile(key *rsa.PublicKey, fileName string) {
	keyFile, err := os.Create(fileName)
	defer keyFile.Close()
	if err != nil {
		log.Fatalf("Failed to open %s for writing public key: %s\n", fileName, err)
	}
	pubKey, _ := x509.MarshalPKIXPublicKey(key)
	pem.Encode(keyFile, &pem.Block{Type: "RSA PUBLIC KEY", Bytes: pubKey})
	log.Printf("wrote public key %s to file\n", fileName)
}

func writePemToFile(b []byte, fileName string) {
	certFile, err := os.Create(fileName)
	defer certFile.Close()
	if err != nil {
		log.Fatalf("Failed to open %s for writing cerificate: %s\n", fileName, err)
	}
	pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: b})
	log.Printf("wrote certificate %s to file\n", fileName)
}
<|endoftext|>


<commit_before>package main

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

	"github.com/boltdb/bolt"
)

var (
	port = flag.Int("port", 8080, "port to run on")
	db   = flag.String("db", "bolt.db", "bolt db file")
)

func main() {
	flag.Parse()
	db, err := bolt.Open(*db, 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	s := &server{db}
	log.Println("server start")
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), s))
}

type server struct {
	db *bolt.DB
}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hello world")
}
<commit_msg>add unimplemented handlers<commit_after>package main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/boltdb/bolt"
)

const (
	idKey        = "_id"
	createdKey   = "_created"
	updatedKey   = "_updated"
	defaultLimit = 10
)

var (
	port = flag.Int("port", 8080, "port to run on")
	db   = flag.String("db", "bolt.db", "bolt db file")

	invalidPath = errors.New("invalid path")
	nowFunc     = time.Now
)

func main() {
	flag.Parse()
	db, err := bolt.Open(*db, 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	s := &server{db}
	log.Println("server start")
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), s))
}

type server struct {
	db *bolt.DB
}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")

	// TODO: user ID namespacing / auth

	kind, id, err := getKindAndID(r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	var resp map[string]interface{}
	errCode := http.StatusOK
	if id == int64(0) {
		switch r.Method {
		case "POST":
			resp, errCode = s.insert(kind, r.Body)
			r.Body.Close()
		case "GET":
			uq, err := newUserQuery(r)
			if err != nil {
				http.Error(w, "Bad Request", http.StatusBadRequest)
				return
			}
			resp, errCode = s.list(kind, *uq)
		default:
			http.Error(w, "Unsupported Method", http.StatusMethodNotAllowed)
			return
		}
	} else {
		switch r.Method {
		case "GET":
			resp, errCode = s.get(kind, id)
		case "DELETE":
			errCode = s.delete2(kind, id)
		case "POST":
			// This is strictly "replace all properties/values", not "add new properties, update existing"
			resp, errCode = s.update(kind, id, r.Body)
			r.Body.Close()
		default:
			http.Error(w, "Unsupported Method", http.StatusMethodNotAllowed)
			return
		}
	}
	if errCode != http.StatusOK {
		http.Error(w, "", errCode)
		return
	}
	if resp != nil && len(resp) != 0 {
		if err := json.NewEncoder(w).Encode(&resp); err != nil {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
	}
	w.Header().Add("Content-Type", "application/json")
}

// getKindAndID parses the kind and ID from a request path.
func getKindAndID(path string) (string, int64, error) {
	if !strings.HasPrefix(path, "/") || path == "/" {
		return "", int64(0), invalidPath
	}
	parts := strings.Split(path[1:], "/")
	if len(parts) > 2 {
		return "", int64(0), invalidPath
	} else if len(parts) == 1 {
		return parts[0], int64(0), nil
	} else if len(parts) == 2 {
		id, err := strconv.ParseInt(parts[1], 10, 64)
		if err != nil {
			return "", int64(0), err
		}
		return parts[0], id, nil
	}
	return "", int64(0), invalidPath
}

type filter struct {
	Key, Value string
}
type userQuery struct {
	Limit                        int
	StartCursor, EndCursor, Sort string
	Filters                      []filter
}

func newUserQuery(r *http.Request) (*userQuery, error) {
	uq := userQuery{
		StartCursor: r.FormValue("start"),
		EndCursor:   r.FormValue("end"),
		Sort:        r.FormValue("sort"),
	}
	if r.FormValue("limit") != "" {
		lim, err := strconv.Atoi(r.FormValue("limit"))
		if err != nil {
			return nil, err
		}
		uq.Limit = lim
	}

	for _, f := range map[string][]string(r.Form)["where"] {
		parts := strings.Split(f, "=")
		if len(parts) != 2 {
			return nil, errors.New("invalid where: " + f)
		}
		uq.Filters = append(uq.Filters, filter{Key: parts[0], Value: parts[1]})
	}
	return &uq, nil
}

func (s *server) delete2(kind string, id int64) int {
	// TODO: implement
	return http.StatusOK
}

func (s *server) get(kind string, id int64) (map[string]interface{}, int) {
	// TODO: implement
	return nil, http.StatusOK
}

func (s *server) insert(kind string, r io.Reader) (map[string]interface{}, int) {
	m, err := fromJSON(r)
	if err != nil {
		return nil, http.StatusInternalServerError
	}
	m[createdKey] = nowFunc().Unix()

	// TODO: implement
	return m, http.StatusOK
}

func (s *server) list(kind string, uq userQuery) (map[string]interface{}, int) {
	// TODO: implement
	items := make([]map[string]interface{}, 0)
	r := map[string]interface{}{
		"items": items,
	}
	return r, http.StatusOK
}

func (s *server) update(kind string, id int64, r io.Reader) (map[string]interface{}, int) {
	m, err := fromJSON(r)
	if err != nil {
		return nil, http.StatusInternalServerError
	}
	delete(m, createdKey) // Ignore any _created value the user provides
	delete(m, idKey)      // Ignore any _id value the user provides
	m[updatedKey] = nowFunc().Unix()

	// TODO: implement
	return m, http.StatusOK
}

func fromJSON(r io.Reader) (map[string]interface{}, error) {
	var m map[string]interface{}
	err := json.NewDecoder(r).Decode(&m)
	if err != nil {
		fmt.Errorf("decoding json: %v", err)
	}
	return m, err
}
<|endoftext|>


<commit_before>// Package main starts the binary.
// Argument parsing, usage information and the actual execution can be found here.
// See package promplot for using piece directly from you own Go code.
package main

import (
	"flag"
	"fmt"
	"os"
	"runtime"
	"time"

	"qvl.io/promplot/flags"
	"qvl.io/promplot/promplot"
)

// Can be set in build step using -ldflags
var version string

const (
	usage = `
Usage: %s [flags...]

Create and deliver plots from your Prometheus metrics.
Currently only the Slack transport is implemented.

Flags:
`
	more = "\nFor more visit: https://qvl.io/promplot"
)

// Number of data points for the plot
const step = 100

func main() {
	var (
		silent      = flag.Bool("silent", false, "Suppress all output.")
		versionFlag = flag.Bool("version", false, "Print binary version.")
		promServer  = flag.String("url", "", "Required. URL of Prometheus server.")
		query       = flag.String("query", "", "Required. PQL query.")
		queryTime   = flags.UnixTime("time", time.Now(), "Required. Time for query (default is now). Format like the default format of the Unix date command.")
		duration    = flag.Duration("range", 0, "Required. Time to look back to. Format: 12h34m56s.")
		title       = flag.String("title", "Prometheus metrics", "Title of graph.")
		slackToken  = flag.String("slack", "", "Required. Slack API token (https://api.slack.com/docs/oauth-test-tokens).")
		channel     = flag.String("channel", "", "Required. Slack channel to post to.")
	)

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, usage, os.Args[0])
		flag.PrintDefaults()
		fmt.Fprintln(os.Stderr, more)
	}
	flag.Parse()

	if *versionFlag {
		fmt.Printf("promplot %s %s %s\n", version, runtime.GOOS, runtime.GOARCH)
		os.Exit(0)
	}

	// Required flag
	if *promServer == "" || *query == "" || *duration == 0 || *slackToken == "" || *channel == "" {
		flag.Usage()
		os.Exit(1)
	}

	// Loggin helper
	log := func(format string, a ...interface{}) {
		if !*silent {
			fmt.Fprintf(os.Stderr, format, a...)
		}
	}

	// Fetch
	log("Querying Prometheus \"%s\".\n", *query)
	metrics, err := promplot.Metrics(*promServer, *query, queryTime(), *duration, step)
	fatal(err, "failed getting metrics")

	// Plot
	log("Creating plot \"%s\".\n", *title)
	file, err := promplot.Plot(metrics, *title)
	defer cleanup(file)
	fatal(err, "failed creating plot")

	// Upload
	log("Uploading to Slack channel \"%s\".\n", *channel)
	fatal(promplot.Slack(*slackToken, *channel, file, *title), "failed creating plot")

	log("Done.")
}

func cleanup(file string) {
	if file == "" {
		return
	}
	fatal(os.Remove(file), "failed deleting file")
}

func fatal(err error, msg string) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "msg: %v\n", err)
		os.Exit(1)
	}
}
<commit_msg>Improve logging<commit_after>// Package main starts the binary.
// Argument parsing, usage information and the actual execution can be found here.
// See package promplot for using piece directly from you own Go code.
package main

import (
	"flag"
	"fmt"
	"os"
	"runtime"
	"time"

	"qvl.io/promplot/flags"
	"qvl.io/promplot/promplot"
)

// Can be set in build step using -ldflags
var version string

const (
	usage = `
Usage: %s [flags...]

Create and deliver plots from your Prometheus metrics.
Currently only the Slack transport is implemented.

Flags:
`
	more = "\nFor more visit: https://qvl.io/promplot"
)

// Number of data points for the plot
const step = 100

func main() {
	var (
		silent      = flag.Bool("silent", false, "Suppress all output.")
		versionFlag = flag.Bool("version", false, "Print binary version.")
		promServer  = flag.String("url", "", "Required. URL of Prometheus server.")
		query       = flag.String("query", "", "Required. PQL query.")
		queryTime   = flags.UnixTime("time", time.Now(), "Required. Time for query (default is now). Format like the default format of the Unix date command.")
		duration    = flag.Duration("range", 0, "Required. Time to look back to. Format: 12h34m56s.")
		title       = flag.String("title", "Prometheus metrics", "Title of graph.")
		slackToken  = flag.String("slack", "", "Required. Slack API token (https://api.slack.com/docs/oauth-test-tokens).")
		channel     = flag.String("channel", "", "Required. Slack channel to post to.")
	)

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, usage, os.Args[0])
		flag.PrintDefaults()
		fmt.Fprintln(os.Stderr, more)
	}
	flag.Parse()

	if *versionFlag {
		fmt.Printf("promplot %s %s %s\n", version, runtime.GOOS, runtime.GOARCH)
		os.Exit(0)
	}

	// Required flag
	if *promServer == "" || *query == "" || *duration == 0 || *slackToken == "" || *channel == "" {
		flag.Usage()
		os.Exit(1)
	}

	// Loggin helper
	log := func(format string, a ...interface{}) {
		if !*silent {
			fmt.Fprintf(os.Stderr, format+"\n", a...)
		}
	}

	// Fetch
	log("Querying Prometheus \"%s\"", *query)
	metrics, err := promplot.Metrics(*promServer, *query, queryTime(), *duration, step)
	fatal(err, "failed getting metrics")

	// Plot
	log("Creating plot \"%s\"", *title)
	file, err := promplot.Plot(metrics, *title)
	defer cleanup(file)
	fatal(err, "failed creating plot")

	// Upload
	log("Uploading to Slack channel \"%s\"", *channel)
	fatal(promplot.Slack(*slackToken, *channel, file, *title), "failed creating plot")

	log("Done")
}

func cleanup(file string) {
	if file == "" {
		return
	}
	fatal(os.Remove(file), "failed deleting file")
}

func fatal(err error, msg string) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "msg: %v\n", err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/facebookgo/grace/gracehttp"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/techjanitor/pram-get/config"
	c "github.com/techjanitor/pram-get/controllers"
	m "github.com/techjanitor/pram-get/middleware"
	u "github.com/techjanitor/pram-get/utils"
)

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

	// Get start time
	u.InitTime()

	// Set up DB connection
	u.NewDb()

	// Set up Redis connection
	u.NewRedisCache()

	// Get limits and stuff from database
	u.GetDatabaseSettings()

	// Print out config
	config.Print()

	// init the user data worker
	u.UserInit()

	// init the analytics data worker
	m.AnalyticsInit()

	// channel for shutdown
	c := make(chan os.Signal, 10)

	// watch for shutdown signals to shutdown cleanly
	signal.Notify(c, syscall.SIGTERM, os.Interrupt)
	go func() {
		<-c
		Shutdown()
	}()

}

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

	// add CORS headers
	r.Use(m.CORS())
	// validate all route parameters
	r.Use(m.ValidateParams())

	r.GET("/uptime", c.UptimeController)
	r.NoRoute(c.ErrorController)

	// public cached pages
	public := r.Group("/")
	public.Use(m.AntiSpamCookie())
	public.Use(m.Auth(m.SetAuthLevel().All()))
	public.Use(m.Analytics())
	public.Use(m.Cache())

	public.GET("/index/:ib/:page", c.IndexController)
	public.GET("/thread/:ib/:thread/:page", c.ThreadController)
	public.GET("/tag/:ib/:tag/:page", c.TagController)
	public.GET("/image/:ib/:id", c.ImageController)
	public.GET("/post/:ib/:thread/:id", c.PostController)
	public.GET("/tags/:ib", c.TagsController)
	public.GET("/directory/:ib", c.DirectoryController)
	public.GET("/taginfo/:id", c.TagInfoController)
	public.GET("/tagtypes", c.TagTypesController)
	public.GET("/pram", c.PramController)

	// user pages
	users := r.Group("/user")
	users.Use(m.Auth(m.SetAuthLevel().Registered()))

	users.GET("/whoami", c.UserController)
	users.GET("/favorite/:id", c.FavoriteController)
	users.GET("/favorites/:ib/:page", c.FavoritesController)

	s := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", config.Settings.General.Address, config.Settings.General.Port),
		Handler: r,
	}

	gracehttp.Serve(s)

}

// called on sigterm or interrupt
func Shutdown() {

	fmt.Println("Shutting down...")

	// close the database connection
	fmt.Println("Closing database connection")
	err := u.CloseDb()
	if err != nil {
		fmt.Println(err)
	}

}
<commit_msg>goroutine for prepared statement probably not a good idea ;D<commit_after>package main

import (
	"fmt"
	"github.com/facebookgo/grace/gracehttp"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/techjanitor/pram-get/config"
	c "github.com/techjanitor/pram-get/controllers"
	m "github.com/techjanitor/pram-get/middleware"
	u "github.com/techjanitor/pram-get/utils"
)

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

	// Get start time
	u.InitTime()

	// Set up DB connection
	u.NewDb()

	// Set up Redis connection
	u.NewRedisCache()

	// Get limits and stuff from database
	u.GetDatabaseSettings()

	// Print out config
	config.Print()

	// channel for shutdown
	c := make(chan os.Signal, 10)

	// watch for shutdown signals to shutdown cleanly
	signal.Notify(c, syscall.SIGTERM, os.Interrupt)
	go func() {
		<-c
		Shutdown()
	}()

}

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

	// add CORS headers
	r.Use(m.CORS())
	// validate all route parameters
	r.Use(m.ValidateParams())

	r.GET("/uptime", c.UptimeController)
	r.NoRoute(c.ErrorController)

	// public cached pages
	public := r.Group("/")
	public.Use(m.AntiSpamCookie())
	public.Use(m.Auth(m.SetAuthLevel().All()))
	public.Use(m.Analytics())
	public.Use(m.Cache())

	public.GET("/index/:ib/:page", c.IndexController)
	public.GET("/thread/:ib/:thread/:page", c.ThreadController)
	public.GET("/tag/:ib/:tag/:page", c.TagController)
	public.GET("/image/:ib/:id", c.ImageController)
	public.GET("/post/:ib/:thread/:id", c.PostController)
	public.GET("/tags/:ib", c.TagsController)
	public.GET("/directory/:ib", c.DirectoryController)
	public.GET("/taginfo/:id", c.TagInfoController)
	public.GET("/tagtypes", c.TagTypesController)
	public.GET("/pram", c.PramController)

	// user pages
	users := r.Group("/user")
	users.Use(m.Auth(m.SetAuthLevel().Registered()))

	users.GET("/whoami", c.UserController)
	users.GET("/favorite/:id", c.FavoriteController)
	users.GET("/favorites/:ib/:page", c.FavoritesController)

	s := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", config.Settings.General.Address, config.Settings.General.Port),
		Handler: r,
	}

	gracehttp.Serve(s)

}

// called on sigterm or interrupt
func Shutdown() {

	fmt.Println("Shutting down...")

	// close the database connection
	fmt.Println("Closing database connection")
	err := u.CloseDb()
	if err != nil {
		fmt.Println(err)
	}

}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/user"
	"path"

	"github.com/erroneousboat/termui"
	termbox "github.com/nsf/termbox-go"

	"github.com/erroneousboat/slack-term/context"
	"github.com/erroneousboat/slack-term/handlers"
)

const (
	VERSION = "v0.3.1"
	USAGE   = `NAME:
    slack-term - slack client for your terminal

USAGE:
    slack-term -config [path-to-config]

VERSION:
    %s

GLOBAL OPTIONS:
   --help, -h
`
)

var (
	flgConfig string
	flgDebug  bool
	flgUsage  bool
)

func init() {
	// Get home dir for config file default
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	// Parse flags
	flag.StringVar(
		&flgConfig,
		"config",
		path.Join(usr.HomeDir, "slack-term.json"),
		"location of config file",
	)

	flag.BoolVar(
		&flgDebug,
		"debug",
		false,
		"turn on debugging",
	)

	flag.Usage = func() {
		fmt.Printf(USAGE, VERSION)
	}

	flag.Parse()
}

func main() {
	// Start terminal user interface
	err := termui.Init()
	if err != nil {
		log.Fatal(err)
	}
	defer termui.Close()

	// Create custom event stream for termui because
	// termui's one has data race conditions with its
	// event handling. We're circumventing it here until
	// it has been fixed.
	customEvtStream := &termui.EvtStream{
		Handlers: make(map[string]func(termui.Event)),
	}
	termui.DefaultEvtStream = customEvtStream

	// Create context
	ctx, err := context.CreateAppContext(flgConfig, flgDebug)
	if err != nil {
		termbox.Close()
		log.Println(err)
		os.Exit(0)
	}

	// Register handlers
	handlers.RegisterEventHandlers(ctx)

	termui.Loop()
}
<commit_msg>Add website usage overview<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/user"
	"path"

	"github.com/erroneousboat/termui"
	termbox "github.com/nsf/termbox-go"

	"github.com/erroneousboat/slack-term/context"
	"github.com/erroneousboat/slack-term/handlers"
)

const (
	VERSION = "v0.3.1"
	USAGE   = `NAME:
    slack-term - slack client for your terminal

USAGE:
    slack-term -config [path-to-config]

VERSION:
    %s

WEBSITE:
	https://github.com/erroneousboat/slack-term

GLOBAL OPTIONS:
   --help, -h
`
)

var (
	flgConfig string
	flgDebug  bool
	flgUsage  bool
)

func init() {
	// Get home dir for config file default
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	// Parse flags
	flag.StringVar(
		&flgConfig,
		"config",
		path.Join(usr.HomeDir, "slack-term.json"),
		"location of config file",
	)

	flag.BoolVar(
		&flgDebug,
		"debug",
		false,
		"turn on debugging",
	)

	flag.Usage = func() {
		fmt.Printf(USAGE, VERSION)
	}

	flag.Parse()
}

func main() {
	// Start terminal user interface
	err := termui.Init()
	if err != nil {
		log.Fatal(err)
	}
	defer termui.Close()

	// Create custom event stream for termui because
	// termui's one has data race conditions with its
	// event handling. We're circumventing it here until
	// it has been fixed.
	customEvtStream := &termui.EvtStream{
		Handlers: make(map[string]func(termui.Event)),
	}
	termui.DefaultEvtStream = customEvtStream

	// Create context
	ctx, err := context.CreateAppContext(flgConfig, flgDebug)
	if err != nil {
		termbox.Close()
		log.Println(err)
		os.Exit(0)
	}

	// Register handlers
	handlers.RegisterEventHandlers(ctx)

	termui.Loop()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"kubekit/utils"
	"os"

	cli "gopkg.in/urfave/cli.v1"
)

func initialize() {
	//Remove the install log file
	os.Remove("install.log")
	utils.DisplayLogo()
}

func main() {
	initialize()

	app := cli.NewApp()
	app.Name = "KubeKit"
	app.Usage = "A kubernetes toolkit for offline deploying K8S & apps."
	app.Version = "0.1.0"
	app.Action = func(c *cli.Context) error {
		return nil
	}

	app.Commands = []cli.Command{
		{
			Name:    "init",
			Aliases: []string{"i"},
			Usage:   "Initialize current server with Docker engine & Kubernetes master.",
			Action: func(c *cli.Context) error {
				if utils.SetupDocker() {
					utils.SetupMaster()
				}
				return nil
			},
		},
		{
			Name:    "server",
			Aliases: []string{"s"},
			Usage:   "Start kubekit toolkit server.",
			Action: func(c *cli.Context) error {
				fmt.Println("Server is starting...")
				return nil
			},
		},
	}

	app.Run(os.Args)
}
<commit_msg>add todo list<commit_after>package main

import (
	"fmt"
	"kubekit/utils"
	"os"

	"github.com/fatih/color"

	cli "gopkg.in/urfave/cli.v1"
)

func initialize() {
	//Remove the install log file
	os.Remove("install.log")
	utils.DisplayLogo()
}

func main() {
	initialize()

	app := cli.NewApp()
	app.Name = "KubeKit"
	app.Usage = "A kubernetes toolkit for offline deploying K8S & apps."
	app.Version = "0.1.0"
	app.Action = func(c *cli.Context) error {
		return nil
	}

	app.Commands = []cli.Command{
		{
			Name:    "init",
			Aliases: []string{"i"},
			Usage:   "Initialize current server with Docker engine & Kubernetes master.",
			Action: func(c *cli.Context) error {
				if !utils.SetupDocker() {
					color.Red("%sProgram terminated...")
					os.Exit(1)
				}

				if utils.SetupMaster() {
					//1. Get K8S token, save it to .k8s.token file
					//2. Launch toolkit server
				}

				return nil
			},
		},
		{
			Name:    "server",
			Aliases: []string{"s"},
			Usage:   "Start kubekit toolkit server.",
			Action: func(c *cli.Context) error {
				fmt.Println("Server is starting...")
				return nil
			},
		},
	}

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