<commit_before>package toot

import (
	"strings"
)

type Account struct {
	Id             string `json:"id"`
	Username       string `json:"username"`
	Acct           string `json:"acct"`
	DisplayName    string `json:"display_name"`
	Note           string `json:"note"`
	Url            string `json:"url"`
	Avatar         string `json:"avatar"`
	Header         string `json:"header"`
	Locked         bool   `json:"locked"`
	CreatedAt      string `json:"created_at"`
	FollowersCount int    `json:"followers_count"`
	FollowingCount int    `json:"following_count"`
	StatusesCount  int    `json:"statuses_count"`
}

type Scope struct {
	Read   bool
	Write  bool
	Follow bool
}

func (s Scope) String() string {
	scopes := []string{}

	if s.Read {
		scopes = append(scopes, "read")
	}

	if s.Write {
		scopes = append(scopes, "write")
	}

	if s.Follow {
		scopes = append(scopes, "follow")
	}

	return strings.Join(scopes, " ")
}
<commit_msg>Add start of app creation<commit_after>package toot

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"
)

type Account struct {
	Id             string `json:"id"`
	Username       string `json:"username"`
	Acct           string `json:"acct"`
	DisplayName    string `json:"display_name"`
	Note           string `json:"note"`
	Url            string `json:"url"`
	Avatar         string `json:"avatar"`
	Header         string `json:"header"`
	Locked         bool   `json:"locked"`
	CreatedAt      string `json:"created_at"`
	FollowersCount int    `json:"followers_count"`
	FollowingCount int    `json:"following_count"`
	StatusesCount  int    `json:"statuses_count"`
}

type Scope struct {
	Read   bool
	Write  bool
	Follow bool
}

func (s Scope) String() string {
	scopes := []string{}

	if s.Read {
		scopes = append(scopes, "read")
	}

	if s.Write {
		scopes = append(scopes, "write")
	}

	if s.Follow {
		scopes = append(scopes, "follow")
	}

	return strings.Join(scopes, " ")
}

type AppRequest struct {
	ClientName   string `json:"client_name"`
	Scopes       string `json:"scopes"`
	RedirectUris string `json:"redirect_uris"`
}

func NewApp(name string, scope Scope) {
	url := "https://cmpwn.com/api/v1/apps"

	r := AppRequest{
		ClientName:   name,
		Scopes:       scope.String(),
		RedirectUris: "urn:ietf:wg:oauth:2.0:oob",
	}

	jsonStr, _ := json.Marshal(r)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
}
<|endoftext|>


<commit_before>package lib

import (
    "fmt"
    "os"
    "strconv"
    "time"

    . "gopkg.in/check.v1"
)

func (s *OssutilCommandSuite) rawSetBucketACL(bucket, acl string, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, ""), acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, true, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetObjectACL(bucket, object, acl string, recursive, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, object), acl}
    showElapse, err := s.rawSetACLWithArgs(args, recursive, false, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetACLWithArgs(args []string, recursive, bucket, force bool) (bool, error) {
    command := "set-acl"
    str := ""
    routines := strconv.Itoa(Routines)
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &configFile,
        "routines": &routines,
        "recursive": &recursive,
        "bucket": &bucket,
        "force": &force,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    time.Sleep(sleepTime)
    return showElapse, err
}

func (s *OssutilCommandSuite) TestSetBucketACL(c *C) {
    bucket := bucketNameExist

    // set acl
    for _, acl := range []string{"private", "public-read", "public-read-write"} {
        s.setBucketACL(bucket, acl, c)
        s.getStat(bucket, "", c)
    }
}

func (s *OssutilCommandSuite) TestSetBucketErrorACL(c *C) {
    bucket := bucketNameDest

    for _, acl := range []string{"default", "def", "erracl", "私有"} {
        showElapse, err := s.rawSetBucketACL(bucket, acl, false)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        showElapse, err = s.rawSetBucketACL(bucket, acl, true)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        bucketStat := s.getStat(bucket, "", c)
        c.Assert(bucketStat[StatACL], Equals, "private")
    }
}

func (s *OssutilCommandSuite) TestSetNotExistBucketACL(c *C) {
    bucket := bucketNamePrefix + "noexistsetacl"

    // set acl and create bucket
    showElapse, err = s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    s.removeBucket(bucket, true, c)
    time.Sleep(14*time.Second)

    // invalid bucket name
    bucket = "a"
    showElapse, err = s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    showElapse, err = s.rawGetStat(bucket, "")
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestSetBucketEmptyACL(c *C) {
    bucket := bucketNamePrefix + "acl3"
    s.putBucket(bucket, c)
    time.Sleep(7*time.Second)

    object := "test"
    s.putObject(bucket, object, uploadFileName, c)

    showElapse, err := s.rawSetObjectACL(bucket, object, "", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    s.removeBucket(bucket, true, c)
    time.Sleep(7*time.Second)
}

func (s *OssutilCommandSuite) TestSetObjectACL(c *C) {
    bucket := bucketNameSetACL

    object := "TestSetObjectACL"

    // set acl to not exist object
    showElapse, err := s.rawSetObjectACL(bucket, object, "default", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    object = "setacl-oldobject"
    s.putObject(bucket, object, uploadFileName, c)

    //get object acl
    objectStat := s.getStat(bucket, object, c)
    c.Assert(objectStat[StatACL], Equals, "default")

    object = "setacl-newobject"
    s.putObject(bucket, object, uploadFileName, c)

    // set acl
    for _, acl := range []string{"default"} {
        s.setObjectACL(bucket, object, acl, false, true, c)
        objectStat = s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, acl)
    }

    s.setObjectACL(bucket, object, "private", false, true, c)

    // set error acl
    for _, acl := range []string{"public_read", "erracl", "私有"} {
        showElapse, err = s.rawSetObjectACL(bucket, object, acl, false, false)
        c.Assert(showElapse, Equals, false)
        c.Assert(err, NotNil)
    }
}

func (s *OssutilCommandSuite) TestBatchSetObjectACL(c *C) {
    bucket := bucketNameSetACL1

    // put objects
    num := 2
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestBatchSetObjectACL_setacl%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }
    time.Sleep(time.Second)

    for _, object := range objectNames {
        s.getStat(bucket, object, c)
    }

    // without --force option
    s.setObjectACL(bucket, "", "public-read-write", true, false, c)

    for _, object := range objectNames {
        s.getStat(bucket, object, c)
    }

    for _, acl := range []string{"public-read"} {
        s.setObjectACL(bucket, "TestBatchSetObjectACL_setacl", acl, true, true, c)
        time.Sleep(sleepTime)

        for _, object := range objectNames {
            objectStat := s.getStat(bucket, object, c)
            c.Assert(objectStat[StatACL], Equals, acl)
        }
    }

    showElapse, err := s.rawSetObjectACL(bucket, "TestBatchSetObjectACL_setacl", "erracl", true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrSetACL(c *C) {
    acl := "private"
    args := []string{"os://", acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{"oss://", acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)

    // error set bucket acl
    bucket := bucketNamePrefix + "set-acl"
    object := "testobject"
    args = []string{CloudURLToString(bucket, object), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, true, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss acl
    args = []string{CloudURLToString(bucket, "")}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, true, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss object
    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // bad prefix
    showElapse, err = s.rawSetObjectACL(bucket, "/object", acl, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrBatchSetACL(c *C) {
    bucket := bucketNameExist

    // put objects
    num := 10
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestErrBatchSetACL_setacl:%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }

    command := "set-acl"
    str := ""
    str1 := "abc"
    args := []string{CloudURLToString(bucket, ""), "public-read-write"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str1,
        "accessKeyID": &str1,
        "accessKeySecret": &str1,
        "stsToken": &str,
        "routines": &routines,
        "recursive": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }
}

func (s *OssutilCommandSuite) TestSetACLIDKey(c *C) {
    bucket := bucketNameExist

    cfile := "ossutil_test.config_boto"
    data := fmt.Sprintf("[Credentials]\nendpoint=%s\naccessKeyID=%s\naccessKeySecret=%s\n[Bucket-Endpoint]\n%s=%s[Bucket-Cname]\n%s=%s", "abc", "def", "ghi", bucket, "abc", bucket, "abc")
    s.createFile(cfile, data, c)

    command := "set-acl"
    str := ""
    args := []string{CloudURLToString(bucket, ""), "public-read"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)

    options = OptionMapType{
        "endpoint": &endpoint,
        "accessKeyID": &accessKeyID,
        "accessKeySecret": &accessKeySecret,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err = cm.RunCommand(command, args, options)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    _ = os.Remove(cfile)
}
<commit_msg>modify case<commit_after>package lib

import (
    "fmt"
    "os"
    "strconv"
    "time"

    . "gopkg.in/check.v1"
)

func (s *OssutilCommandSuite) rawSetBucketACL(bucket, acl string, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, ""), acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, true, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetObjectACL(bucket, object, acl string, recursive, force bool) (bool, error) {
    args := []string{CloudURLToString(bucket, object), acl}
    showElapse, err := s.rawSetACLWithArgs(args, recursive, false, force)
    return showElapse, err
}

func (s *OssutilCommandSuite) rawSetACLWithArgs(args []string, recursive, bucket, force bool) (bool, error) {
    command := "set-acl"
    str := ""
    routines := strconv.Itoa(Routines)
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &configFile,
        "routines": &routines,
        "recursive": &recursive,
        "bucket": &bucket,
        "force": &force,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    time.Sleep(sleepTime)
    return showElapse, err
}

func (s *OssutilCommandSuite) TestSetBucketACL(c *C) {
    bucket := bucketNameExist

    // set acl
    for _, acl := range []string{"private", "public-read", "public-read-write"} {
        s.setBucketACL(bucket, acl, c)
        s.getStat(bucket, "", c)
    }
}

func (s *OssutilCommandSuite) TestSetBucketErrorACL(c *C) {
    bucket := bucketNameDest

    for _, acl := range []string{"default", "def", "erracl", "私有"} {
        showElapse, err := s.rawSetBucketACL(bucket, acl, false)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        showElapse, err = s.rawSetBucketACL(bucket, acl, true)
        c.Assert(err, NotNil)
        c.Assert(showElapse, Equals, false)

        bucketStat := s.getStat(bucket, "", c)
        c.Assert(bucketStat[StatACL], Equals, "private")
    }
}

func (s *OssutilCommandSuite) TestSetNotExistBucketACL(c *C) {
    bucket := bucketNamePrefix + "noexistsetacl"

    // set acl and create bucket
    showElapse, err := s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    s.removeBucket(bucket, true, c)
    time.Sleep(14*time.Second)

    // invalid bucket name
    bucket = "a"
    showElapse, err = s.rawSetBucketACL(bucket, "public-read", true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    showElapse, err = s.rawGetStat(bucket, "")
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestSetBucketEmptyACL(c *C) {
    bucket := bucketNamePrefix + "acl3"
    s.putBucket(bucket, c)
    time.Sleep(7*time.Second)

    object := "test"
    s.putObject(bucket, object, uploadFileName, c)

    showElapse, err := s.rawSetObjectACL(bucket, object, "", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    s.removeBucket(bucket, true, c)
    time.Sleep(7*time.Second)
}

func (s *OssutilCommandSuite) TestSetObjectACL(c *C) {
    bucket := bucketNameSetACL

    object := "TestSetObjectACL"

    // set acl to not exist object
    showElapse, err := s.rawSetObjectACL(bucket, object, "default", false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    object = "setacl-oldobject"
    s.putObject(bucket, object, uploadFileName, c)

    //get object acl
    objectStat := s.getStat(bucket, object, c)
    c.Assert(objectStat[StatACL], Equals, "default")

    object = "setacl-newobject"
    s.putObject(bucket, object, uploadFileName, c)

    // set acl
    for _, acl := range []string{"default"} {
        s.setObjectACL(bucket, object, acl, false, true, c)
        objectStat = s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, acl)
    }

    s.setObjectACL(bucket, object, "private", false, true, c)

    // set error acl
    for _, acl := range []string{"public_read", "erracl", "私有"} {
        showElapse, err = s.rawSetObjectACL(bucket, object, acl, false, false)
        c.Assert(showElapse, Equals, false)
        c.Assert(err, NotNil)
    }
}

func (s *OssutilCommandSuite) TestBatchSetObjectACL(c *C) {
    bucket := bucketNameSetACL1

    // put objects
    num := 2
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestBatchSetObjectACL_setacl%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }
    time.Sleep(time.Second)

    for _, object := range objectNames {
        s.getStat(bucket, object, c)
    }

    // without --force option
    s.setObjectACL(bucket, "", "public-read-write", true, false, c)

    for _, object := range objectNames {
        s.getStat(bucket, object, c)
    }

    for _, acl := range []string{"public-read"} {
        s.setObjectACL(bucket, "TestBatchSetObjectACL_setacl", acl, true, true, c)
        time.Sleep(sleepTime)

        for _, object := range objectNames {
            objectStat := s.getStat(bucket, object, c)
            c.Assert(objectStat[StatACL], Equals, acl)
        }
    }

    showElapse, err := s.rawSetObjectACL(bucket, "TestBatchSetObjectACL_setacl", "erracl", true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrSetACL(c *C) {
    acl := "private"
    args := []string{"os://", acl}
    showElapse, err := s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{"oss://", acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)

    // error set bucket acl
    bucket := bucketNamePrefix + "set-acl"
    object := "testobject"
    args = []string{CloudURLToString(bucket, object), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, true, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss acl
    args = []string{CloudURLToString(bucket, "")}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, false, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    args = []string{CloudURLToString(bucket, object)}
    showElapse, err = s.rawSetACLWithArgs(args, true, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // miss object
    args = []string{CloudURLToString(bucket, ""), acl}
    showElapse, err = s.rawSetACLWithArgs(args, false, false, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    // bad prefix
    showElapse, err = s.rawSetObjectACL(bucket, "/object", acl, true, true)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)
}

func (s *OssutilCommandSuite) TestErrBatchSetACL(c *C) {
    bucket := bucketNameExist

    // put objects
    num := 10
    objectNames := []string{}
    for i := 0; i < num; i++ {
        object := fmt.Sprintf("TestErrBatchSetACL_setacl:%d", i)
        s.putObject(bucket, object, uploadFileName, c)
        objectNames = append(objectNames, object)
    }

    command := "set-acl"
    str := ""
    str1 := "abc"
    args := []string{CloudURLToString(bucket, ""), "public-read-write"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str1,
        "accessKeyID": &str1,
        "accessKeySecret": &str1,
        "stsToken": &str,
        "routines": &routines,
        "recursive": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)
    c.Assert(showElapse, Equals, false)

    for _, object := range objectNames {
        objectStat := s.getStat(bucket, object, c)
        c.Assert(objectStat[StatACL], Equals, "default")
    }
}

func (s *OssutilCommandSuite) TestSetACLIDKey(c *C) {
    bucket := bucketNameExist

    cfile := "ossutil_test.config_boto"
    data := fmt.Sprintf("[Credentials]\nendpoint=%s\naccessKeyID=%s\naccessKeySecret=%s\n[Bucket-Endpoint]\n%s=%s[Bucket-Cname]\n%s=%s", "abc", "def", "ghi", bucket, "abc", bucket, "abc")
    s.createFile(cfile, data, c)

    command := "set-acl"
    str := ""
    args := []string{CloudURLToString(bucket, ""), "public-read"}
    routines := strconv.Itoa(Routines)
    ok := true
    options := OptionMapType{
        "endpoint": &str,
        "accessKeyID": &str,
        "accessKeySecret": &str,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err := cm.RunCommand(command, args, options)
    c.Assert(err, NotNil)

    options = OptionMapType{
        "endpoint": &endpoint,
        "accessKeyID": &accessKeyID,
        "accessKeySecret": &accessKeySecret,
        "stsToken": &str,
        "configFile": &cfile,
        "routines": &routines,
        "bucket": &ok,
        "force": &ok,
    }
    showElapse, err = cm.RunCommand(command, args, options)
    c.Assert(err, IsNil)
    c.Assert(showElapse, Equals, true)

    _ = os.Remove(cfile)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/IngCr3at1on/ccgen/params"

	"github.com/btcsuite/btcd/btcec"
	"github.com/btcsuite/btcd/chaincfg"
	"github.com/btcsuite/btcutil"
	"github.com/codegangsta/cli"
)

var app *cli.App

func init() {
	app = cli.NewApp()
	app.Name = "ccgen"
	app.Usage = "Cryptocoin address generator"
	app.Version = "0.0.1"

	var ctype string

	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:        "coin, c",
			Value:       "bitcoin",
			Usage:       "Define coin-type to generate an address for",
			Destination: &ctype,
		},
	}

	app.Action = func(c *cli.Context) {
		priv, err := btcec.NewPrivateKey(btcec.S256())
		if err != nil {
			fmt.Println(err)
			return
		}

		var p *chaincfg.Params
		switch {
		case strings.ToLower(ctype) == "bitcoin" || strings.ToLower(ctype) == "btc":
			p = &chaincfg.MainNetParams
			break
		case strings.ToLower(ctype) == "litedoge" || strings.ToLower(ctype) == "ldoge":
			p = &params.Litedoge
			break
		case strings.ToLower(ctype) == "paycoin" || strings.ToLower(ctype) == "xpy":
			p = &params.Paycoin
			break
		default:
			p = &chaincfg.MainNetParams
			break
		}

		wif, err := btcutil.NewWIF(priv, p, true)
		if err != nil {
			fmt.Println(err)
			return
		}

		fmt.Printf("%s\n", wif.String())

		addr, err := btcutil.NewAddressPubKey(priv.PubKey().SerializeCompressed(), p)
		if err != nil {
			fmt.Println(err)
			return
		}

		fmt.Printf("%s\n", addr.EncodeAddress())
	}
}

func main() {
	app.Run(os.Args)
}
<commit_msg>Make compress optional.<commit_after>package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/IngCr3at1on/ccgen/params"

	"github.com/btcsuite/btcd/btcec"
	"github.com/btcsuite/btcd/chaincfg"
	"github.com/btcsuite/btcutil"
	"github.com/codegangsta/cli"
)

var app *cli.App

func init() {
	app = cli.NewApp()
	app.Name = "ccgen"
	app.Usage = "Cryptocoin address generator"
	app.Version = "0.0.1"

	var ctype string
	var compress bool

	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:        "type, t",
			Value:       "bitcoin",
			Usage:       "Define coin-type to generate an address for",
			Destination: &ctype,
		},
		cli.BoolFlag{
			Name:        "compress, c",
			Usage:       "Compress the private key and address",
			Destination: &compress,
		},
	}

	app.Action = func(c *cli.Context) {
		priv, err := btcec.NewPrivateKey(btcec.S256())
		if err != nil {
			fmt.Println(err)
			return
		}

		var p *chaincfg.Params
		switch {
		case strings.ToLower(ctype) == "bitcoin" || strings.ToLower(ctype) == "btc":
			p = &chaincfg.MainNetParams
			break
		case strings.ToLower(ctype) == "litedoge" || strings.ToLower(ctype) == "ldoge":
			p = &params.Litedoge
			break
		case strings.ToLower(ctype) == "paycoin" || strings.ToLower(ctype) == "xpy":
			p = &params.Paycoin
			break
		default:
			p = &chaincfg.MainNetParams
			break
		}

		wif, err := btcutil.NewWIF(priv, p, compress)
		if err != nil {
			fmt.Println(err)
			return
		}

		fmt.Printf("%s\n", wif.String())

		var spub []byte
		if compress {
			spub = priv.PubKey().SerializeCompressed()
		} else {
			spub = priv.PubKey().SerializeUncompressed()
		}

		addr, err := btcutil.NewAddressPubKey(spub, p)
		if err != nil {
			fmt.Println(err)
			return
		}

		fmt.Printf("%s\n", addr.EncodeAddress())
	}
}

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


<commit_before>package main

import (
	// "fmt"
	"github.com/cloudfoundry/gosteno"
	"github.com/codegangsta/cli"
	"github.com/pivotalservices/cfops/backup"
	. "github.com/pivotalservices/cfops/cli"
	"github.com/pivotalservices/cfops/config"
	// "github.com/pivotalservices/cfops/configuration"
	"github.com/pivotalservices/cfops/install"
	"github.com/pivotalservices/cfops/start"
	"github.com/pivotalservices/cfops/system"
	"os"
	"strings"
)

var (
	logFilePath    = NewFlag("logFile", "", "The CFOPS log file, defaults to STDOUT", "CFOPS_LOG")
	configFilePath = NewFlag("configFile", config.DefaultFilePath(), "Location of the CFOPS config json file", "CFOPS_CONFIG")
	debug          = NewFlag("debug", false, "Debug logging", "CFOPS_TRACE")
	iaas           = NewFlag("iaas, i", "aws, vsphere, vcloud, openstack", "Sets the IaaS type to target for deployment", "CFOPS_IAAS")
	lang           = NewFlag("lang, l", "en, es", "Language for the cfops cli responses", "CFOPS_LANG")
)

type Config struct {
	Name string
	*backup.BackupConfig
}

// To get the base foundation configuration see the Pivotal CF Data Collector @
// https://docs.google.com/a/pivotal.io/spreadsheets/d/1XHKSrJiQIu5MWGpPYWbMY8M09eqe-GV8MQsl_mqw1RM/edit#gid=0
func main() {

	commandFactory := NewCommandFactory()

	commandRunner := &system.OSCommandRunner{}

	start.New(commandFactory)
	install.New(commandFactory)
	backup.New(commandFactory, commandRunner)

	globalFlags := []*Flag{logFilePath, configFilePath, debug, iaas, lang}

	app := NewApp(commandFactory, globalFlags)

	app.Before = func(c *cli.Context) error {
		for _, flag := range globalFlags {
			if flag.Type == "bool" {
				flag.Value = c.Bool(flag.Name)
				// fmt.Printf("BEFORE flag %s has value %v\n", flag.Name, flag.Value)
			} else {
				flag.Value = c.String(flag.Name)
				// fmt.Printf("BEFORE flag %s has value %s\n", flag.Name, flag.Value)
			}
		}
		config := parseConfig(debug.ParseBool(), configFilePath.ParseString())
		backupCommand := commandFactory.FindCommand("backup").(*backup.BackupCommand)
		backupCommand.Config = config.BackupConfig

		logger := NewLogger(debug.ParseBool(), logFilePath.ParseString(), "cfops")
		logger.Info("Setting up CFOPS")

		commandRunner.SetLogger(logger)
		commandFactory.SetLogger(logger)
		return nil
	}

	app.RunAndExitOnError()
}

func parseConfig(debug bool, configFile string) Config {
	configuration := Config{"",
		&backup.BackupConfig{},
	}
	err := config.LoadConfig(&configuration, configFile)
	if err != nil {
		panic(err)
	}
	return configuration
}

func NewLogger(verbose bool, logFilePath, name string) *gosteno.Logger {
	level := gosteno.LOG_INFO

	if verbose {
		level = gosteno.LOG_DEBUG
	}

	loggingConfig := &gosteno.Config{
		Sinks:     make([]gosteno.Sink, 1),
		Level:     level,
		Codec:     gosteno.NewJsonPrettifier(gosteno.EXCLUDE_DATA),
		EnableLOC: true}

	if strings.TrimSpace(logFilePath) == "" {
		loggingConfig.Sinks[0] = gosteno.NewIOSink(os.Stdout)
	} else {
		loggingConfig.Sinks[0] = gosteno.NewFileSink(logFilePath)
	}

	gosteno.Init(loggingConfig)
	logger := gosteno.NewLogger(name)
	logger.Debugf("Component %s in debug mode!", name)
	return logger
}
<commit_msg>Polishing...<commit_after>package main

import (
	// "fmt"
	"github.com/cloudfoundry/gosteno"
	"github.com/codegangsta/cli"
	"github.com/pivotalservices/cfops/backup"
	. "github.com/pivotalservices/cfops/cli"
	"github.com/pivotalservices/cfops/config"
	// "github.com/pivotalservices/cfops/configuration"
	"github.com/pivotalservices/cfops/install"
	"github.com/pivotalservices/cfops/start"
	"github.com/pivotalservices/cfops/system"
	"os"
	"strings"
)

var (
	logFilePath    = NewFlag("logFile", "", "The CFOPS log file, defaults to STDOUT", "CFOPS_LOG")
	configFilePath = NewFlag("configFile", config.DefaultFilePath(), "Location of the CFOPS config json file", "CFOPS_CONFIG")
	debug          = NewFlag("debug", false, "Debug logging", "CFOPS_TRACE")
	iaas           = NewFlag("iaas, i", "aws, vsphere, vcloud, openstack", "Sets the IaaS type to target for deployment", "CFOPS_IAAS")
	lang           = NewFlag("lang, l", "en, es", "Language for the cfops cli responses", "CFOPS_LANG")
)

type Config struct {
	Name string
	*backup.BackupConfig
}

// To get the base foundation configuration see the Pivotal CF Data Collector @
// https://docs.google.com/a/pivotal.io/spreadsheets/d/1XHKSrJiQIu5MWGpPYWbMY8M09eqe-GV8MQsl_mqw1RM/edit#gid=0
func main() {

	commandFactory := NewCommandFactory()

	commandRunner := &system.OSCommandRunner{}

	start.New(commandFactory)
	install.New(commandFactory)
	backup.New(commandFactory, commandRunner)

	globalFlags := []*Flag{logFilePath, configFilePath, debug, iaas, lang}

	app := NewApp(commandFactory, globalFlags)

	app.Before = func(c *cli.Context) error {
		for _, flag := range globalFlags {
			if flag.Type == "bool" {
				flag.Value = c.Bool(flag.Name)
				// fmt.Printf("BEFORE flag %s has value %v\n", flag.Name, flag.Value)
			} else {
				flag.Value = c.String(flag.Name)
				// fmt.Printf("BEFORE flag %s has value %s\n", flag.Name, flag.Value)
			}
		}
		config := parseConfig(debug.ParseBool(), configFilePath.ParseString())
		backupCommand := commandFactory.FindCommand("backup").(*backup.BackupCommand)
		backupCommand.Config = config.BackupConfig

		logger := NewLogger(debug.ParseBool(), logFilePath.ParseString(), "cfops")
		logger.Info("Setting up CFOPS")

		commandRunner.SetLogger(logger)
		commandFactory.SetLogger(logger)
		return nil
	}

	app.RunAndExitOnError()
}

func parseConfig(debug bool, configFile string) Config {
	configuration := Config{}
	err := config.LoadConfig(&configuration, configFile)
	if err != nil {
		panic(err)
	}
	return configuration
}

func NewLogger(verbose bool, logFilePath, name string) *gosteno.Logger {
	level := gosteno.LOG_INFO

	if verbose {
		level = gosteno.LOG_DEBUG
	}

	loggingConfig := &gosteno.Config{
		Sinks:     make([]gosteno.Sink, 1),
		Level:     level,
		Codec:     gosteno.NewJsonPrettifier(gosteno.EXCLUDE_DATA),
		EnableLOC: true}

	if strings.TrimSpace(logFilePath) == "" {
		loggingConfig.Sinks[0] = gosteno.NewIOSink(os.Stdout)
	} else {
		loggingConfig.Sinks[0] = gosteno.NewFileSink(logFilePath)
	}

	gosteno.Init(loggingConfig)
	logger := gosteno.NewLogger(name)
	logger.Debugf("Component %s in debug mode!", name)
	return logger
}
<|endoftext|>


<commit_before>package nagiosplugin

import (
	"fmt"
	"os"
	"strings"
)

const (
	messageSeparator = ", "
)

// Standalone Exit function for simple checks without multiple results
// or perfdata.
func Exit(status Status, message string) {
	fmt.Printf("%v: %s\n", status, message)
	os.Exit(int(status))
}

// Represents the state of a Nagios check.
type Check struct {
	results  []Result
	perfdata []PerfDatum
	status   Status
}

// NewCheck returns an empty Check object.
func NewCheck() *Check {
	c := new(Check)
	return c
}

// AddResult adds a check result. This will not terminate the check. If
// status is the highest yet reported, this will update the check's
// final return status.
func (c *Check) AddResult(status Status, message string) {
	var result Result
	result.status = status
	result.message = message
	c.results = append(c.results, result)
	if result.status > c.status {
		c.status = result.status
	}
}

// AddPerfDatum adds a metric to the set output by the check. unit must
// be a valid Nagios unit of measurement (UOM): "us", "ms", "s",
// "%", "b", "kb", "mb", "gb", "tb", "c", or the empty string. UOMs are
// not case-sensitive.
//
// Zero or more of the thresholds min, max, warn and crit may be
// supplied; these must be of the same UOM as the value.
//
// A threshold may be positive or negative infinity, in which case it
// will be omitted in the check output. A value may not be either
// infinity.
//
// Returns error on invalid parameters.
func (c *Check) AddPerfDatum(label, unit string, value float64, thresholds ...float64) error {
	datum, err := NewPerfDatum(label, unit, value, thresholds...)
	if err != nil {
		return err
	}
	c.perfdata = append(c.perfdata, *datum)
	return nil
}

// exitInfoText returns the most important result text, formatted for
// the first line of plugin output.
//
// Returns joined string of (messageSeparator-separated) info text from
// results which have a status of at least c.status.
func (c Check) exitInfoText() string {
	importantMessages := make([]string, 0)
	for _, result := range c.results {
		if result.status == c.status {
			importantMessages = append(importantMessages, result.message)
		}
	}
	return strings.Join(importantMessages, messageSeparator)
}

// String representation of the check results, suitable for output and
// parsing by Nagios.
func (c Check) String() string {
	value := fmt.Sprintf("%v: %s", c.status, c.exitInfoText())
	value += RenderPerfdata(c.perfdata)
	return value
}

// Finish ends the check, prints its output (to stdout), and exits with
// the correct status.
func (c Check) Finish() {
	if len(c.results) == 0 {
		c.AddResult(UNKNOWN, "no check result specified")
	}
	fmt.Println(c)
	os.Exit(int(c.status))
}

// Exitf takes a status plus a format string, and a list of
// parameters to pass to Sprintf. It then immediately outputs and exits.
func (c *Check) Exitf(status Status, format string, v ...interface{}) {
	info := fmt.Sprintf(format, v...)
	c.AddResult(status, info)
	c.Finish()
}

// Criticalf is a shorthand function which calls Exitf with
// nagiosplugin.CRITICAL and the supplied format string.
func (c *Check) Criticalf(format string, v ...interface{}) {
	c.Exitf(CRITICAL, format, v...)
}
<commit_msg>Finish() should take a Check pointer so calls to it can be deferred<commit_after>package nagiosplugin

import (
	"fmt"
	"os"
	"strings"
)

const (
	messageSeparator = ", "
)

// Standalone Exit function for simple checks without multiple results
// or perfdata.
func Exit(status Status, message string) {
	fmt.Printf("%v: %s\n", status, message)
	os.Exit(int(status))
}

// Represents the state of a Nagios check.
type Check struct {
	results  []Result
	perfdata []PerfDatum
	status   Status
}

// NewCheck returns an empty Check object.
func NewCheck() *Check {
	c := new(Check)
	return c
}

// AddResult adds a check result. This will not terminate the check. If
// status is the highest yet reported, this will update the check's
// final return status.
func (c *Check) AddResult(status Status, message string) {
	var result Result
	result.status = status
	result.message = message
	c.results = append(c.results, result)
	if result.status > c.status {
		c.status = result.status
	}
}

// AddPerfDatum adds a metric to the set output by the check. unit must
// be a valid Nagios unit of measurement (UOM): "us", "ms", "s",
// "%", "b", "kb", "mb", "gb", "tb", "c", or the empty string. UOMs are
// not case-sensitive.
//
// Zero or more of the thresholds min, max, warn and crit may be
// supplied; these must be of the same UOM as the value.
//
// A threshold may be positive or negative infinity, in which case it
// will be omitted in the check output. A value may not be either
// infinity.
//
// Returns error on invalid parameters.
func (c *Check) AddPerfDatum(label, unit string, value float64, thresholds ...float64) error {
	datum, err := NewPerfDatum(label, unit, value, thresholds...)
	if err != nil {
		return err
	}
	c.perfdata = append(c.perfdata, *datum)
	return nil
}

// exitInfoText returns the most important result text, formatted for
// the first line of plugin output.
//
// Returns joined string of (messageSeparator-separated) info text from
// results which have a status of at least c.status.
func (c Check) exitInfoText() string {
	importantMessages := make([]string, 0)
	for _, result := range c.results {
		if result.status == c.status {
			importantMessages = append(importantMessages, result.message)
		}
	}
	return strings.Join(importantMessages, messageSeparator)
}

// String representation of the check results, suitable for output and
// parsing by Nagios.
func (c Check) String() string {
	value := fmt.Sprintf("%v: %s", c.status, c.exitInfoText())
	value += RenderPerfdata(c.perfdata)
	return value
}

// Finish ends the check, prints its output (to stdout), and exits with
// the correct status.
func (c *Check) Finish() {
	if len(c.results) == 0 {
		c.AddResult(UNKNOWN, "no check result specified")
	}
	fmt.Println(c)
	os.Exit(int(c.status))
}

// Exitf takes a status plus a format string, and a list of
// parameters to pass to Sprintf. It then immediately outputs and exits.
func (c *Check) Exitf(status Status, format string, v ...interface{}) {
	info := fmt.Sprintf(format, v...)
	c.AddResult(status, info)
	c.Finish()
}

// Criticalf is a shorthand function which calls Exitf with
// nagiosplugin.CRITICAL and the supplied format string.
func (c *Check) Criticalf(format string, v ...interface{}) {
	c.Exitf(CRITICAL, format, v...)
}
<|endoftext|>


<commit_before>package ci

import (
	"appengine"
	"appengine/urlfetch"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

func init() {
	http.HandleFunc("/", handler)
}

var expected_user_agent string = "Google Code Project Hosting (+http://code.google.com/p/support/wiki/PostCommitWebHooks)"
var repository_path_prefix string = "https://code.google.com/p/m-lab."
var drone_io_prefix string = "https://drone.io/dominic-mlab/m-lab."

func handler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		redirect_map := map[string]string {
			"libraries": "BV8KN727SQ1JMEK7DKIGSO97SLBDJL2O",
			"ns":        "S4MHVE51D5KN5SGK1IOV1TA0SGK21RBF",
			"pipeline":  "6MO0BPE3RKNHJ1EOS3MHE89M71C9JF8M",
		}

		c := appengine.NewContext(r)
		c.Debugf("Request: %#v", r)

		if r.Header["User-Agent"][0] != expected_user_agent {
			c.Errorf("Unexpected user agent: %v", r.Header["User-Agent"])
			http.Error(w, "Unexpected user agent", http.StatusForbidden)
			return
		}

		var b []byte;
		b, err := ioutil.ReadAll(r.Body)
		r.Body.Close()

		if err != nil {
			c.Errorf("Failed to read body: %v", err)
			return
		}
		c.Debugf("Body: %s", string(b))
		var f interface{}
		err = json.Unmarshal(b, &f)
		if err != nil {
			c.Errorf("Failed to unmarshal body: %s", string(b))
			return
		}
		m := f.(map[string]interface{})
		repository_path := m["repository_path"].(string)
		c.Debugf("Repository: %s", repository_path)

		if !strings.HasPrefix(repository_path, repository_path_prefix) {
			c.Errorf("Unexpected repository path: %s", repository_path)
			return
		}
		repo := repository_path[len(repository_path_prefix):len(repository_path)-1]
		var key string
		var exists bool
		if key, exists = redirect_map[repo]; !exists {
			c.Warningf("No redirect for repo %s", repo)
			return
		}

		c.Infof("Found key %s for repo %s", key, repo)
		var url string = drone_io_prefix + repo + "?key=" + key

		// post to drone.io based on contents
		c.Infof("Forwarding request to %s", url)
		client := urlfetch.Client(c)
		resp, err := client.Post(url, repo, nil)
		if err != nil {
			c.Errorf("Error posting: %s", err)
			fmt.Fprint(w, "Error posting: %s", err)
			return
		}

		body, _ := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		c.Infof("POST response: %s", body)
		fmt.Fprint(w, "POST response: %s", body)
	}
}
<commit_msg>Update to drone.io API<commit_after>package ci

import (
	"appengine"
	"appengine/urlfetch"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

func init() {
	http.HandleFunc("/", handler)
}

var expected_user_agent string = "Google Code Project Hosting (+http://code.google.com/p/support/wiki/PostCommitWebHooks)"
var repository_path_prefix string = "https://code.google.com/p/m-lab."
var drone_io_prefix string = "https://drone.io/hook?id=dominic-mlab/m-lab."

func handler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		c := appengine.NewContext(r)
		c.Debugf("Request: %#v", r)

		if r.Header["User-Agent"][0] != expected_user_agent {
			c.Errorf("Unexpected user agent: %v", r.Header["User-Agent"])
			http.Error(w, "Unexpected user agent", http.StatusForbidden)
			return
		}

		var b []byte;
		b, err := ioutil.ReadAll(r.Body)
		r.Body.Close()

		if err != nil {
			c.Errorf("Failed to read body: %v", err)
			return
		}
		c.Debugf("Body: %s", string(b))
		var f interface{}
		err = json.Unmarshal(b, &f)
		if err != nil {
			c.Errorf("Failed to unmarshal body: %s", string(b))
			return
		}
		m := f.(map[string]interface{})
		repository_path := m["repository_path"].(string)
		c.Debugf("Repository: %s", repository_path)

		if !strings.HasPrefix(repository_path, repository_path_prefix) {
			c.Errorf("Unexpected repository path: %s", repository_path)
			return
		}
		repo := repository_path[len(repository_path_prefix):len(repository_path)-1]

		c.Infof("Found repo %s", repo)
		var url string = drone_io_prefix + repo

		// post to drone.io based on contents
		c.Infof("Forwarding request to %s", url)
		client := urlfetch.Client(c)
		resp, err := client.Post(url, repo, nil)
		if err != nil {
			c.Errorf("Error posting: %s", err)
			fmt.Fprint(w, "Error posting: %s", err)
			return
		}

		body, _ := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		c.Infof("POST response: %s", body)
		fmt.Fprint(w, "POST response: %s", body)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"go/build"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"

	"github.com/LK4D4/vndr/godl"
)

// cleanVendor removes files from unused pacakges and non-go files
func cleanVendor(vendorDir string, realDeps []*build.Package) error {
	realPaths := make(map[string]bool)
	realPaths[vendorDir] = true
	for _, pkg := range realDeps {
		realPaths[pkg.Dir] = true
	}
	var paths []string
	err := filepath.Walk(vendorDir, func(path string, i os.FileInfo, err error) error {
		paths = append(paths, path)
		return nil
	})
	if err != nil {
		return err
	}
	sort.Sort(sort.Reverse(sort.StringSlice(paths)))
	// iterate over paths (longer first)
	for _, p := range paths {
		fi, err := os.Stat(p)
		if err != nil {
			return err
		}
		if fi.IsDir() {
			// at this point we cleaned all files from unused deps dirs
			lst, err := ioutil.ReadDir(p)
			if err != nil {
				return err
			}
			if len(lst) > 1 {
				continue
			}
			// remove empty dirs and dirs with sole LICENSE file
			if len(lst) == 0 || (len(lst) == 1 && lst[0].Name() == "LICENSE") {
				if err := os.RemoveAll(p); err != nil {
					return err
				}
			}
			continue

		}
		if realPaths[filepath.Dir(p)] {
			continue
		}
		// remove all files if they're not in dependency paths
		if err := os.RemoveAll(p); err != nil {
			return err
		}
	}
	return nil
}

func cleanVCS(v *godl.VCS) error {
	if err := os.RemoveAll(filepath.Join(v.Root, "."+v.Type)); err != nil {
		return err
	}
	for _, otherVndr := range []string{"vendor", "Godeps", "_vendor"} {
		if err := os.RemoveAll(filepath.Join(v.Root, otherVndr)); err != nil {
			return err
		}
	}
	return nil
}
<commit_msg>Fix cleanup logic<commit_after>package main

import (
	"go/build"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"strings"

	"github.com/LK4D4/vndr/godl"
)

// cleanVendor removes files from unused pacakges and non-go files
func cleanVendor(vendorDir string, realDeps []*build.Package) error {
	realPaths := make(map[string]bool)
	for _, pkg := range realDeps {
		realPaths[pkg.Dir] = true
	}
	var paths []string
	err := filepath.Walk(vendorDir, func(path string, i os.FileInfo, err error) error {
		if path == vendorDir {
			return nil
		}
		if err != nil {
			return nil
		}
		if i.IsDir() {
			if i.Name() == "testdata" {
				return os.RemoveAll(path)
			}
			if !realPaths[path] {
				paths = append(paths, path)
			}
			return nil
		}
		if i.Name() == "LICENSE" || i.Name() == "COPYING" {
			return nil
		}
		if !realPaths[filepath.Dir(path)] {
			return os.Remove(path)
		}
		if strings.HasSuffix(path, "_test.go") {
			return os.Remove(path)
		}
		if filepath.Ext(path) == ".go" || filepath.Ext(path) == ".c" || filepath.Ext(path) == ".s" {
			return nil
		}
		return nil
	})
	if err != nil {
		return err
	}
	sort.Sort(sort.Reverse(sort.StringSlice(paths)))
	// iterate over paths (longer first)
	for _, p := range paths {
		// at this point we cleaned all files from unused deps dirs
		lst, err := ioutil.ReadDir(p)
		if err != nil {
			return err
		}
		var keepDir bool
		for _, fi := range lst {
			if fi.IsDir() {
				keepDir = true
				break
			}
		}
		if keepDir {
			continue
		}
		// remove all files if they're not in dependency paths
		if err := os.RemoveAll(p); err != nil {
			return err
		}
	}
	return nil
}

func cleanVCS(v *godl.VCS) error {
	if err := os.RemoveAll(filepath.Join(v.Root, "."+v.Type)); err != nil {
		return err
	}
	for _, otherVndr := range []string{"vendor", "Godeps", "_vendor"} {
		if err := os.RemoveAll(filepath.Join(v.Root, otherVndr)); err != nil {
			return err
		}
	}
	return nil
}
<|endoftext|>


<commit_before>// clock counts down to or up from a target time.
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	target := time.Date(2017, 11, 20, 0, 0, 0, 0, time.Local)
	motto := "Just Go"
	printTargetTime(target, motto)
	exitOnEnterKey()

	var previous time.Time
	for {
		now := time.Now().Truncate(time.Second)
		if now != previous {
			previous = now
			countdown := now.Sub(target) // Negative times are before the target
			printCountdown(now, countdown)
		}
		time.Sleep(100 * time.Millisecond)
	}
}

func exitOnEnterKey() {
	go func() {
		buf := make([]byte, 1)
		_, _ = os.Stdin.Read(buf)
		os.Exit(0)
	}()
}

const (
	indent         = "\t"
	highlightStart = "\x1b[1;35m"
	highlightEnd   = "\x1b[0m"
)

func printTargetTime(target time.Time, motto string) {
	fmt.Print(indent, highlightStart, motto, highlightEnd, "\n")
	fmt.Print(indent, target.Format(time.UnixDate), "\n")
}

func printCountdown(now time.Time, countdown time.Duration) {
	var sign string
	if countdown >= 0 {
		sign = "+"
	} else {
		sign = "-"
		countdown = -countdown
	}

	days := int(countdown / (24 * time.Hour))
	countdown = countdown % (24 * time.Hour)

	fmt.Print(indent, now.Format(time.UnixDate), "  ", sign)
	if days > 0 {
		fmt.Print(days, "d")
	}
	fmt.Print(countdown, "          \r")
	os.Stdout.Sync()
}
<commit_msg>math.Exp2(7) Day<commit_after>// Clock counts down to or up from a target time.
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	target := time.Date(2017, 12, 8, 0, 0, 0, 0, time.Local)
	motto := "Just Go"
	printTargetTime(target, motto)
	exitOnEnterKey()

	var previous time.Time
	for {
		now := time.Now().Truncate(time.Second)
		if now != previous {
			previous = now
			countdown := now.Sub(target) // Negative times are before the target
			printCountdown(now, countdown)
		}
		time.Sleep(100 * time.Millisecond)
	}
}

func exitOnEnterKey() {
	go func() {
		buf := make([]byte, 1)
		_, _ = os.Stdin.Read(buf)
		os.Exit(0)
	}()
}

const (
	indent         = "\t"
	highlightStart = "\x1b[1;35m"
	highlightEnd   = "\x1b[0m"
)

func printTargetTime(target time.Time, motto string) {
	fmt.Print(indent, highlightStart, motto, highlightEnd, "\n")
	fmt.Print(indent, target.Format(time.UnixDate), "\n")
}

func printCountdown(now time.Time, countdown time.Duration) {
	var sign string
	if countdown >= 0 {
		sign = "+"
	} else {
		sign = "-"
		countdown = -countdown
	}

	days := int(countdown / (24 * time.Hour))
	countdown = countdown % (24 * time.Hour)

	fmt.Print(indent, now.Format(time.UnixDate), "  ", sign)
	if days > 0 {
		fmt.Print(days, "d")
	}
	fmt.Print(countdown, "          \r")
	os.Stdout.Sync()
}
<|endoftext|>


<commit_before>// clock counts down to or up from a target time.
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	target := time.Date(2016, 4, 28, 0, 0, 0, 0, time.UTC)
	printTargetTime(target)
	exitOnEnterKey()

	var previous time.Time
	for {
		now := time.Now()
		now = now.Add(time.Duration(-now.Nanosecond())) // truncate to second
		if now != previous {
			previous = now
			remaining := target.Sub(now)
			printTimeRemaining(now, remaining)
		}
		time.Sleep(50 * time.Millisecond)
	}
}

func exitOnEnterKey() {
	go func() {
		buf := make([]byte, 1)
		_, _ = os.Stdin.Read(buf)
		os.Exit(0)
	}()
}

const (
	indent          = "\t"
	highlight_start = "\x1b[1;36m"
	highlight_end   = "\x1b[0m"
)

func printTargetTime(target time.Time) {
	fmt.Print(indent, highlight_start, "Just Go", highlight_end, "\n")
	fmt.Print(indent, target.Format(time.UnixDate), "\n")
}

func printTimeRemaining(now time.Time, remaining time.Duration) {
	var sign string
	if remaining > 0 {
		sign = "-" // countdown is "T minus..."
	} else {
		sign = "+" // count up is "T plus..."
		remaining = -remaining
	}

	var days int
	if remaining >= 24*time.Hour {
		days = int(remaining / (24 * time.Hour))
		remaining = remaining % (24 * time.Hour)
	}

	fmt.Print(indent, now.Format(time.UnixDate), "  ", sign)
	if days > 0 {
		fmt.Print(days, "d")
	}
	fmt.Print(remaining, "          \r")
}
<commit_msg>back to local time<commit_after>// clock counts down to or up from a target time.
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	target := time.Date(2016, 4, 28, 0, 0, 0, 0, time.Local)
	printTargetTime(target)
	exitOnEnterKey()

	var previous time.Time
	for {
		now := time.Now()
		now = now.Add(time.Duration(-now.Nanosecond())) // truncate to second
		if now != previous {
			previous = now
			remaining := target.Sub(now)
			printTimeRemaining(now, remaining)
		}
		time.Sleep(50 * time.Millisecond)
	}
}

func exitOnEnterKey() {
	go func() {
		buf := make([]byte, 1)
		_, _ = os.Stdin.Read(buf)
		os.Exit(0)
	}()
}

const (
	indent          = "\t"
	highlight_start = "\x1b[1;36m"
	highlight_end   = "\x1b[0m"
)

func printTargetTime(target time.Time) {
	fmt.Print(indent, highlight_start, "Just Go", highlight_end, "\n")
	fmt.Print(indent, target.Format(time.UnixDate), "\n")
}

func printTimeRemaining(now time.Time, remaining time.Duration) {
	var sign string
	if remaining > 0 {
		sign = "-" // countdown is "T minus..."
	} else {
		sign = "+" // count up is "T plus..."
		remaining = -remaining
	}

	var days int
	if remaining >= 24*time.Hour {
		days = int(remaining / (24 * time.Hour))
		remaining = remaining % (24 * time.Hour)
	}

	fmt.Print(indent, now.Format(time.UnixDate), "  ", sign)
	if days > 0 {
		fmt.Print(days, "d")
	}
	fmt.Print(remaining, "          \r")
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/coreos/go-etcd/etcd"
	"github.com/kelseyhightower/go-ini"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"text/template"
)

type FileInfo struct {
	Uid  uint32
	Gid  uint32
	Mode uint16
	Md5  string
}

type Settings struct {
	ConfigDir  string
	EtcdURL    string
	EtcdPrefix string
}

type Config struct {
	Templates []Template
	Services  map[string]Service
}

type Service struct {
	Name      string
	ReloadCmd string `json:"reload_cmd"`
}

type Template struct {
	Dest    string
	Gid     int
	Keys    []string
	Mode    string
	Uid     int
	Service string
	Src     string
}

var settings Settings
var defaultConfig = "/etc/confd/confd.ini"

func main() {
	if err := setConfig(); err != nil {
		log.Fatal(err.Error())
	}
	c := etcd.NewClient()

	// Get config
	configs, err := filepath.Glob(filepath.Join(settings.ConfigDir, "*json"))
	if err != nil {
		log.Fatal(err.Error())
	}

	for _, config := range configs {
		f, err := ioutil.ReadFile(config)
		if err != nil {
			log.Fatal(err.Error())
		}

		var cfg *Config
		err = json.Unmarshal(f, &cfg)
		if err != nil {
			log.Fatal(err.Error())
		}

		// Get the values we care about.
		r := strings.NewReplacer("/", "_")
		for _, tmplConfig := range cfg.Templates {
			m := make(map[string]interface{})
			for _, key := range tmplConfig.Keys {
				values, err := c.Get(filepath.Join(settings.EtcdPrefix, key))
				if err != nil {
					log.Fatal(err.Error())
				}
				for _, v := range values {
					key := strings.TrimPrefix(v.Key, settings.EtcdPrefix)
					new_key := r.Replace(key)
					m[new_key] = v.Value
				}
			}
			tmpl := filepath.Join(settings.ConfigDir, "templates", tmplConfig.Src)
			if isFileExist(tmpl) {
				temp, err := ioutil.TempFile("", "")
				defer os.Remove(temp.Name())
				if err != nil {
					log.Fatal(err.Error())
				}

				data, err := ioutil.ReadFile(tmpl)
				if err != nil {
					log.Fatal(err.Error())
				}
				t := template.Must(template.New("test").Parse(string(data)))
				err = t.Execute(temp, m)
				if err != nil {
					log.Fatal(err.Error())
				}

				fmt.Printf("Uid %d\n", tmplConfig.Uid)

				if isSync(temp.Name(), tmplConfig.Dest) {
					log.Print("Files are in sync")
				} else {
					log.Print("File not in sync")
				}

				os.Rename(temp.Name(), tmplConfig.Dest)

				myMode, _ := strconv.ParseUint(tmplConfig.Mode, 0, 32)
				os.Chmod(tmplConfig.Dest, os.FileMode(myMode))
				os.Chown(tmplConfig.Dest, tmplConfig.Uid, tmplConfig.Gid)
			} else {
				log.Fatal("Missing template: " + tmpl)
			}
		}
	}
}

func Stat(name string) (fi FileInfo, err error) {
	if isFileExist(name) {
		f, err := os.Open(name)
		defer f.Close()
		if err != nil {
			log.Fatal(err.Error())
		}
		stats, _ := f.Stat()
		fi.Uid = stats.Sys().(*syscall.Stat_t).Uid
		fi.Gid = stats.Sys().(*syscall.Stat_t).Gid
		fi.Mode = stats.Sys().(*syscall.Stat_t).Mode
		h := md5.New()
		io.Copy(h, f)
		fi.Md5 = fmt.Sprintf("%x", h.Sum(nil))
		return fi, nil
	} else {
		return fi, errors.New("File not found")
	}
}

func isSync(src, dest string) bool {
	// Compare current and old files

	return true
}

func setConfig() error {
	// Set defaults
	settings.ConfigDir = "/etc/confd/conf.d"
	settings.EtcdURL = "http://0.0.0.0:4001"
	settings.EtcdPrefix = "/"

	// Override defaults from config file.
	if isFileExist(defaultConfig) {
		s, err := ini.LoadFile(defaultConfig)
		if err != nil {
			return err
		}
		if configDir, ok := s.Get("main", "config_dir"); ok {
			settings.ConfigDir = configDir
		}
		if etcdURL, ok := s.Get("etcd", "url"); ok {
			settings.EtcdURL = etcdURL
		}
		if etcdPrefix, ok := s.Get("etcd", "prefix"); ok {
			settings.EtcdPrefix = etcdPrefix
		}
	}
	return nil
}

func isFileExist(fpath string) bool {
	if _, err := os.Stat(fpath); os.IsNotExist(err) {
		return false
	}
	return true
}
<commit_msg>Check file attributes before sync<commit_after>package main

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/coreos/go-etcd/etcd"
	"github.com/kelseyhightower/go-ini"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"text/template"
)

type FileInfo struct {
	Uid  uint32
	Gid  uint32
	Mode uint16
	Md5  string
}

type Settings struct {
	ConfigDir  string
	EtcdURL    string
	EtcdPrefix string
}

type Config struct {
	Templates []Template
	Services  map[string]Service
}

type Service struct {
	Name      string
	ReloadCmd string `json:"reload_cmd"`
}

type Template struct {
	Dest    string
	Gid     int
	Keys    []string
	Mode    string
	Uid     int
	Service string
	Src     string
}

var settings Settings
var defaultConfig = "/etc/confd/confd.ini"

func main() {
	if err := setConfig(); err != nil {
		log.Fatal(err.Error())
	}
	c := etcd.NewClient()

	// Get config
	configs, err := filepath.Glob(filepath.Join(settings.ConfigDir, "*json"))
	if err != nil {
		log.Fatal(err.Error())
	}

	for _, config := range configs {
		f, err := ioutil.ReadFile(config)
		if err != nil {
			log.Fatal(err.Error())
		}

		var cfg *Config
		err = json.Unmarshal(f, &cfg)
		if err != nil {
			log.Fatal(err.Error())
		}

		// Get the values we care about.
		r := strings.NewReplacer("/", "_")
		for _, tmplConfig := range cfg.Templates {
			m := make(map[string]interface{})
			for _, key := range tmplConfig.Keys {
				values, err := c.Get(filepath.Join(settings.EtcdPrefix, key))
				if err != nil {
					log.Fatal(err.Error())
				}
				for _, v := range values {
					key := strings.TrimPrefix(v.Key, settings.EtcdPrefix)
					new_key := r.Replace(key)
					m[new_key] = v.Value
				}
			}
			tmpl := filepath.Join(settings.ConfigDir, "templates", tmplConfig.Src)
			if isFileExist(tmpl) {
				temp, err := ioutil.TempFile("", "")
				defer os.Remove(temp.Name())
				if err != nil {
					log.Fatal(err.Error())
				}

				data, err := ioutil.ReadFile(tmpl)
				if err != nil {
					log.Fatal(err.Error())
				}
				t := template.Must(template.New("test").Parse(string(data)))
				err = t.Execute(temp, m)
				if err != nil {
					log.Fatal(err.Error())
				}
				myMode, _ := strconv.ParseUint(tmplConfig.Mode, 0, 32)
				os.Chmod(temp.Name(), os.FileMode(myMode))
				os.Chown(temp.Name(), tmplConfig.Uid, tmplConfig.Gid)

				if isSync(temp.Name(), tmplConfig.Dest) {
					log.Print("Files are in sync")
				} else {
					log.Print("File not in sync")
					os.Rename(temp.Name(), tmplConfig.Dest)
					cmd := cfg.Services[tmplConfig.Service].ReloadCmd
					log.Printf("Running %s", cmd)
				}
			} else {
				log.Fatal("Missing template: " + tmpl)
			}
		}
	}
}

func Stat(name string) (fi FileInfo, err error) {
	if isFileExist(name) {
		f, err := os.Open(name)
		defer f.Close()
		if err != nil {
			log.Fatal(err.Error())
		}
		stats, _ := f.Stat()
		fi.Uid = stats.Sys().(*syscall.Stat_t).Uid
		fi.Gid = stats.Sys().(*syscall.Stat_t).Gid
		fi.Mode = stats.Sys().(*syscall.Stat_t).Mode
		h := md5.New()
		io.Copy(h, f)
		fi.Md5 = fmt.Sprintf("%x", h.Sum(nil))
		return fi, nil
	} else {
		return fi, errors.New("File not found")
	}
}

func isSync(src, dest string) bool {
	old, err := Stat(dest)
	if err != nil {
		log.Fatal(err.Error())
	}

	n, err := Stat(src)
	if err != nil {
		log.Fatal(err.Error())
	}
	if old.Uid != n.Uid {
		return false
	}
	if old.Gid != n.Gid {
		return false
	}
	if old.Mode != n.Mode {
		return false
	}
	if old.Md5 != n.Md5 {
		return false
	}
	return true
}

func setConfig() error {
	// Set defaults
	settings.ConfigDir = "/etc/confd/conf.d"
	settings.EtcdURL = "http://0.0.0.0:4001"
	settings.EtcdPrefix = "/"

	// Override defaults from config file.
	if isFileExist(defaultConfig) {
		s, err := ini.LoadFile(defaultConfig)
		if err != nil {
			return err
		}
		if configDir, ok := s.Get("main", "config_dir"); ok {
			settings.ConfigDir = configDir
		}
		if etcdURL, ok := s.Get("etcd", "url"); ok {
			settings.EtcdURL = etcdURL
		}
		if etcdPrefix, ok := s.Get("etcd", "prefix"); ok {
			settings.EtcdPrefix = etcdPrefix
		}
	}
	return nil
}

func isFileExist(fpath string) bool {
	if _, err := os.Stat(fpath); os.IsNotExist(err) {
		return false
	}
	return true
}
<|endoftext|>


<commit_before>// Copyright 2012 The Oneslang Authors.  All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package log

// Priority used for identifying the severity of an event.
const (
	Poff = iota
	Pfatal
	Perror
	Pwarn
	Pinfo
	Pdebug
	Ptrace
	Pall
)

var priorityName = []string{
	Poff:   "OFF",
	Pfatal: "FATAL",
	Perror: "ERROR",
	Pwarn:  "WARN",
	Pinfo:  "INFO",
	Pdebug: "DEBUG",
	Ptrace: "TRACE",
	Pall:   "ALL",
}

// Layouts used for identifying the format of an event.
const (
	// Debug 2012/01/23 01:23:23.123123 /a/b/c/d.go:23: message
	Ldate         = 1 << iota     // the date: 2012/01/23
	Ltime                         // the time: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	Lpriority                     // the priority: Debug
	Lstd          = Ldate | Ltime // initial values for the standard logger
)
<commit_msg>rename Lstd -> LstdFlags for compatibility with log<commit_after>// Copyright 2012 The Oneslang Authors.  All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package log

// Priority used for identifying the severity of an event.
const (
	Poff = iota
	Pfatal
	Perror
	Pwarn
	Pinfo
	Pdebug
	Ptrace
	Pall
)

var priorityName = []string{
	Poff:   "OFF",
	Pfatal: "FATAL",
	Perror: "ERROR",
	Pwarn:  "WARN",
	Pinfo:  "INFO",
	Pdebug: "DEBUG",
	Ptrace: "TRACE",
	Pall:   "ALL",
}

// Layouts used for identifying the format of an event.
const (
	// Debug 2012/01/23 01:23:23.123123 /a/b/c/d.go:23: message
	Ldate         = 1 << iota     // the date: 2012/01/23
	Ltime                         // the time: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	Lpriority                     // the priority: Debug
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)
<|endoftext|>


<commit_before>package main

const (
	// Name of this command.
	Name string = "logcatf"
	// Version of this command.
	Version string = "0.4.0"
	// DefaultFormat will be used if format wasn't specified.
	DefaultFormat string = "%time [invert] %priority [reset] %tag: %message"
	// UTF8 represents encode `utf-8`
	UTF8 = "utf-8"
	// ShiftJIS represents encode `shift-jis`
	ShiftJIS = "shift-jis"
)

// Message has message strings.
var Message = map[string]string{
	"commandDescription": "A Command line tool for format Android Logcat",
	"helpFormat": `Format of output
 - Available keyword:
     %t (%time), %a (%tag), %p (%priority)
     %i (%pid), %I (%tid), %m (%message)
 - Example:
   adb logcat -v time | logcatf "%t %4i %m"
   adb logcat -v time | logcatf "%t %a %m" --to-csv > logcat.csv
   adb logcat -v | logcatf -o "Exception" -c "adb shell screencap -p /data/local/tmp/s.png"
 - Default Format:
   "%t [invert] %p [reset] %a: %m"`,
	"helpTrigger":           "regex to trigger a COMMAND.",
	"helpCommand":           "COMMAND will be executed on regex mathed. In COMMAND, you can use parsed logcat as environment variables. ex) `\\${message}` ** You need to escape a dollar mark. **",
	"helpEncode":            "output character encode.",
	"helpToCsv":             "output to CSV format. double-quote will be escaped.",
	"helpToColor":           "enable ANSI color. In format, you can use color tags. ex) [blue], [_red_], [bold], [reset], and more.",
	"helpToColorV":          "- color for verbose.",
	"helpToColorD":          "- color for debug.",
	"helpToColorI":          "- color for information.",
	"helpToColorW":          "- color for warning.",
	"helpToColorE":          "- color for error.",
	"helpToColorF":          "- color for fatal.",
	"msgUnavailableKeyword": "error: %s is not available. Please check `Availavle Keyword:` on help.",
	"msgDuplicatedKeyword":  "error: %s or %s is duplicated.",
	"msgCommandNumMismatch": "error: number of on and command flags are mismatch.",
}
<commit_msg>update to v0.4.1<commit_after>package main

const (
	// Name of this command.
	Name string = "logcatf"
	// Version of this command.
	Version string = "0.4.1"
	// DefaultFormat will be used if format wasn't specified.
	DefaultFormat string = "%time [invert] %priority [reset] %tag: %message"
	// UTF8 represents encode `utf-8`
	UTF8 = "utf-8"
	// ShiftJIS represents encode `shift-jis`
	ShiftJIS = "shift-jis"
)

// Message has message strings.
var Message = map[string]string{
	"commandDescription": "A Command line tool for format Android Logcat",
	"helpFormat": `Format of output
 - Available keyword:
     %t (%time), %a (%tag), %p (%priority)
     %i (%pid), %I (%tid), %m (%message)
 - Example:
   adb logcat -v time | logcatf "%t %4i %m"
   adb logcat -v time | logcatf "%t %a %m" --to-csv > logcat.csv
   adb logcat -v | logcatf -o "Exception" -c "adb shell screencap -p /data/local/tmp/s.png"
 - Default Format:
   "%t [invert] %p [reset] %a: %m"`,
	"helpTrigger":           "regex to trigger a COMMAND.",
	"helpCommand":           "COMMAND will be executed on regex mathed. In COMMAND, you can use parsed logcat as environment variables. ex) `\\${message}` ** You need to escape a dollar mark. **",
	"helpEncode":            "output character encode.",
	"helpToCsv":             "output to CSV format. double-quote will be escaped.",
	"helpToColor":           "enable ANSI color. In format, you can use color tags. ex) [blue], [_red_], [bold], [reset], and more.",
	"helpToColorV":          "- color for verbose.",
	"helpToColorD":          "- color for debug.",
	"helpToColorI":          "- color for information.",
	"helpToColorW":          "- color for warning.",
	"helpToColorE":          "- color for error.",
	"helpToColorF":          "- color for fatal.",
	"msgUnavailableKeyword": "error: %s is not available. Please check `Availavle Keyword:` on help.",
	"msgDuplicatedKeyword":  "error: %s or %s is duplicated.",
	"msgCommandNumMismatch": "error: number of on and command flags are mismatch.",
}
<|endoftext|>


<commit_before>package messaging

import (
	"github.com/microdevs/missy/service"
	"strconv"
)

const defaultKafkaMaxRetries = 3
const defaultKafkaRetriesIntervalMS = 5000

// InitConfig registeres
func InitConfig() {
	service.Config().RegisterOptionalParameter("KAFKA_RETRIES_MAX_NUMBER", strconv.Itoa(defaultKafkaMaxRetries), "kafka.retries.max.number", "The number of times a kafka reader will retry")
	service.Config().RegisterOptionalParameter("KAFKA_RETRIES_INTERVAL_MS", strconv.Itoa(defaultKafkaRetriesIntervalMS), "kafka.retries.interval.ms", "The time between retries in a kafka reader in ms")
	service.Config().Parse()
}
<commit_msg>fix(messaging): go vet errors<commit_after>package messaging

import (
	"github.com/microdevs/missy/service"
	"strconv"
)

const defaultKafkaMaxRetries = 3
const defaultKafkaRetriesIntervalMS = 5000

// InitConfig registers the standard config for this package
func InitConfig() {
	service.Config().RegisterOptionalParameter("KAFKA_RETRIES_MAX_NUMBER", strconv.Itoa(defaultKafkaMaxRetries), "kafka.retries.max.number", "The number of times a kafka reader will retry")
	service.Config().RegisterOptionalParameter("KAFKA_RETRIES_INTERVAL_MS", strconv.Itoa(defaultKafkaRetriesIntervalMS), "kafka.retries.interval.ms", "The time between retries in a kafka reader in ms")
	service.Config().Parse()
}
<|endoftext|>


<commit_before>package trie

import (
	"bufio"
	"bytes"
	"encoding/gob"
	"errors"
	"fmt"
	"io"
	"os"
	"time"
)

func init() {
	// gob.Register(&trie.EnDecodeTrie{})
}

type Trie struct {
	Root *Branch
	// Cardinaliy int
}

/*
NewTrie returns the pointer to a new Trie with an initiallized root Branch
*/
func NewTrie() *Trie {
	t := &Trie{}
	t.Root = NewBranch()
	return t
}

/*
Add adds an non existing entry to the trie
*/
func (t *Trie) Add(entry string) {
	t.Root.Add([]byte(entry))
}

/*
Delete removes an existing entry from the trie
*/
func (t *Trie) Delete(entry string) bool {
	if len(entry) == 0 {
		return false
	}
	return t.Root.delete([]byte(entry))
}

/*
Has returns true if the `entry` exists in the `Trie`
*/
func (t *Trie) Has(entry string) bool {
	return t.Root.Has([]byte(entry))
}

/*
Has returns true if the the `Trie` contains entries with the given prefix
*/
func (t *Trie) HasPrefix(prefix string) bool {
	return t.Root.HasPrefix([]byte(prefix))
}

/*
Members returns all entries of the Trie
*/
func (t *Trie) Members() []string {
	return t.Root.Members([]byte{})
}

/*
PrefixMembers returns all entries of the Trie that have the given prefix
*/
func (t *Trie) PrefixMembers(prefix string) []string {
	return t.Root.prefixMembers([]byte{}, []byte(prefix))
}

/*
DumpToFile dumps all values into a slice of strings and writes that to a file
using encoding/gob.

The Trie itself can currently not be encoded directly because gob does not
directly support structs with a sync.Mutex on them.
*/
func (t *Trie) DumpToFile(fname string) (err error) {
	entries := t.Members()
	// sort.Sort(sort.Reverse(sort.StringSlice(entries)))

	buf := new(bytes.Buffer)
	enc := gob.NewEncoder(buf)
	if err = enc.Encode(entries); err != nil {
		err = errors.New(fmt.Sprintf("Could encode Trie entries for dump file: %v", err))
		return
	}

	f, err := os.Create(fname)
	defer f.Close()
	if err != nil {
		err = errors.New(fmt.Sprintf("Could not save dump file: %v", err))
		return
	}
	w := bufio.NewWriter(f)
	bl, err := w.Write(buf.Bytes())
	if err != nil {
		err = errors.New(fmt.Sprintf("Error writing to dump file: %v", err))
		return
	}
	fmt.Printf("wrote %d bytes\n", bl)
	w.Flush()
	return
}

/*
LoadFromFile loads a gib encoded wordlist from a file and creates a new Trie
by Add()ing all of them.
*/
func LoadFromFile(fname string) (tr *Trie, err error) {
	f, err := os.Open(fname)
	defer f.Close()
	if err != nil {
		err = errors.New(fmt.Sprintf("Could not open Trie file: %v", err))
		return
	}

	buf := bufio.NewReader(f)
	var entries []string
	dec := gob.NewDecoder(buf)
	if err = dec.Decode(&entries); err != nil {
		if err == io.EOF && entries == nil {
			fmt.Println("Nothing to decode. Seems the file is empty.")
			err = nil
		} else {
			err = errors.New(fmt.Sprintf("Decoding error: %v", err))
			return
		}
	}

	tr = NewTrie()
	startTime := time.Now()
	for _, word := range entries {
		tr.Add(word)
	}
	fmt.Printf("adding words to index took: %v\n", time.Since(startTime))

	return
}

/*
Dump returns a string representation of the `Trie`
*/
func (t *Trie) Dump() string {
	return t.Root.Dump(0)
}

/*
 */
func (t *Trie) PrintDump() {
	t.Root.PrintDump()
}

// persistence

// type EnDecodeTrie struct {
// 	Root *EnDecodeBranch
// }

// type EnDecodeBranch struct {
// 	Branches  map[byte]*Branch
// 	LeafValue []byte // tail end
// 	End       bool
// }

// func (t *Trie) FileDump(fname string) {

// 	edTrie := &EnDecodeTrie{
// 	Root: &EnDecodeBranch{
// 	Branches
// 	}
// 	}

// 	buf := new(bytes.Buffer)
// 	enc := gob.NewEncoder(buf)
// 	if err := enc.Encode(tr); err != nil {
// 		log.Println(err)
// 	}

// 	f, err := os.Create(fname)
// 	if err != nil {
// 		log.Println(err)
// 	}
// 	defer f.Close()

// 	w := bufio.NewWriter(f)
// 	blength, err := w.Write(buf.Bytes())
// 	log.Printf("wrote %d bytes\n", blength)
// 	w.Flush()
// }
<commit_msg>fix nil pointer problem<commit_after>package trie

import (
	"bufio"
	"bytes"
	"encoding/gob"
	"errors"
	"fmt"
	"io"
	"os"
	"time"
)

func init() {
	// gob.Register(&trie.EnDecodeTrie{})
}

type Trie struct {
	Root *Branch
	// Cardinaliy int
}

/*
NewTrie returns the pointer to a new Trie with an initiallized root Branch
*/
func NewTrie() *Trie {
	t := &Trie{}
	t.Root = NewBranch()
	return t
}

/*
Add adds an non existing entry to the trie
*/
func (t *Trie) Add(entry string) {
	t.Root.Add([]byte(entry))
}

/*
Delete removes an existing entry from the trie
*/
func (t *Trie) Delete(entry string) bool {
	if len(entry) == 0 {
		return false
	}
	return t.Root.delete([]byte(entry))
}

/*
Has returns true if the `entry` exists in the `Trie`
*/
func (t *Trie) Has(entry string) bool {
	return t.Root.Has([]byte(entry))
}

/*
Has returns true if the the `Trie` contains entries with the given prefix
*/
func (t *Trie) HasPrefix(prefix string) bool {
	return t.Root.HasPrefix([]byte(prefix))
}

/*
Members returns all entries of the Trie
*/
func (t *Trie) Members() []string {
	return t.Root.Members([]byte{})
}

/*
PrefixMembers returns all entries of the Trie that have the given prefix
*/
func (t *Trie) PrefixMembers(prefix string) []string {
	return t.Root.prefixMembers([]byte{}, []byte(prefix))
}

/*
DumpToFile dumps all values into a slice of strings and writes that to a file
using encoding/gob.

The Trie itself can currently not be encoded directly because gob does not
directly support structs with a sync.Mutex on them.
*/
func (t *Trie) DumpToFile(fname string) (err error) {
	entries := t.Members()
	// sort.Sort(sort.Reverse(sort.StringSlice(entries)))

	buf := new(bytes.Buffer)
	enc := gob.NewEncoder(buf)
	if err = enc.Encode(entries); err != nil {
		err = errors.New(fmt.Sprintf("Could encode Trie entries for dump file: %v", err))
		return
	}

	f, err := os.Create(fname)
	if err != nil {
		err = errors.New(fmt.Sprintf("Could not save dump file: %v", err))
		return
	}
	defer f.Close()

	w := bufio.NewWriter(f)
	bl, err := w.Write(buf.Bytes())
	if err != nil {
		err = errors.New(fmt.Sprintf("Error writing to dump file: %v", err))
		return
	}
	fmt.Printf("wrote %d bytes\n", bl)
	w.Flush()
	return
}

/*
LoadFromFile loads a gib encoded wordlist from a file and creates a new Trie
by Add()ing all of them.
*/
func LoadFromFile(fname string) (tr *Trie, err error) {
	fmt.Println("Load trie from", fname)
	f, err := os.Open(fname)
	if err != nil {
		err = errors.New(fmt.Sprintf("Could not open Trie file: %v", err))
		return
	}
	defer f.Close()

	buf := bufio.NewReader(f)
	var entries []string
	dec := gob.NewDecoder(buf)
	if err = dec.Decode(&entries); err != nil {
		if err == io.EOF && entries == nil {
			fmt.Println("Nothing to decode. Seems the file is empty.")
			err = nil
		} else {
			err = errors.New(fmt.Sprintf("Decoding error: %v", err))
			return
		}
	}

	tr = NewTrie()
	startTime := time.Now()
	for _, word := range entries {
		tr.Add(word)
	}
	fmt.Printf("adding words to index took: %v\n", time.Since(startTime))

	return
}

/*
Dump returns a string representation of the `Trie`
*/
func (t *Trie) Dump() string {
	return t.Root.Dump(0)
}

/*
 */
func (t *Trie) PrintDump() {
	t.Root.PrintDump()
}

// persistence

// type EnDecodeTrie struct {
// 	Root *EnDecodeBranch
// }

// type EnDecodeBranch struct {
// 	Branches  map[byte]*Branch
// 	LeafValue []byte // tail end
// 	End       bool
// }

// func (t *Trie) FileDump(fname string) {

// 	edTrie := &EnDecodeTrie{
// 	Root: &EnDecodeBranch{
// 	Branches
// 	}
// 	}

// 	buf := new(bytes.Buffer)
// 	enc := gob.NewEncoder(buf)
// 	if err := enc.Encode(tr); err != nil {
// 		log.Println(err)
// 	}

// 	f, err := os.Create(fname)
// 	if err != nil {
// 		log.Println(err)
// 	}
// 	defer f.Close()

// 	w := bufio.NewWriter(f)
// 	blength, err := w.Write(buf.Bytes())
// 	log.Printf("wrote %d bytes\n", blength)
// 	w.Flush()
// }
<|endoftext|>


<commit_before><commit_msg>SessionManager uses Flag system + Doc<commit_after><|endoftext|>


<commit_before>package runc

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"strconv"
	"syscall"
	"time"

	"github.com/Sirupsen/logrus"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

// Runc is the client to the runc cli
type Runc struct {
	Root  string
	Debug bool
}

// List returns all containers created inside the provided runc root directory
func (r *Runc) List() ([]*Container, error) {
	data, err := r.command("list", "--format=json").Output()
	if err != nil {
		return nil, err
	}
	var out []*Container
	if err := json.Unmarshal(data, &out); err != nil {
		return nil, err
	}
	return out, nil
}

// State returns the state for the container provided by id
func (r *Runc) State(id string) (*Container, error) {
	data, err := r.command("state", id).CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("%s: %s", err, data)
	}
	var c Container
	if err := json.Unmarshal(data, &c); err != nil {
		return nil, err
	}
	return &c, nil
}

type CreateOpts struct {
	IO
	// PidFile is a path to where a pid file should be created
	PidFile      string
	Console      string
	Detach       bool
	NoPivot      bool
	NoNewKeyring bool
}

type IO struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

func (o IO) setSTDIO(cmd *exec.Cmd) {
	cmd.Stdin = o.Stdin
	cmd.Stdout = o.Stdout
	cmd.Stderr = o.Stderr
}

func (o *CreateOpts) args() (out []string) {
	if o.PidFile != "" {
		out = append(out, "--pid-file", o.PidFile)
	}
	if o.Console != "" {
		out = append(out, "--console", o.Console)
	}
	if o.NoPivot {
		out = append(out, "--no-pivot")
	}
	if o.NoNewKeyring {
		out = append(out, "--no-new-keyring")
	}
	if o.Detach {
		out = append(out, "--detach")
	}
	return out
}

// Create creates a new container and returns its pid if it was created successfully
func (r *Runc) Create(id, bundle string, opts *CreateOpts) error {
	args := []string{"create", "--bundle", bundle}
	if opts != nil {
		args = append(args, opts.args()...)
	}
	cmd := r.command(append(args, id)...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	return runOrError(cmd)
}

// Start will start an already created container
func (r *Runc) Start(id string) error {
	return runOrError(r.command("start", id))
}

type ExecOpts struct {
	IO
	Uid    int
	Gid    int
	Cwd    string
	Tty    bool
	Detach bool
}

func (o *ExecOpts) args() (out []string) {
	out = append(out, "--user", fmt.Sprintf("%d:%d", o.Uid, o.Gid))
	if o.Tty {
		out = append(out, "--tty")
	}
	if o.Cwd != "" {
		out = append(out, "--cwd", o.Cwd)
	}
	if o.Detach {
		out = append(out, "--detach")
	}
	return out
}

// Exec executes an additional process inside a container
func (r *Runc) Exec(id string, args []string, opts *ExecOpts) error {
	bargs := []string{"exec"}
	if opts != nil {
		bargs = append(bargs, opts.args()...)
	}
	args = append(bargs, id)
	cmd := r.command(append(bargs, args...)...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	return runOrError(cmd)
}

// ExecProcess executres and additional process inside the container based on a full
// OCI Process specification
func (r *Runc) ExecProcess(id string, spec specs.Process, opts *ExecOpts) error {
	f, err := ioutil.TempFile("", "-process")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	err = json.NewEncoder(f).Encode(spec)
	f.Close()
	if err != nil {
		return err
	}
	args := []string{"exec", "--process", f.Name()}
	if opts != nil {
		args = append(args, opts.args()...)
	}
	cmd := r.command(args...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	return runOrError(cmd)
}

// Run runs the create, start, delete lifecycle of the container
// and returns its exit status after it has exited
func (r *Runc) Run(id, bundle string, opts *CreateOpts) (int, error) {
	args := []string{"run", "--bundle", bundle}
	if opts != nil {
		args = append(args, opts.args()...)
	}
	cmd := r.command(append(args, id)...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	if err := cmd.Start(); err != nil {
		return -1, err
	}
	status, err := cmd.Process.Wait()
	if err != nil {
		return -1, err
	}
	return status.Sys().(syscall.WaitStatus).ExitStatus(), nil
}

// Delete deletes the container
func (r *Runc) Delete(id string) error {
	return r.command("delete", id).Run()
}

// Kill sends the specified signal to the container
func (r *Runc) Kill(id string, sig int) error {
	return r.command("kill", id, strconv.Itoa(sig)).Run()
}

// Stats return the stats for a container like cpu, memory, and io
func (r *Runc) Stats(id string) (*Stats, error) {
	cmd := r.command("events", "--stats", id)
	rd, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	defer func() {
		rd.Close()
		cmd.Wait()
	}()
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	var e Event
	if err := json.NewDecoder(rd).Decode(&e); err != nil {
		return nil, err
	}
	return e.Stats, nil
}

// Events returns an event stream from runc for a container with stats and OOM notifications
func (r *Runc) Events(id string, interval time.Duration) (chan *Event, error) {
	cmd := r.command("events", fmt.Sprintf("--interval=%ds", int(interval.Seconds())), id)
	rd, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	if err := cmd.Start(); err != nil {
		rd.Close()
		return nil, err
	}
	var (
		dec = json.NewDecoder(rd)
		c   = make(chan *Event, 128)
	)
	go func() {
		defer func() {
			close(c)
			rd.Close()
			cmd.Wait()
		}()
		for {
			var e Event
			if err := dec.Decode(&e); err != nil {
				if err == io.EOF {
					return
				}
				logrus.WithError(err).Error("runc: decode event")
				continue
			}
			c <- &e
		}
	}()
	return c, nil
}

func (r *Runc) args() (out []string) {
	if r.Root != "" {
		out = append(out, "--root", r.Root)
	}
	if r.Debug {
		out = append(out, "--debug")
	}
	return out
}

func (r *Runc) command(args ...string) *exec.Cmd {
	return exec.Command("runc", append(r.args(), args...)...)
}
<commit_msg>Add pidfile to exec<commit_after>package runc

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"strconv"
	"syscall"
	"time"

	"github.com/Sirupsen/logrus"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

// Runc is the client to the runc cli
type Runc struct {
	Root  string
	Debug bool
}

// List returns all containers created inside the provided runc root directory
func (r *Runc) List() ([]*Container, error) {
	data, err := r.command("list", "--format=json").Output()
	if err != nil {
		return nil, err
	}
	var out []*Container
	if err := json.Unmarshal(data, &out); err != nil {
		return nil, err
	}
	return out, nil
}

// State returns the state for the container provided by id
func (r *Runc) State(id string) (*Container, error) {
	data, err := r.command("state", id).CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("%s: %s", err, data)
	}
	var c Container
	if err := json.Unmarshal(data, &c); err != nil {
		return nil, err
	}
	return &c, nil
}

type CreateOpts struct {
	IO
	// PidFile is a path to where a pid file should be created
	PidFile      string
	Console      string
	Detach       bool
	NoPivot      bool
	NoNewKeyring bool
}

type IO struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

func (o IO) setSTDIO(cmd *exec.Cmd) {
	cmd.Stdin = o.Stdin
	cmd.Stdout = o.Stdout
	cmd.Stderr = o.Stderr
}

func (o *CreateOpts) args() (out []string) {
	if o.PidFile != "" {
		out = append(out, "--pid-file", o.PidFile)
	}
	if o.Console != "" {
		out = append(out, "--console", o.Console)
	}
	if o.NoPivot {
		out = append(out, "--no-pivot")
	}
	if o.NoNewKeyring {
		out = append(out, "--no-new-keyring")
	}
	if o.Detach {
		out = append(out, "--detach")
	}
	return out
}

// Create creates a new container and returns its pid if it was created successfully
func (r *Runc) Create(id, bundle string, opts *CreateOpts) error {
	args := []string{"create", "--bundle", bundle}
	if opts != nil {
		args = append(args, opts.args()...)
	}
	cmd := r.command(append(args, id)...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	return runOrError(cmd)
}

// Start will start an already created container
func (r *Runc) Start(id string) error {
	return runOrError(r.command("start", id))
}

type ExecOpts struct {
	IO
	PidFile string
	Uid     int
	Gid     int
	Cwd     string
	Tty     bool
	Detach  bool
}

func (o *ExecOpts) args() (out []string) {
	out = append(out, "--user", fmt.Sprintf("%d:%d", o.Uid, o.Gid))
	if o.Tty {
		out = append(out, "--tty")
	}
	if o.Cwd != "" {
		out = append(out, "--cwd", o.Cwd)
	}
	if o.Detach {
		out = append(out, "--detach")
	}
	if o.PidFile != "" {
		out = append(out, "--pid-file", o.PidFile)
	}
	return out
}

// Exec executes an additional process inside a container
func (r *Runc) Exec(id string, args []string, opts *ExecOpts) error {
	bargs := []string{"exec"}
	if opts != nil {
		bargs = append(bargs, opts.args()...)
	}
	args = append(bargs, id)
	cmd := r.command(append(bargs, args...)...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	return runOrError(cmd)
}

// ExecProcess executres and additional process inside the container based on a full
// OCI Process specification
func (r *Runc) ExecProcess(id string, spec specs.Process, opts *ExecOpts) error {
	f, err := ioutil.TempFile("", "-process")
	if err != nil {
		return err
	}
	defer os.Remove(f.Name())
	err = json.NewEncoder(f).Encode(spec)
	f.Close()
	if err != nil {
		return err
	}
	args := []string{"exec", "--process", f.Name()}
	if opts != nil {
		args = append(args, opts.args()...)
	}
	cmd := r.command(append(args, id)...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	return runOrError(cmd)
}

// Run runs the create, start, delete lifecycle of the container
// and returns its exit status after it has exited
func (r *Runc) Run(id, bundle string, opts *CreateOpts) (int, error) {
	args := []string{"run", "--bundle", bundle}
	if opts != nil {
		args = append(args, opts.args()...)
	}
	cmd := r.command(append(args, id)...)
	if opts != nil {
		opts.setSTDIO(cmd)
	}
	if err := cmd.Start(); err != nil {
		return -1, err
	}
	status, err := cmd.Process.Wait()
	if err != nil {
		return -1, err
	}
	return status.Sys().(syscall.WaitStatus).ExitStatus(), nil
}

// Delete deletes the container
func (r *Runc) Delete(id string) error {
	return r.command("delete", id).Run()
}

// Kill sends the specified signal to the container
func (r *Runc) Kill(id string, sig int) error {
	return r.command("kill", id, strconv.Itoa(sig)).Run()
}

// Stats return the stats for a container like cpu, memory, and io
func (r *Runc) Stats(id string) (*Stats, error) {
	cmd := r.command("events", "--stats", id)
	rd, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	defer func() {
		rd.Close()
		cmd.Wait()
	}()
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	var e Event
	if err := json.NewDecoder(rd).Decode(&e); err != nil {
		return nil, err
	}
	return e.Stats, nil
}

// Events returns an event stream from runc for a container with stats and OOM notifications
func (r *Runc) Events(id string, interval time.Duration) (chan *Event, error) {
	cmd := r.command("events", fmt.Sprintf("--interval=%ds", int(interval.Seconds())), id)
	rd, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	if err := cmd.Start(); err != nil {
		rd.Close()
		return nil, err
	}
	var (
		dec = json.NewDecoder(rd)
		c   = make(chan *Event, 128)
	)
	go func() {
		defer func() {
			close(c)
			rd.Close()
			cmd.Wait()
		}()
		for {
			var e Event
			if err := dec.Decode(&e); err != nil {
				if err == io.EOF {
					return
				}
				logrus.WithError(err).Error("runc: decode event")
				continue
			}
			c <- &e
		}
	}()
	return c, nil
}

func (r *Runc) args() (out []string) {
	if r.Root != "" {
		out = append(out, "--root", r.Root)
	}
	if r.Debug {
		out = append(out, "--debug")
	}
	return out
}

func (r *Runc) command(args ...string) *exec.Cmd {
	return exec.Command("runc", append(r.args(), args...)...)
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"github.com/howeyc/gopass"
	"io"
	"log"
)

func main() {
	fmt.Printf("Password: ")
	password := gopass.GetPasswd()

	hasher := sha256.New()
	hasher.Write(password)
	key := hasher.Sum(nil)

	plaintext := []byte("some really really really long plaintext")
	fmt.Printf("%s\n", plaintext)

	ciphertext, err := encrypt(key, plaintext)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%0x\n", ciphertext)

	result, err := decrypt(key, ciphertext)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", result)
}

func encrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	b := base64.StdEncoding.EncodeToString(text)
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
	return ciphertext, nil
}

func decrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(text) < aes.BlockSize {
		return nil, errors.New("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)
	data, err := base64.StdEncoding.DecodeString(string(text))
	if err != nil {
		return nil, err
	}
	return data, nil
}
<commit_msg>update<commit_after>package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"github.com/howeyc/gopass"
	"io"
	"log"
	"os"
	"io/ioutil"
)

func main() {
	if len(os.Args) < 2 {
		log.Fatal("No file given.")
	}

	inputData, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Password: ")
	password := gopass.GetPasswd()

	hasher := sha256.New()
	hasher.Write(password)
	key := hasher.Sum(nil)

	fmt.Printf("%s\n", inputData)

	ciphertext, err := encrypt(key, inputData)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%0x\n", ciphertext)

	result, err := decrypt(key, ciphertext)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", result)
}

func encrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	b := base64.StdEncoding.EncodeToString(text)
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
	return ciphertext, nil
}

func decrypt(key, text []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	if len(text) < aes.BlockSize {
		return nil, errors.New("ciphertext too short")
	}
	iv := text[:aes.BlockSize]
	text = text[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(text, text)
	data, err := base64.StdEncoding.DecodeString(string(text))
	if err != nil {
		return nil, err
	}
	return data, nil
}

func openFile() {

}
<|endoftext|>