<commit_before>package cmd

import (
	"fmt"
	"os"
	"strings"

	"git.apache.org/thrift.git/lib/go/thrift"
	"github.com/hltcoe/goncrete"
	"github.com/spf13/cobra"
)

const (
	summaryTypesURL string = "http://hltcoe.github.io/concrete/schema/summarization.html#Enum_SummarySourceType"
)

var (
	// SummarizeHost is the host of store
	SummarizeHost string
	// SummarizePort is the port of store
	SummarizePort uint64
	// UUIDs are uuids to add to the summarization request
	UUIDs []string
	// TypeString is the type of summarization request
	TypeString string

	// MaxTokens is the maximum number of tokens to submit
	MaxTokens uint
)

func init() {
	RootCmd.AddCommand(SummarizeCmd)

	SummarizeCmd.PersistentFlags().StringVar(&SummarizeHost, "summ-host", "localhost", "Hostname of summarization service")
	SummarizeCmd.PersistentFlags().Uint64Var(&SummarizePort, "summ-port", 22999, "Port of summarization service")
	SummarizeCmd.Flags().StringVarP(&TypeString, "type", "t", "entity", "Summary source type (example: entity)")
	SummarizeCmd.Flags().StringSliceVar(&UUIDs, "uuids", []string{}, "UUIDs to query")
	SummarizeCmd.Flags().UintVar(&MaxTokens, "max-tokens", 250, "maximum tokens in summary")
}

var SummarizeCmd = &cobra.Command{
	Use:   "summarize",
	Short: "Client for interacting with a summarize service",
	Long:  `This provides a client for interacting with a summarization service.`,
	Run: func(cmd *cobra.Command, args []string) {
		summType, err := goncrete.SummarySourceTypeFromString(strings.ToUpper(TypeString))
		if err != nil {
			fmt.Printf("error parsing summary source type: %v\n", err)
			fmt.Println("check available types: " + summaryTypesURL)
			os.Exit(-1)
		}

		var transportFactory thrift.TTransportFactory
		if Buffered {
			transportFactory = thrift.NewTBufferedTransportFactory(8192)
		} else {
			transportFactory = thrift.NewTTransportFactory()
		}

		if Framed {
			transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
		}
		protocolFactory := thrift.NewTCompactProtocolFactory()
		tport, err := NewSocketServer(SummarizeHost, SummarizePort)
		if err != nil {
			fmt.Printf("error creating socket: %v\n", err)
			os.Exit(-1)
		}

		wrapped := transportFactory.GetTransport(tport)
		defer wrapped.Close()
		if err = wrapped.Open(); err != nil {
			fmt.Printf("error connecting to store: %v\n", err)
			os.Exit(-1)
		}

		summCli := goncrete.NewSummarizationServiceClientFactory(wrapped, protocolFactory)
		alive, err := summCli.Alive()
		if err != nil || !alive {
			fmt.Printf("server not alive / error querying alive: %v", err)
			os.Exit(-1)
		}

		summReq := goncrete.NewSummarizationRequest()
		thriftMaxTokens := int32(MaxTokens)
		summReq.MaximumTokens = thrift.Int32Ptr(thriftMaxTokens)
		for _, uuid := range UUIDs {
			concUUID := goncrete.NewUUID()
			concUUID.UuidString = uuid
			summReq.SourceIds = append(summReq.SourceIds, concUUID)
		}
		summReq.SourceType = goncrete.SummarySourceTypePtr(summType)
		resp, err := summCli.Summarize(summReq)
		if err != nil {
			fmt.Printf("error summary call: %v\n", err)
			os.Exit(-1)
		}
		if resp == nil {
			fmt.Println("received nil Summary")
		} else if resp.IsSetSummaryCommunication() && resp.GetSummaryCommunication().IsSetText() {
			fmt.Println(resp.GetSummaryCommunication().GetText())
		} else {
			fmt.Println("no summary communication text received")
		}
	},
}
<commit_msg>summarize: add capabilities flag<commit_after>package cmd

import (
	"fmt"
	"os"
	"strings"

	"git.apache.org/thrift.git/lib/go/thrift"
	"github.com/hltcoe/goncrete"
	"github.com/spf13/cobra"
)

const (
	summaryTypesURL string = "http://hltcoe.github.io/concrete/schema/summarization.html#Enum_SummarySourceType"
)

var (
	// SummarizeHost is the host of store
	SummarizeHost string
	// SummarizePort is the port of store
	SummarizePort uint64
	// UUIDs are uuids to add to the summarization request
	UUIDs []string
	// TypeString is the type of summarization request
	TypeString string

	// MaxTokens is the maximum number of tokens to submit
	MaxTokens uint

	// IsCapabilities calls GetCapabilities then quits
	IsCapabilities bool
)

func init() {
	RootCmd.AddCommand(SummarizeCmd)

	SummarizeCmd.PersistentFlags().StringVar(&SummarizeHost, "summ-host", "localhost", "Hostname of summarization service")
	SummarizeCmd.PersistentFlags().Uint64Var(&SummarizePort, "summ-port", 22999, "Port of summarization service")
	SummarizeCmd.Flags().StringVarP(&TypeString, "type", "t", "entity", "Summary source type (example: entity)")
	SummarizeCmd.Flags().StringSliceVar(&UUIDs, "uuids", []string{}, "UUIDs to query")
	SummarizeCmd.Flags().UintVar(&MaxTokens, "max-tokens", 250, "maximum tokens in summary")
	SummarizeCmd.Flags().BoolVar(&IsCapabilities, "capabilities", false, "perform a getCapabilities call then exit")
}

var SummarizeCmd = &cobra.Command{
	Use:   "summarize",
	Short: "Client for interacting with a summarize service",
	Long:  `This provides a client for interacting with a summarization service.`,
	Run: func(cmd *cobra.Command, args []string) {
		var summType goncrete.SummarySourceType
		var err error

		// if this is not a capabilities check, validate the input
		if !IsCapabilities {
			summType, err = goncrete.SummarySourceTypeFromString(strings.ToUpper(TypeString))
			if err != nil {
				fmt.Printf("error parsing summary source type: %v\n", err)
				fmt.Println("check available types: " + summaryTypesURL)
				os.Exit(-1)
			}
		}

		var transportFactory thrift.TTransportFactory
		if Buffered {
			transportFactory = thrift.NewTBufferedTransportFactory(8192)
		} else {
			transportFactory = thrift.NewTTransportFactory()
		}

		if Framed {
			transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
		}
		protocolFactory := thrift.NewTCompactProtocolFactory()
		tport, err := NewSocketServer(SummarizeHost, SummarizePort)
		if err != nil {
			fmt.Printf("error creating socket: %v\n", err)
			os.Exit(-1)
		}

		wrapped := transportFactory.GetTransport(tport)
		defer wrapped.Close()
		if err = wrapped.Open(); err != nil {
			fmt.Printf("error connecting to store: %v\n", err)
			os.Exit(-1)
		}

		summCli := goncrete.NewSummarizationServiceClientFactory(wrapped, protocolFactory)
		alive, err := summCli.Alive()
		if err != nil || !alive {
			fmt.Printf("server not alive / error querying alive: %v", err)
			os.Exit(-1)
		}
		if IsCapabilities {
			caps, capErr := summCli.GetCapabilities()
			if capErr != nil {
				fmt.Printf("error during get capabilities call: %v", capErr.Error())
				os.Exit(-1)
			}

			fmt.Printf("Received %v capabilities from server:\n", len(caps))
			for idx := range caps {
				cap := caps[idx]
				fmt.Printf("\t%v\n", cap.String())
			}
			return
		}

		summReq := goncrete.NewSummarizationRequest()
		thriftMaxTokens := int32(MaxTokens)
		summReq.MaximumTokens = thrift.Int32Ptr(thriftMaxTokens)
		for _, uuid := range UUIDs {
			concUUID := goncrete.NewUUID()
			concUUID.UuidString = uuid
			summReq.SourceIds = append(summReq.SourceIds, concUUID)
		}
		summReq.SourceType = goncrete.SummarySourceTypePtr(summType)
		resp, err := summCli.Summarize(summReq)
		if err != nil {
			fmt.Printf("error summary call: %v\n", err)
			os.Exit(-1)
		}
		if resp == nil {
			fmt.Println("received nil Summary")
		} else if resp.IsSetSummaryCommunication() && resp.GetSummaryCommunication().IsSetText() {
			fmt.Println(resp.GetSummaryCommunication().GetText())
		} else {
			fmt.Println("no summary communication text received")
		}
	},
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"

	"github.com/anacrolix/utp"
	"github.com/anacrolix/envpprof"
)

func main() {
	defer envpprof.Stop()
	listen := flag.Bool("l", false, "listen")
	port := flag.Int("p", 0, "port to listen on")
	flag.Parse()
	var (
		conn net.Conn
		err  error
	)
	if *listen {
		s, err := utp.NewSocket(fmt.Sprintf(":%d", *port))
		if err != nil {
			log.Fatal(err)
		}
		defer s.Close()
		conn, err = s.Accept()
		if err != nil {
			log.Fatal(err)
		}
	} else {
		conn, err = utp.Dial(net.JoinHostPort(flag.Arg(0), flag.Arg(1)))
		if err != nil {
			log.Fatal(err)
		}
	}
	defer conn.Close()
	writerDone := make(chan struct{})
	go func() {
		defer close(writerDone)
		written, err := io.Copy(conn, os.Stdin)
		if err != nil {
			conn.Close()
			log.Fatalf("error after writing %d bytes: %s", written, err)
		}
		log.Printf("wrote %d bytes", written)
		conn.Close()
	}()
	n, err := io.Copy(os.Stdout, conn)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("received %d bytes", n)
	// <-writerDone
}
<commit_msg>sortimports<commit_after>package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"

	"github.com/anacrolix/envpprof"

	"github.com/anacrolix/utp"
)

func main() {
	defer envpprof.Stop()
	listen := flag.Bool("l", false, "listen")
	port := flag.Int("p", 0, "port to listen on")
	flag.Parse()
	var (
		conn net.Conn
		err  error
	)
	if *listen {
		s, err := utp.NewSocket(fmt.Sprintf(":%d", *port))
		if err != nil {
			log.Fatal(err)
		}
		defer s.Close()
		conn, err = s.Accept()
		if err != nil {
			log.Fatal(err)
		}
	} else {
		conn, err = utp.Dial(net.JoinHostPort(flag.Arg(0), flag.Arg(1)))
		if err != nil {
			log.Fatal(err)
		}
	}
	defer conn.Close()
	writerDone := make(chan struct{})
	go func() {
		defer close(writerDone)
		written, err := io.Copy(conn, os.Stdin)
		if err != nil {
			conn.Close()
			log.Fatalf("error after writing %d bytes: %s", written, err)
		}
		log.Printf("wrote %d bytes", written)
		conn.Close()
	}()
	n, err := io.Copy(os.Stdout, conn)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("received %d bytes", n)
	// <-writerDone
}
<|endoftext|>


<commit_before>package fs

import (
	"log"

	"bazil.org/bazil/cas/chunks"
	"bazil.org/bazil/db"
	"bazil.org/bazil/fs/inodes"
	"bazil.org/bazil/fs/wire"
	"bazil.org/bazil/tokens"
	"bazil.org/fuse/fs"
)

type Volume struct {
	db         *db.DB
	volID      db.VolumeID
	chunkStore chunks.Store
}

var _ = fs.FS(&Volume{})
var _ = fs.FSInodeGenerator(&Volume{})

var bucketVolume = []byte(tokens.BucketVolume)
var bucketVolName = []byte(tokens.BucketVolName)
var bucketDir = []byte("dir")
var bucketInode = []byte("inode")
var bucketSnap = []byte("snap")
var bucketStorage = []byte("storage")

func (v *Volume) bucket(tx *db.Tx) *db.Volume {
	vv, err := tx.Volumes().GetByVolumeID(&v.volID)
	if err != nil {
		log.Printf("volume has disappeared: %v: %v", &v.volID, err)
	}
	return vv
}

// Open returns a FUSE filesystem instance serving content from the
// given volume. The result can be passed to bazil.org/fuse/fs#Serve
// to start serving file access requests from the kernel.
//
// Caller guarantees volume ID exists at least as long as requests are
// served for this file system.
func Open(db *db.DB, chunkStore chunks.Store, volumeID *db.VolumeID) (*Volume, error) {
	fs := &Volume{}
	fs.db = db
	fs.volID = *volumeID
	fs.chunkStore = chunkStore
	return fs, nil
}

func (v *Volume) Root() (fs.Node, error) {
	d := newDir(v, tokens.InodeRoot, nil, "")
	return d, nil
}

func (*Volume) GenerateInode(parent uint64, name string) uint64 {
	return inodes.Dynamic(parent, name)
}

var _ = fs.FSInodeGenerator(&Volume{})

type node interface {
	fs.Node

	marshal() (*wire.Dirent, error)
	setName(name string)
}
<commit_msg>fs: Memoize root dir<commit_after>package fs

import (
	"log"

	"bazil.org/bazil/cas/chunks"
	"bazil.org/bazil/db"
	"bazil.org/bazil/fs/inodes"
	"bazil.org/bazil/fs/wire"
	"bazil.org/bazil/tokens"
	"bazil.org/fuse/fs"
)

type Volume struct {
	db         *db.DB
	volID      db.VolumeID
	chunkStore chunks.Store
	root       *dir
}

var _ = fs.FS(&Volume{})
var _ = fs.FSInodeGenerator(&Volume{})

var bucketVolume = []byte(tokens.BucketVolume)
var bucketVolName = []byte(tokens.BucketVolName)
var bucketDir = []byte("dir")
var bucketInode = []byte("inode")
var bucketSnap = []byte("snap")
var bucketStorage = []byte("storage")

func (v *Volume) bucket(tx *db.Tx) *db.Volume {
	vv, err := tx.Volumes().GetByVolumeID(&v.volID)
	if err != nil {
		log.Printf("volume has disappeared: %v: %v", &v.volID, err)
	}
	return vv
}

// Open returns a FUSE filesystem instance serving content from the
// given volume. The result can be passed to bazil.org/fuse/fs#Serve
// to start serving file access requests from the kernel.
//
// Caller guarantees volume ID exists at least as long as requests are
// served for this file system.
func Open(db *db.DB, chunkStore chunks.Store, volumeID *db.VolumeID) (*Volume, error) {
	fs := &Volume{}
	fs.db = db
	fs.volID = *volumeID
	fs.chunkStore = chunkStore
	fs.root = newDir(fs, tokens.InodeRoot, nil, "")
	return fs, nil
}

func (v *Volume) Root() (fs.Node, error) {
	return v.root, nil
}

func (*Volume) GenerateInode(parent uint64, name string) uint64 {
	return inodes.Dynamic(parent, name)
}

var _ = fs.FSInodeGenerator(&Volume{})

type node interface {
	fs.Node

	marshal() (*wire.Dirent, error)
	setName(name string)
}
<|endoftext|>


<commit_before>package g

import (
	"encoding/json"
	"github.com/toolkits/file"
	"log"
	"sync"
)

type PluginConfig struct {
	Dir    string `json:"dir"`
	Git    string `json:"git"`
	LogDir string `json:"logs"`
}

type HeartbeatConfig struct {
	Enabled  bool   `json:"enabled"`
	Addr     string `json:"addr"`
	Interval int    `json:"interval"`
	Timeout  int    `json:"timeout"`
}

type TransferConfig struct {
	Enabled  bool   `json:"enabled"`
	Addr     string `json:"addr"`
	Interval int    `json:"interval"`
	Timeout  int    `json:"timeout"`
}

type HttpConfig struct {
	Port int `json:"port"`
}

type GlobalConfig struct {
	Debug     bool             `json:"debug"`
	Hostname  string           `json:"hostname"`
	Plugin    *PluginConfig    `json:"plugin"`
	Heartbeat *HeartbeatConfig `json:"heartbeat"`
	Transfer  *TransferConfig  `json:"transfer"`
	Http      *HttpConfig      `json:"http"`
}

var (
	config *GlobalConfig
	rwlock = new(sync.RWMutex)
)

func GetConfig() *GlobalConfig {
	rwlock.RLock()
	defer rwlock.RUnlock()
	return config
}

func ParseConfig(cfg string) {
	rwlock.Lock()
	defer rwlock.Unlock()
	if !file.IsExist(cfg) {
		log.Fatalln("config file:", cfg, "is not existent")
	}

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		log.Fatalln("read config file:", cfg, "fail:", err)
	}

	var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}

	config = &c

	if config.Debug {
		log.Println("read config file:", cfg, "successfully")
	}
}
<commit_msg>rename<commit_after>package g

import (
	"encoding/json"
	"github.com/toolkits/file"
	"log"
	"sync"
)

type PluginConfig struct {
	Dir    string `json:"dir"`
	Git    string `json:"git"`
	LogDir string `json:"logs"`
}

type HeartbeatConfig struct {
	Enabled  bool   `json:"enabled"`
	Addr     string `json:"addr"`
	Interval int    `json:"interval"`
	Timeout  int    `json:"timeout"`
}

type TransferConfig struct {
	Enabled  bool   `json:"enabled"`
	Addr     string `json:"addr"`
	Interval int    `json:"interval"`
	Timeout  int    `json:"timeout"`
}

type HttpConfig struct {
	Port int `json:"port"`
}

type GlobalConfig struct {
	Debug     bool             `json:"debug"`
	Hostname  string           `json:"hostname"`
	Plugin    *PluginConfig    `json:"plugin"`
	Heartbeat *HeartbeatConfig `json:"heartbeat"`
	Transfer  *TransferConfig  `json:"transfer"`
	Http      *HttpConfig      `json:"http"`
}

var (
	config *GlobalConfig
	lock   = new(sync.RWMutex)
)

func GetConfig() *GlobalConfig {
	lock.RLock()
	defer lock.RUnlock()
	return config
}

func ParseConfig(cfg string) {
	lock.Lock()
	defer lock.Unlock()
	if !file.IsExist(cfg) {
		log.Fatalln("config file:", cfg, "is not existent")
	}

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		log.Fatalln("read config file:", cfg, "fail:", err)
	}

	var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}

	config = &c

	if config.Debug {
		log.Println("read config file:", cfg, "successfully")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func main() {
	fmt.Printf("geist main() sees os.Args = '%#v'\n", os.Args)

	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "geist error: missing path to script to run as argument to geist.")
		os.Exit(1)
	}
	if !FileExists(os.Args[1]) {
		fmt.Fprintf(os.Stderr, "geist error: file not found: '%s'.")
		os.Exit(1)
	}

	origPath := os.Args[1]
	newPath, err := GeistFileToGoFile(origPath)
	panicOn(err)

	outb, errb, err := Run(".", "go", "run", newPath)
	if err != nil {
		panic(fmt.Errorf("geist error: could not run script '%s': '%v'", origPath, err))
	}
	os.Stdout.Write(outb.Bytes())
	os.Stderr.Write(errb.Bytes())
}

func GeistFileToGoFile(geistPath string) (string, error) {
	f, err := os.Open(geistPath)
	if err != nil {
		return "", err
	}
	defer f.Close()

	r := bufio.NewReader(f)

	// Can't work in the cwd directory.
	// make a new project dir (or run a cached one)
	p := NewProject(geistPath)
	writeDir, err := p.GetWriteDir()
	panicOn(err)

	writePath := writeDir + "main.go"

	of, err := os.OpenFile(writePath, os.O_CREATE|os.O_WRONLY, 0755)
	if err != nil {
		return "", fmt.Errorf("GeistFileToGoFile(): error durring OpenFile on '%s': '%v'",
			writePath, err)
	}
	defer of.Close()

	// preamble
	fmt.Fprintf(of, `package main
import (
 "fmt"
 "time"
)

func main() {
 // avoid compile errors if unused
  _ = fmt.Fprintf
  _ = time.Now

`)

	// we've got to remove the first line from f
	_, err = r.ReadString('\n')
	if err == io.EOF {
		return "", fmt.Errorf("not enough input in '%s': hit EOF before finding end of first line", geistPath)
	}
	panicOn(err)

	// copy the rest of the script.g -> main.go file
	_, err = io.Copy(of, r)
	if err != nil {
		return "", fmt.Errorf("GeistFileToGoFile(): error during creation of .go file in '%s': '%v'", writePath, err)
	}

	// postamble
	fmt.Fprintf(of, `
}
`)

	return writePath, nil
}
<commit_msg>atg. more packages by default<commit_after>package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

func main() {
	fmt.Printf("geist main() sees os.Args = '%#v'\n", os.Args)

	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "geist error: missing path to script to run as argument to geist.")
		os.Exit(1)
	}
	if !FileExists(os.Args[1]) {
		fmt.Fprintf(os.Stderr, "geist error: file not found: '%s'.")
		os.Exit(1)
	}

	origPath := os.Args[1]
	newPath, err := GeistFileToGoFile(origPath)
	panicOn(err)

	outb, errb, err := Run(".", "go", "run", newPath)
	if err != nil {
		panic(fmt.Errorf("geist error: could not run script '%s': '%v'. Stderr: '%s'. Stdout: '%s'.", origPath, err, errb.String(), outb.String()))
	}
	os.Stdout.Write(outb.Bytes())
	os.Stderr.Write(errb.Bytes())
}

func GeistFileToGoFile(geistPath string) (string, error) {
	f, err := os.Open(geistPath)
	if err != nil {
		return "", err
	}
	defer f.Close()

	r := bufio.NewReader(f)

	// Can't work in the cwd directory.
	// make a new project dir (or run a cached one)
	p := NewProject(geistPath)
	writeDir, err := p.GetWriteDir()
	panicOn(err)

	writePath := writeDir + "main.go"

	of, err := os.OpenFile(writePath, os.O_CREATE|os.O_WRONLY, 0755)
	if err != nil {
		return "", fmt.Errorf("GeistFileToGoFile(): error durring OpenFile on '%s': '%v'",
			writePath, err)
	}
	defer of.Close()

	// preamble
	fmt.Fprintf(of, `package main
import (
 "fmt"
 "time"
 "os"
 "io"
 "os/exec"
)

func main() {
 // avoid compile errors if unused
  _ = fmt.Fprintf
  _ = time.Now
  _ = exec.Command
  _ = os.Chdir
  _ = io.Copy

`)

	// we've got to remove the first line from f
	_, err = r.ReadString('\n')
	if err == io.EOF {
		return "", fmt.Errorf("not enough input in '%s': hit EOF before finding end of first line", geistPath)
	}
	panicOn(err)

	// copy the rest of the script.g -> main.go file
	_, err = io.Copy(of, r)
	if err != nil {
		return "", fmt.Errorf("GeistFileToGoFile(): error during creation of .go file in '%s': '%v'", writePath, err)
	}

	// postamble
	fmt.Fprintf(of, `
}
`)

	return writePath, nil
}
<|endoftext|>


<commit_before>package main

import (
	// stdlib
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"path/filepath"
	"regexp"
	"text/template"

	// external
	"github.com/russross/blackfriday"
)

const (
	GOIKIVERSION = "0.0.1"
)

var (
	displayVersion bool
	config         Config
	templates      *template.Template
	validPath      *regexp.Regexp
)

type Config struct {
	Port    int
	Host    string
	DataDir string
}

type Page struct {
	Title string
	Body  string
}

func init() {
	flag.IntVar(&config.Port, "port", 4567, "Bind port")
	flag.StringVar(&config.Host, "host", "0.0.0.0", "Hostname or IP address to listen on")
	flag.StringVar(&config.DataDir, "data-dir", "./data", "Directory for page data")
	flag.BoolVar(&displayVersion, "version", false, "Display version and exit")

	templates = template.Must(template.ParseFiles("templates/edit.html", "templates/view.html"))
	validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9/]+)$")
}

func (p *Page) save() error {
	filename := buildFilename(p.Title)
	return ioutil.WriteFile(filename, []byte(p.Body), 0600)
}

func buildFilename(title string) string {
	return filepath.Join(config.DataDir, (title + ".txt"))
}

func loadPage(title string) (*Page, error) {
	filename := buildFilename(title)
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return &Page{Title: title, Body: string(body)}, nil
}

func processLinks(content []byte) []byte {
	re := regexp.MustCompile(`\[([^\]]+)]\(\)`)
	return re.ReplaceAllFunc(content, func(match []byte) []byte {
		return re.ReplaceAll(match, []byte("[$1]($1)"))
	})
}

func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}

	content := []byte(p.Body)
	content = processLinks(content)
	content = blackfriday.MarkdownCommon(content)
	p.Body = string(content)

	renderTemplate(w, "view", p)
}

func editHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		p = &Page{Title: title}
	}
	renderTemplate(w, "edit", p)
}

func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
	body := r.FormValue("body")
	p := &Page{Title: title, Body: body}
	err := p.save()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
	err := templates.ExecuteTemplate(w, tmpl+".html", p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		if path == "/" {
			path = "/view/FrontPage"
		}
		fmt.Println(path)
		m := validPath.FindStringSubmatch(path)
		if m == nil {
			http.NotFound(w, r)
			return
		}
		fn(w, r, m[2])
	}
}

func main() {
	flag.Parse()

	// Display version and exit
	if displayVersion {
		fmt.Println("Goiki", GOIKIVERSION)
		return
	}

	http.Handle("/static/", http.FileServer(http.Dir("./")))
	http.HandleFunc("/", makeHandler(viewHandler))
	http.HandleFunc("/view/", makeHandler(viewHandler))
	http.HandleFunc("/edit/", makeHandler(editHandler))
	http.HandleFunc("/save/", makeHandler(saveHandler))

	l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", config.Host, config.Port))
	if err != nil {
		log.Fatal(err)
	}

	s := &http.Server{}
	s.Serve(l)
	return
}
<commit_msg>Reorganize variables<commit_after>package main

import (
	// stdlib
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"path/filepath"
	"regexp"
	"text/template"

	// external
	"github.com/russross/blackfriday"
)

const (
	GOIKIVERSION = "0.0.1"
)

var (
	displayVersion bool
	config         Config
	templates      *template.Template
	validPath      *regexp.Regexp
	validLink      *regexp.Regexp
)

type Config struct {
	Port    int
	Host    string
	DataDir string
}

type Page struct {
	Title string
	Body  string
}

func init() {
	flag.IntVar(&config.Port, "port", 4567, "Bind port")
	flag.StringVar(&config.Host, "host", "0.0.0.0", "Hostname or IP address to listen on")
	flag.StringVar(&config.DataDir, "data-dir", "./data", "Directory for page data")
	flag.BoolVar(&displayVersion, "version", false, "Display version and exit")

	templates = template.Must(template.ParseFiles("templates/edit.html", "templates/view.html"))
	validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9/]+)$")
	validLink = regexp.MustCompile(`\[([^\]]+)]\(\)`)
}

func (p *Page) save() error {
	filename := buildFilename(p.Title)
	return ioutil.WriteFile(filename, []byte(p.Body), 0600)
}

func buildFilename(title string) string {
	return filepath.Join(config.DataDir, (title + ".txt"))
}

func loadPage(title string) (*Page, error) {
	filename := buildFilename(title)
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return &Page{Title: title, Body: string(body)}, nil
}

func processLinks(content []byte) []byte {
	return validLink.ReplaceAllFunc(content, func(match []byte) []byte {
		return validLink.ReplaceAll(match, []byte("[$1]($1)"))
	})
}

func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}

	content := []byte(p.Body)
	content = processLinks(content)
	content = blackfriday.MarkdownCommon(content)
	p.Body = string(content)

	renderTemplate(w, "view", p)
}

func editHandler(w http.ResponseWriter, r *http.Request, title string) {
	p, err := loadPage(title)
	if err != nil {
		p = &Page{Title: title}
	}
	renderTemplate(w, "edit", p)
}

func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
	body := r.FormValue("body")
	p := &Page{Title: title, Body: body}
	err := p.save()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
	err := templates.ExecuteTemplate(w, tmpl+".html", p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		path := r.URL.Path
		if path == "/" {
			path = "/view/FrontPage"
		}
		fmt.Println(path)
		m := validPath.FindStringSubmatch(path)
		if m == nil {
			http.NotFound(w, r)
			return
		}
		fn(w, r, m[2])
	}
}

func main() {
	flag.Parse()

	// Display version and exit
	if displayVersion {
		fmt.Println("Goiki", GOIKIVERSION)
		return
	}

	http.Handle("/static/", http.FileServer(http.Dir("./")))
	http.HandleFunc("/", makeHandler(viewHandler))
	http.HandleFunc("/view/", makeHandler(viewHandler))
	http.HandleFunc("/edit/", makeHandler(editHandler))
	http.HandleFunc("/save/", makeHandler(saveHandler))

	l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", config.Host, config.Port))
	if err != nil {
		log.Fatal(err)
	}

	s := &http.Server{}
	s.Serve(l)
	return
}
<|endoftext|>


<commit_before>package main

import (
	"code.google.com/p/gorilla/mux"
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/{name}", func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		fmt.Fprintf(w, "%s", getMetaTag(vars["name"]))
	})
	http.Handle("/", router)

	addr := ":" + os.Getenv("PORT")
	log.Println("Listening on " + addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}

func getMetaTag(name string) string {
	return fmt.Sprintf("<meta name=\"go-import\" content=\"gopkg.iprod.activestate.com/%s git gitolite@gitolite.activestate.com:%s.git\">",
		name, name)
}
<commit_msg>go get requries a scheme in git repo url<commit_after>package main

import (
	"code.google.com/p/gorilla/mux"
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	router := mux.NewRouter()
	router.HandleFunc("/{name}", func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		fmt.Fprintf(w, "%s", getMetaTag(vars["name"]))
	})
	http.Handle("/", router)

	addr := ":" + os.Getenv("PORT")
	log.Println("Listening on " + addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}

func getMetaTag(name string) string {
	return fmt.Sprintf("<meta name=\"go-import\" content=\"gopkg.iprod.activestate.com/%s git ssh://gitolite@gitolite.activestate.com/%s\">",
		name, name)
}
<|endoftext|>


<commit_before>package gorma

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

	"github.com/raphael/goa/design"
	"github.com/raphael/goa/goagen/codegen"
	"gopkg.in/alecthomas/kingpin.v2"
)

// Generator is the application code generator.
type Generator struct {
	genfiles []string
}

// Generate is the generator entry point called by the meta generator.
func Generate(api *design.APIDefinition) ([]string, error) {
	g, err := NewGenerator()
	if err != nil {
		return nil, err
	}
	return g.Generate(api)
}

// NewGenerator returns the application code generator.
func NewGenerator() (*Generator, error) {
	return new(Generator), nil
}

// Generate produces the skeleton main.
func (g *Generator) Generate(api *design.APIDefinition) ([]string, error) {

	os.RemoveAll(ModelDir())
	os.MkdirAll(ModelDir(), 0755)
	app := kingpin.New("Model generator", "model generator")
	codegen.RegisterFlags(app)
	_, err := app.Parse(os.Args[1:])
	if err != nil {
		panic(err)
	}
	imp, err := filepath.Rel(filepath.Join(os.Getenv("GOPATH"), "src"), codegen.OutputDir)
	if err != nil {
		return nil, err
	}
	imp = filepath.Join(imp, "app")
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport(imp),
		codegen.SimpleImport("github.com/jinzhu/gorm"),
		codegen.SimpleImport("github.com/jinzhu/copier"),
		codegen.SimpleImport("database/sql"),
	}

	rbacimports := []*codegen.ImportSpec{
		codegen.SimpleImport(imp),
		codegen.SimpleImport("github.com/mikespook/gorbac"),
	}

	rbactitle := fmt.Sprintf("%s: RBAC", api.Name)
	_, dorbac := api.Metadata["github.com/bketelsen/gorma#rbac"]

	err = api.IterateUserTypes(func(res *design.UserTypeDefinition) error {
		if res.Type.IsObject() {
			title := fmt.Sprintf("%s: Models", api.Name)
			filename := filepath.Join(ModelDir(), res.TypeName+"_model.go")
			mtw, err := NewModelWriter(filename)
			if err != nil {
				panic(err)
			}
			mtw.WriteHeader(title, "models", imports)
			if md, ok := res.Metadata["github.com/bketelsen/gorma"]; ok && md == "Model" {
				fmt.Println("Found Gorma Metadata:", md)
				err = mtw.Execute(res)
				if err != nil {
					g.Cleanup()
					return err
				}
			}
			if err := mtw.FormatCode(); err != nil {
				g.Cleanup()

			}
			if err != nil {
				g.genfiles = append(g.genfiles, filename)
			}
			return nil
		}

		return nil

	})
	if dorbac {
		rbacfilename := filepath.Join(ModelDir(), "rbac.go")
		rbacw, err := NewRbacWriter(rbacfilename)
		if err != nil {
			panic(err)
		}
		rbacw.WriteHeader(rbactitle, "models", rbacimports)
		err = rbacw.Execute(api)
		if err != nil {
			g.Cleanup()
			return g.genfiles, err
		}
		if err := rbacw.FormatCode(); err != nil {
			g.Cleanup()
			return nil, err
		}
		if err != nil {
			g.genfiles = append(g.genfiles, rbacfilename)
		}

	}

	return g.genfiles, err
}

// Cleanup removes all the files generated by this generator during the last invokation of Generate.
func (g *Generator) Cleanup() {
	for _, f := range g.genfiles {
		os.Remove(f)
	}
	g.genfiles = nil
}
<commit_msg>trying it<commit_after>package gorma

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

	"github.com/raphael/goa/design"
	"github.com/raphael/goa/goagen/codegen"
	"gopkg.in/alecthomas/kingpin.v2"
)

// Generator is the application code generator.
type Generator struct {
	genfiles []string
}

// Generate is the generator entry point called by the meta generator.
func Generate(api *design.APIDefinition) ([]string, error) {
	g, err := NewGenerator()
	if err != nil {
		return nil, err
	}
	return g.Generate(api)
}

// NewGenerator returns the application code generator.
func NewGenerator() (*Generator, error) {
	return new(Generator), nil
}

// Generate produces the skeleton main.
func (g *Generator) Generate(api *design.APIDefinition) ([]string, error) {

	os.RemoveAll(ModelDir())
	os.MkdirAll(ModelDir(), 0755)
	app := kingpin.New("Model generator", "model generator")
	codegen.RegisterFlags(app)
	_, err := app.Parse(os.Args[1:])
	if err != nil {
		panic(err)
	}
	imp, err := filepath.Rel(filepath.Join(os.Getenv("GOPATH"), "src"), codegen.OutputDir)
	if err != nil {
		return nil, err
	}
	imp = filepath.Join(imp, "app")
	imports := []*codegen.ImportSpec{
		codegen.SimpleImport(imp),
		codegen.SimpleImport("github.com/jinzhu/gorm"),
		codegen.SimpleImport("github.com/jinzhu/copier"),
		codegen.SimpleImport("database/sql"),
	}

	rbacimports := []*codegen.ImportSpec{
		codegen.SimpleImport(imp),
		codegen.SimpleImport("github.com/mikespook/gorbac"),
	}

	rbactitle := fmt.Sprintf("%s: RBAC", api.Name)
	_, dorbac := api.Metadata["github.com/bketelsen/gorma#rbac"]

	err = api.IterateUserTypes(func(res *design.UserTypeDefinition) error {
		if res.Type.IsObject() {
			title := fmt.Sprintf("%s: Models", api.Name)
			modelname := strings.ToLower(Demodel(res.TypeName))
			filename := filepath.Join(ModelDir(), modelname+"_model.go")
			mtw, err := NewModelWriter(filename)
			if err != nil {
				panic(err)
			}
			mtw.WriteHeader(title, "models", imports)
			if md, ok := res.Metadata["github.com/bketelsen/gorma"]; ok && md == "Model" {
				fmt.Println("Found Gorma Metadata:", md)
				err = mtw.Execute(res)
				if err != nil {
					g.Cleanup()
					return err
				}
			}
			if err := mtw.FormatCode(); err != nil {
				g.Cleanup()

			}
			if err != nil {
				g.genfiles = append(g.genfiles, filename)
			}
			return nil
		}

		return nil

	})
	if dorbac {
		rbacfilename := filepath.Join(ModelDir(), "rbac.go")
		rbacw, err := NewRbacWriter(rbacfilename)
		if err != nil {
			panic(err)
		}
		rbacw.WriteHeader(rbactitle, "models", rbacimports)
		err = rbacw.Execute(api)
		if err != nil {
			g.Cleanup()
			return g.genfiles, err
		}
		if err := rbacw.FormatCode(); err != nil {
			g.Cleanup()
			return nil, err
		}
		if err != nil {
			g.genfiles = append(g.genfiles, rbacfilename)
		}

	}

	return g.genfiles, err
}

// Cleanup removes all the files generated by this generator during the last invokation of Generate.
func (g *Generator) Cleanup() {
	for _, f := range g.genfiles {
		os.Remove(f)
	}
	g.genfiles = nil
}
<|endoftext|>


<commit_before>package gotak

import (
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/http/httputil"
	"strings"
)

type TlsVersion uint16

const (
	TLS_1_0 TlsVersion = 10
	TLS_1_1            = 11
	TLS_1_2            = 12
)

func (t TlsVersion) String() string {
	switch t {
	case TLS_1_0:
		return "1.0"
	case TLS_1_1:
		return "1.1"
	case TLS_1_2:
		return "1.2"
	default:
		return ""
	}
}

func cryptVersTlsToGotak(vers uint16) (TlsVersion, error) {
	switch vers {
	case VersionSSL30, VersionTLS10:
		return TLS_1_0, nil
	case VersionTLS11:
		return TLS_1_1, nil
	case VersionTLS12:
		return TLS_1_2, nil
	default:
		return 0, fmt.Errorf("Error: Could not parse version %d.", vers)
	}
}

func Diagnose(addr string, config *Config) (*Diagnostics, error) {
	if config == nil {
		config = new(Config)
		config.NextProtos = []string{"http/1.1"}
	}

	if !strings.Contains(addr, ":") {
		addr = addr + ":443"
	}

	conn, diag, err := Dial("tcp", addr, config)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	clientConn := httputil.NewClientConn(conn, nil)

	req, err := http.NewRequest("HEAD", "/", nil)
	if err != nil {
		return nil, err
	}

	_, err = clientConn.Do(req)
	if err != nil {
		return nil, err
	}

	if diag.NpnStrings != nil {
		diag.NPN = true
	}

	return diag, nil
}

type Diagnostics struct {
	Version      TlsVersion
	CipherSuite  string
	Certificates []*x509.Certificate
	NPN          bool
	NpnStrings   []string
}

func (d *Diagnostics) JSON() ([]byte, error) {
	jd := new(jsonDiagnostics)
	jd.Version = d.Version.String()
	jd.CipherSuite = d.CipherSuite
	jd.NPN = d.NpnStrings

	return json.Marshal(jd)
}

func (d *Diagnostics) EncodeJSON(w io.Writer) error {
	jd := new(jsonDiagnostics)
	jd.Version = d.Version.String()
	jd.CipherSuite = d.CipherSuite
	jd.NPN = d.NpnStrings

	return json.NewEncoder(w).Encode(jd)
}

type jsonDiagnostics struct {
	Version     string   `json:"version"`
	CipherSuite string   `json:"cipher_suite"`
	NPN         []string `json:"next_protocol_negotiation,omitempty"`
}
<commit_msg>Minor refactoring and request improvement<commit_after>package gotak

import (
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/http/httputil"
	"strings"
)

type Diagnostics struct {
	Version      TlsVersion
	CipherSuite  string
	Certificates []*x509.Certificate
	NPN          bool
	NpnStrings   []string
}

func Diagnose(addr string, config *Config) (*Diagnostics, error) {
	if config == nil {
		config = new(Config)
		config.NextProtos = []string{"http/1.1"}
	}

	if !strings.Contains(addr, ":") {
		addr = addr + ":443"
	}

	conn, diag, err := Dial("tcp", addr, config)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	clientConn := httputil.NewClientConn(conn, nil)

	req, err := http.NewRequest("GET", "/favicon.ico", nil)
	if err != nil {
		return nil, err
	}

	_, err = clientConn.Do(req)
	if err != nil {
		return nil, err
	}

	if diag.NpnStrings != nil {
		diag.NPN = true
	}

	return diag, nil
}

func DiagnoseRequest(r *http.Request, config *Config) (*Diagnostics, error) {
	if config == nil {
		config = new(Config)
		config.NextProtos = []string{"http/1.1"}
	}

	if !strings.Contains(addr, ":") {
		addr = addr + ":443"
	}

	conn, diag, err := Dial("tcp", addr, config)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	clientConn := httputil.NewClientConn(conn, nil)

	_, err = clientConn.Do(r)
	if err != nil {
		return nil, err
	}

	if diag.NpnStrings != nil {
		diag.NPN = true
	}

	return diag, nil
}

func (d *Diagnostics) JSON() ([]byte, error) {
	jd := new(jsonDiagnostics)
	jd.Version = d.Version.String()
	jd.CipherSuite = d.CipherSuite
	jd.NPN = d.NpnStrings

	return json.Marshal(jd)
}

func (d *Diagnostics) EncodeJSON(w io.Writer) error {
	jd := new(jsonDiagnostics)
	jd.Version = d.Version.String()
	jd.CipherSuite = d.CipherSuite
	jd.NPN = d.NpnStrings

	return json.NewEncoder(w).Encode(jd)
}

type jsonDiagnostics struct {
	Version     string   `json:"version"`
	CipherSuite string   `json:"cipher_suite"`
	NPN         []string `json:"next_protocol_negotiation,omitempty"`
}

type TlsVersion uint16

const (
	TLS_1_0 TlsVersion = 10
	TLS_1_1            = 11
	TLS_1_2            = 12
)

func (t TlsVersion) String() string {
	switch t {
	case TLS_1_0:
		return "1.0"
	case TLS_1_1:
		return "1.1"
	case TLS_1_2:
		return "1.2"
	default:
		return ""
	}
}

func cryptVersTlsToGotak(vers uint16) (TlsVersion, error) {
	switch vers {
	case VersionSSL30, VersionTLS10:
		return TLS_1_0, nil
	case VersionTLS11:
		return TLS_1_1, nil
	case VersionTLS12:
		return TLS_1_2, nil
	default:
		return 0, fmt.Errorf("Error: Could not parse version %d.", vers)
	}
}
<|endoftext|>


<commit_before>package libxml
/*
#include <libxml/xmlversion.h>
#include <libxml/parser.h>
#include <libxml/HTMLparser.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlstring.h>
char* xmlChar2C(xmlChar* x) { return (char *) x; }
xmlNode * NodeNext(xmlNode *node) { return node->next; }
xmlNode * NodeChildren(xmlNode *node) { return node->children; }
int NodeType(xmlNode *node) { return (int)node->type; }
*/
import "C"
import (
//      "unsafe"
//      "os"
)

type XmlNode struct {
  Ptr *C.xmlNode
}

func XmlCheckVersion() int {
  var v C.int
  C.xmlCheckVersion(v)
  return int(v)
}

func XmlCleanUpParser() {
  C.xmlCleanupParser()
}

func BuildXmlNode(ptr *C.xmlNode) *XmlNode {
  if ptr == nil {
    return nil
  }
  return &XmlNode{Ptr: ptr}
}

func HtmlReadFile(url string, encoding string, opts int) *XmlDoc {
  return BuildXmlDoc(C.htmlReadFile( C.CString(url), C.CString(encoding), C.int(opts) ))
}

func HtmlReadDoc(content string, url string, encoding string, opts int) *XmlDoc {
  c := C.xmlCharStrdup( C.CString(content) )
  xmlDocPtr := C.htmlReadDoc( c, C.CString(url), C.CString(encoding), C.int(opts) )
  return &XmlDoc{Ptr: xmlDocPtr}
}

func HtmlReadDocSimple(content string) *XmlDoc {
  return HtmlReadDoc(content, "", "", HTML_PARSE_COMPACT | HTML_PARSE_NOBLANKS |
                                      HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING)
}

func (node *XmlNode) GetProp(name string) string {
  c := C.xmlCharStrdup( C.CString(name) )
  s := C.xmlGetProp(node.Ptr, c)
  return XmlChar2String(s)
}

func XmlChar2String(s *C.xmlChar) string {
  return C.GoString( C.xmlChar2C(s) )
}

func HtmlTagLookup(name string) *C.htmlElemDesc {
  c := C.xmlCharStrdup( C.CString(name) )
  return C.htmlTagLookup(c)
}

func HtmlEntityLookup(name string) *C.htmlEntityDesc {
  c := C.xmlCharStrdup( C.CString(name) )
  return C.htmlEntityLookup(c)
}

func HtmlEntityValueLookup(value uint) *C.htmlEntityDesc {
  return C.htmlEntityValueLookup( C.uint(value) )
}

//Helpers
func (node *XmlNode) Next() *XmlNode { return BuildXmlNode(C.NodeNext(node.Ptr)) }
func (node *XmlNode) Children() *XmlNode { return BuildXmlNode(C.NodeChildren(node.Ptr)) }
func (node *XmlNode) Name() string { return C.GoString( C.xmlChar2C(node.Ptr.name) ) }
func (node *XmlNode) Type() int { return int(C.NodeType(node.Ptr)) }<commit_msg>Imports not required.<commit_after>package libxml
/*
#include <libxml/xmlversion.h>
#include <libxml/parser.h>
#include <libxml/HTMLparser.h>
#include <libxml/HTMLtree.h>
#include <libxml/xmlstring.h>
char* xmlChar2C(xmlChar* x) { return (char *) x; }
xmlNode * NodeNext(xmlNode *node) { return node->next; }
xmlNode * NodeChildren(xmlNode *node) { return node->children; }
int NodeType(xmlNode *node) { return (int)node->type; }
*/
import "C"

type XmlNode struct {
  Ptr *C.xmlNode
}

func XmlCheckVersion() int {
  var v C.int
  C.xmlCheckVersion(v)
  return int(v)
}

func XmlCleanUpParser() {
  C.xmlCleanupParser()
}

func BuildXmlNode(ptr *C.xmlNode) *XmlNode {
  if ptr == nil {
    return nil
  }
  return &XmlNode{Ptr: ptr}
}

func HtmlReadFile(url string, encoding string, opts int) *XmlDoc {
  return BuildXmlDoc(C.htmlReadFile( C.CString(url), C.CString(encoding), C.int(opts) ))
}

func HtmlReadDoc(content string, url string, encoding string, opts int) *XmlDoc {
  c := C.xmlCharStrdup( C.CString(content) )
  xmlDocPtr := C.htmlReadDoc( c, C.CString(url), C.CString(encoding), C.int(opts) )
  return &XmlDoc{Ptr: xmlDocPtr}
}

func HtmlReadDocSimple(content string) *XmlDoc {
  return HtmlReadDoc(content, "", "", HTML_PARSE_COMPACT | HTML_PARSE_NOBLANKS |
                                      HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING)
}

func (node *XmlNode) GetProp(name string) string {
  c := C.xmlCharStrdup( C.CString(name) )
  s := C.xmlGetProp(node.Ptr, c)
  return XmlChar2String(s)
}

func XmlChar2String(s *C.xmlChar) string {
  return C.GoString( C.xmlChar2C(s) )
}

func HtmlTagLookup(name string) *C.htmlElemDesc {
  c := C.xmlCharStrdup( C.CString(name) )
  return C.htmlTagLookup(c)
}

func HtmlEntityLookup(name string) *C.htmlEntityDesc {
  c := C.xmlCharStrdup( C.CString(name) )
  return C.htmlEntityLookup(c)
}

func HtmlEntityValueLookup(value uint) *C.htmlEntityDesc {
  return C.htmlEntityValueLookup( C.uint(value) )
}

//Helpers
func (node *XmlNode) Next() *XmlNode { return BuildXmlNode(C.NodeNext(node.Ptr)) }
func (node *XmlNode) Children() *XmlNode { return BuildXmlNode(C.NodeChildren(node.Ptr)) }
func (node *XmlNode) Name() string { return C.GoString( C.xmlChar2C(node.Ptr.name) ) }
func (node *XmlNode) Type() int { return int(C.NodeType(node.Ptr)) }<|endoftext|>


<commit_before>//
// Reads gccgo AST dumps and performs symbol demangling.
//

package demangler

import (
	"errors"
	"fmt"
	"regexp"
)

var verbctl int = 2

func verb(vlevel int, s string, a ...interface{}) {
	if verbctl >= vlevel {
		fmt.Printf(s, a...)
		fmt.Printf("\n")
	}
}

// Regular expression for an embedded length
var emlenre *regexp.Regexp = regexp.MustCompile(`([0-9]+)[^0-9].*`)

// Get embedded length, return value and num chars it took up
func getemlen(id []byte) (length int, nchars int, err error) {
	// length
	lensl := emlenre.FindSubmatch(id)
	verb(2, "emlenre.FindSubmatch(%s) returns %v", string(id), lensl)

	if len(lensl) != 2 {
		return 0, 0, errors.New("embedded length match failed")
	}
	verb(2, "emlenre digstring is %s", string(lensl[1]))
	nmatched, serr := fmt.Sscanf(string(lensl[1]), "%d", &length)
	if serr != nil {
		return 0, 0, serr
	}
	if nmatched != 1 {
		return 0, 0, errors.New("embedded length scanf failed")
	}
	nchars = len(lensl[1])
	verb(2, "getemlen %s returns l=%d nc=%d", string(id), length, nchars)
	return
}

// A => array (A element [dd]e)
func dem_array(id []byte) (res []byte, consumed int, err error) {
	// element type

	elemt, elemcon, eerr := dem(id[1:])
	if eerr != nil {
		return []byte{}, 0, eerr
	}

	// slice?
	if id[elemcon+1] == 'e' {
		// success
		return []byte(fmt.Sprintf("[]%s", string(elemt))), elemcon + 2, nil
	}

	// length
	arlen, lchars, lerr := getemlen(id[1+elemcon:])
	if lerr != nil {
		return []byte{}, 0, lerr
	}

	// trailing "e"
	if id[elemcon+lchars+1] != 'e' {
		return []byte{}, 0, errors.New("trailing 'e' for array missing")
	}

	// success
	res = []byte(fmt.Sprintf("[%d]%s", arlen, string(elemt)))
	consumed = elemcon + lchars + 2
	err = nil
	return
}

// read <length> _ <name>
func dem_name(id []byte) (res []byte, consumed int, err error) {
	verb(2, "dem_name(%s)", string(id))

	// length
	length, lchars, lerr := getemlen(id)
	if lerr != nil {
		return []byte{}, 0, lerr
	}

	// underscore
	if id[lchars] != '_' {
		return []byte{}, 0, errors.New("named type missing underscore")
	}

	// success
	return id[lchars+1 : lchars+length+1], lchars + length + 1, nil
}

// I => interface (I (method-name method-type) e)
func dem_interface(id []byte) (res []byte, consumed int, err error) {
	idx := 1
	methodnames := make([][]byte, 0, 16)
	methodtypes := make([][]byte, 0, 16)

	for id[idx] != 'e' {

		// method name
		mname, mncons, mnerr := dem_name(id[idx:])
		if mnerr != nil || mncons == 0 {
			return []byte{}, 0, mnerr
		}
		methodnames = append(methodnames, mname)
		idx += mncons

		// method type
		mtype, mtcons, mterr := dem(id[idx:])
		if mterr != nil || mtcons == 0 {
			return []byte{}, 0, mterr
		}
		methodtypes = append(methodtypes, mtype)
		idx += mtcons
	}

	res = make([]byte, 0, idx)
	res = append(res, []byte("interface{")...)
	for i, mn := range methodnames {
		if i != 0 {
			res = append(res, []byte(", ")...)
		}
		res = append(res, mn...)
		res = append(res, []byte(" ")...)
		res = append(res, methodtypes[i]...)
	}
	res = append(res, []byte("}")...)
	return res, idx + 1, nil
}

// F => function (F [m receiver] [p params e] [r results e] e)
func dem_function(id []byte) (res []byte, consumed int, err error) {
	idx := 1

	verb(1, "examining function %s", string(id))

	var receiverType []byte
	for id[idx] == 'm' {
		verb(1, "starting receiver type")

		// receiver
		idx += 1
		rtype, rtcons, rterr := dem(id[idx:])
		if rterr != nil || rtcons == 0 {
			verb(1, "receiver type error %v", rterr)
			return []byte{}, 0, rterr
		}
		receiverType = rtype
		idx += rtcons
	}

	var paramTypes [][]byte
	varargs := ""
	if id[idx] == 'p' {
		verb(1, "starting params")

		// parameters
		idx += 1
		for id[idx] != 'e' {
			ptype, ptcons, pterr := dem(id[idx:])
			if pterr != nil || ptcons == 0 {
				return []byte{}, 0, pterr
			}
			paramTypes = append(paramTypes, ptype)
			idx += ptcons

			verb(1, "ptype %s", string(ptype))

			for id[idx] == 'V' {
				idx += 1
				varargs = "..."
			}
		}
		verb(1, "finished params")
		idx += 1
	}

	var resultTypes [][]byte
	if id[idx] == 'r' {
		verb(1, "starting returns")

		// results
		idx += 1
		for id[idx] != 'e' {
			rtype, rtcons, rterr := dem(id[idx:])
			if rterr != nil || rtcons == 0 {
				return []byte{}, 0, rterr
			}
			resultTypes = append(resultTypes, rtype)
			idx += rtcons
		}
		verb(1, "finished returns")
		idx += 1
	}

	if id[idx] != 'e' {
		return []byte{}, 0, errors.New("func type missing terminator")
	}

	res = make([]byte, 0, idx)
	res = append(res, []byte("func{")...)
	if len(receiverType) > 0 {
		rtclause := []byte(fmt.Sprintf("R(%s) ", string(receiverType)))
		res = append(res, rtclause...)
	}
	res = append(res, []byte("(")...)
	for i, pt := range paramTypes {
		if i != 0 {
			res = append(res, []byte(", ")...)
		}
		res = append(res, pt...)
	}
	res = append(res, []byte(")")...)
	if len(resultTypes) > 0 {
		res = append(res, []byte(" ")...)
		if len(resultTypes) > 1 {
			res = append(res, []byte("(")...)
		}
		for i, rt := range resultTypes {
			if i != 0 {
				res = append(res, []byte(", ")...)
			}
			res = append(res, rt...)
		}
		if len(varargs) > 1 {
			res = append(res, []byte(varargs)...)
		}
		if len(resultTypes) > 1 {
			res = append(res, []byte(")")...)
		}
	}
	res = append(res, []byte("}")...)

	return res, idx + 1, nil

}

// A => array (A element [dd]e)
// b => boolean
// C => channel (C element [s][r]e)
// c => complex (c [a]bits e)
// E => error
// f => float (f [a]bits e)
// F => function (F [m receiver] [p params e] [r results e] e)
// i => integer (i [a][u]bits e)
// I => interface (I (method-name method-type) e)
// M => map (M keytype __ valtype)
// n => nil
// N => named type (N dd_ name)
// p => pointer (p points-to)
// S => struct (S (field-name field-type [T dd_ tag]) e)
// v => void
// V => varargs [varargs-type]
// z => string

var singletons = map[byte]string{
	'E': "error",
	'z': "string",
	'v': "void",
	'b': "boolean",
	'n': "nil",
}

func dem(id []byte) (res []byte, consumed int, err error) {
	verb(1, "=-=-=-=-=\ndem(%s)", string(id))

	if len(id) == 0 {
		return []byte{}, 0, errors.New("premature EOS")
	}
	switch id[0] {
	case 'E', 'z', 'v', 'b', 'n':
		return []byte(singletons[id[0]]), 1, nil
	case 'A':
		// A => array (A element [dd]e)
		return dem_array(id)
	case 'N':
		// N => named type (N dd_ name)
		dres, dcons, derr := dem_name(id[1:])
		if derr != nil {
			verb(2, "name rule failed")
			return []byte{}, 0, derr
		}
		return dres, dcons + 1, nil
	case 'p':
		// p => pointer (p points-to)
		pt, pcon, perr := dem(id[1:])
		if perr != nil {
			verb(1, "ptr rule failed")
			return []byte{}, 0, perr
		}
		return []byte(fmt.Sprintf("*%s", string(pt))), pcon + 1, nil
	case 'I':
		// I => interface (I (method-name method-type) e)
		return dem_interface(id)
	case 'F':
		// F => function (F [m receiver] [p params e] [r results e] e)
		return dem_function(id)
	default:
		msg := fmt.Sprintf("unmatched char %s", string(id[0]))
		return []byte{}, 0, errors.New(msg)
	}
	return []byte{}, 0, errors.New("what happened?")
}

func Demangle(token string) string {
	btoken := []byte(token)
	dtoken, consumed, err := dem(btoken)
	if err != nil {
		dtoken = btoken
	}
	if len(token) != consumed {
		dtoken = btoken
	}

	return string(dtoken)
}

// Regular expression for a go identifier
var idsre *regexp.Regexp = regexp.MustCompile(`[\pL_][\pL\pN_]*`)

func DemangleLine(line string) string {
	bytes := []byte(line)
	m := idsre.FindAllSubmatchIndex(bytes, -1)
	if len(m) == 0 {
		return line
	}
	res := []byte{}
	sslot := 0
	for _, s := range idsre.FindAllSubmatchIndex(bytes, -1) {
		res = append(res, bytes[sslot:s[0]]...)
		identifier := bytes[s[0]:s[1]]
		verb(1, "DemangleLine: dem(%s)", string(identifier))
		dem, consumed, err := dem(identifier)
		if err != nil || len(identifier) != consumed {
			dem = identifier
		}
		res = append(res, dem...)
		sslot = s[1]
	}
	res = append(res, bytes[sslot:len(bytes)]...)
	return string(res)
}
<commit_msg>turn off verb for now<commit_after>//
// Reads gccgo AST dumps and performs symbol demangling.
//

package demangler

import (
	"errors"
	"fmt"
	"regexp"
)

var verbctl int = 0

func verb(vlevel int, s string, a ...interface{}) {
	if verbctl >= vlevel {
		fmt.Printf(s, a...)
		fmt.Printf("\n")
	}
}

// Regular expression for an embedded length
var emlenre *regexp.Regexp = regexp.MustCompile(`([0-9]+)[^0-9].*`)

// Get embedded length, return value and num chars it took up
func getemlen(id []byte) (length int, nchars int, err error) {
	// length
	lensl := emlenre.FindSubmatch(id)
	verb(2, "emlenre.FindSubmatch(%s) returns %v", string(id), lensl)

	if len(lensl) != 2 {
		return 0, 0, errors.New("embedded length match failed")
	}
	verb(2, "emlenre digstring is %s", string(lensl[1]))
	nmatched, serr := fmt.Sscanf(string(lensl[1]), "%d", &length)
	if serr != nil {
		return 0, 0, serr
	}
	if nmatched != 1 {
		return 0, 0, errors.New("embedded length scanf failed")
	}
	nchars = len(lensl[1])
	verb(2, "getemlen %s returns l=%d nc=%d", string(id), length, nchars)
	return
}

// A => array (A element [dd]e)
func dem_array(id []byte) (res []byte, consumed int, err error) {
	// element type

	elemt, elemcon, eerr := dem(id[1:])
	if eerr != nil {
		return []byte{}, 0, eerr
	}

	// slice?
	if id[elemcon+1] == 'e' {
		// success
		return []byte(fmt.Sprintf("[]%s", string(elemt))), elemcon + 2, nil
	}

	// length
	arlen, lchars, lerr := getemlen(id[1+elemcon:])
	if lerr != nil {
		return []byte{}, 0, lerr
	}

	// trailing "e"
	if id[elemcon+lchars+1] != 'e' {
		return []byte{}, 0, errors.New("trailing 'e' for array missing")
	}

	// success
	res = []byte(fmt.Sprintf("[%d]%s", arlen, string(elemt)))
	consumed = elemcon + lchars + 2
	err = nil
	return
}

// read <length> _ <name>
func dem_name(id []byte) (res []byte, consumed int, err error) {
	verb(2, "dem_name(%s)", string(id))

	// length
	length, lchars, lerr := getemlen(id)
	if lerr != nil {
		return []byte{}, 0, lerr
	}

	// underscore
	if id[lchars] != '_' {
		return []byte{}, 0, errors.New("named type missing underscore")
	}

	// success
	return id[lchars+1 : lchars+length+1], lchars + length + 1, nil
}

// I => interface (I (method-name method-type) e)
func dem_interface(id []byte) (res []byte, consumed int, err error) {
	idx := 1
	methodnames := make([][]byte, 0, 16)
	methodtypes := make([][]byte, 0, 16)

	for id[idx] != 'e' {

		// method name
		mname, mncons, mnerr := dem_name(id[idx:])
		if mnerr != nil || mncons == 0 {
			return []byte{}, 0, mnerr
		}
		methodnames = append(methodnames, mname)
		idx += mncons

		// method type
		mtype, mtcons, mterr := dem(id[idx:])
		if mterr != nil || mtcons == 0 {
			return []byte{}, 0, mterr
		}
		methodtypes = append(methodtypes, mtype)
		idx += mtcons
	}

	res = make([]byte, 0, idx)
	res = append(res, []byte("interface{")...)
	for i, mn := range methodnames {
		if i != 0 {
			res = append(res, []byte(", ")...)
		}
		res = append(res, mn...)
		res = append(res, []byte(" ")...)
		res = append(res, methodtypes[i]...)
	}
	res = append(res, []byte("}")...)
	return res, idx + 1, nil
}

// F => function (F [m receiver] [p params e] [r results e] e)
func dem_function(id []byte) (res []byte, consumed int, err error) {
	idx := 1

	verb(1, "examining function %s", string(id))

	var receiverType []byte
	for id[idx] == 'm' {
		verb(1, "starting receiver type")

		// receiver
		idx += 1
		rtype, rtcons, rterr := dem(id[idx:])
		if rterr != nil || rtcons == 0 {
			verb(1, "receiver type error %v", rterr)
			return []byte{}, 0, rterr
		}
		receiverType = rtype
		idx += rtcons
	}

	var paramTypes [][]byte
	varargs := ""
	if id[idx] == 'p' {
		verb(1, "starting params")

		// parameters
		idx += 1
		for id[idx] != 'e' {
			ptype, ptcons, pterr := dem(id[idx:])
			if pterr != nil || ptcons == 0 {
				return []byte{}, 0, pterr
			}
			paramTypes = append(paramTypes, ptype)
			idx += ptcons

			verb(1, "ptype %s", string(ptype))

			for id[idx] == 'V' {
				idx += 1
				varargs = "..."
			}
		}
		verb(1, "finished params")
		idx += 1
	}

	var resultTypes [][]byte
	if id[idx] == 'r' {
		verb(1, "starting returns")

		// results
		idx += 1
		for id[idx] != 'e' {
			rtype, rtcons, rterr := dem(id[idx:])
			if rterr != nil || rtcons == 0 {
				return []byte{}, 0, rterr
			}
			resultTypes = append(resultTypes, rtype)
			idx += rtcons
		}
		verb(1, "finished returns")
		idx += 1
	}

	if id[idx] != 'e' {
		return []byte{}, 0, errors.New("func type missing terminator")
	}

	res = make([]byte, 0, idx)
	res = append(res, []byte("func{")...)
	if len(receiverType) > 0 {
		rtclause := []byte(fmt.Sprintf("R(%s) ", string(receiverType)))
		res = append(res, rtclause...)
	}
	res = append(res, []byte("(")...)
	for i, pt := range paramTypes {
		if i != 0 {
			res = append(res, []byte(", ")...)
		}
		res = append(res, pt...)
	}
	res = append(res, []byte(")")...)
	if len(resultTypes) > 0 {
		res = append(res, []byte(" ")...)
		if len(resultTypes) > 1 {
			res = append(res, []byte("(")...)
		}
		for i, rt := range resultTypes {
			if i != 0 {
				res = append(res, []byte(", ")...)
			}
			res = append(res, rt...)
		}
		if len(varargs) > 1 {
			res = append(res, []byte(varargs)...)
		}
		if len(resultTypes) > 1 {
			res = append(res, []byte(")")...)
		}
	}
	res = append(res, []byte("}")...)

	return res, idx + 1, nil

}

// A => array (A element [dd]e)
// b => boolean
// C => channel (C element [s][r]e)
// c => complex (c [a]bits e)
// E => error
// f => float (f [a]bits e)
// F => function (F [m receiver] [p params e] [r results e] e)
// i => integer (i [a][u]bits e)
// I => interface (I (method-name method-type) e)
// M => map (M keytype __ valtype)
// n => nil
// N => named type (N dd_ name)
// p => pointer (p points-to)
// S => struct (S (field-name field-type [T dd_ tag]) e)
// v => void
// V => varargs [varargs-type]
// z => string

var singletons = map[byte]string{
	'E': "error",
	'z': "string",
	'v': "void",
	'b': "boolean",
	'n': "nil",
}

func dem(id []byte) (res []byte, consumed int, err error) {
	verb(1, "=-=-=-=-=\ndem(%s)", string(id))

	if len(id) == 0 {
		return []byte{}, 0, errors.New("premature EOS")
	}
	switch id[0] {
	case 'E', 'z', 'v', 'b', 'n':
		return []byte(singletons[id[0]]), 1, nil
	case 'A':
		// A => array (A element [dd]e)
		return dem_array(id)
	case 'N':
		// N => named type (N dd_ name)
		dres, dcons, derr := dem_name(id[1:])
		if derr != nil {
			verb(2, "name rule failed")
			return []byte{}, 0, derr
		}
		return dres, dcons + 1, nil
	case 'p':
		// p => pointer (p points-to)
		pt, pcon, perr := dem(id[1:])
		if perr != nil {
			verb(1, "ptr rule failed")
			return []byte{}, 0, perr
		}
		return []byte(fmt.Sprintf("*%s", string(pt))), pcon + 1, nil
	case 'I':
		// I => interface (I (method-name method-type) e)
		return dem_interface(id)
	case 'F':
		// F => function (F [m receiver] [p params e] [r results e] e)
		return dem_function(id)
	default:
		msg := fmt.Sprintf("unmatched char %s", string(id[0]))
		return []byte{}, 0, errors.New(msg)
	}
	return []byte{}, 0, errors.New("what happened?")
}

func Demangle(token string) string {
	btoken := []byte(token)
	dtoken, consumed, err := dem(btoken)
	if err != nil {
		dtoken = btoken
	}
	if len(token) != consumed {
		dtoken = btoken
	}

	return string(dtoken)
}

// Regular expression for a go identifier
var idsre *regexp.Regexp = regexp.MustCompile(`[\pL_][\pL\pN_]*`)

func DemangleLine(line string) string {
	bytes := []byte(line)
	m := idsre.FindAllSubmatchIndex(bytes, -1)
	if len(m) == 0 {
		return line
	}
	res := []byte{}
	sslot := 0
	for _, s := range idsre.FindAllSubmatchIndex(bytes, -1) {
		res = append(res, bytes[sslot:s[0]]...)
		identifier := bytes[s[0]:s[1]]
		verb(1, "DemangleLine: dem(%s)", string(identifier))
		dem, consumed, err := dem(identifier)
		if err != nil || len(identifier) != consumed {
			dem = identifier
		}
		res = append(res, dem...)
		sslot = s[1]
	}
	res = append(res, bytes[sslot:len(bytes)]...)
	return string(res)
}
<|endoftext|>


<commit_before>package controllers

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/eirka/eirka-libs/audit"
	"github.com/eirka/eirka-libs/config"
	"github.com/eirka/eirka-libs/db"

	local "github.com/eirka/eirka-post/config"
)

func init() {

	// Database connection settings
	dbase := db.Database{

		User:           local.Settings.Database.User,
		Password:       local.Settings.Database.Password,
		Proto:          local.Settings.Database.Proto,
		Host:           local.Settings.Database.Host,
		Database:       local.Settings.Database.Database,
		MaxIdle:        local.Settings.Database.MaxIdle,
		MaxConnections: local.Settings.Database.MaxConnections,
	}

	// Set up DB connection
	dbase.NewDb()

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

}

func performJsonRequest(r http.Handler, method, path string, body []byte) *httptest.ResponseRecorder {
	req, _ := http.NewRequest(method, path, bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req)
	return w
}

func TestAddTagController(t *testing.T) {

	gin.SetMode(gin.ReleaseMode)

	router := gin.New()

	router.POST("/tag/add", AddTagController)

	first := performRequest(router, "POST", "/tag/add")

	assert.Equal(t, first.Code, 400, "HTTP request code should match")

	request1 := []byte(`{"ib": 1, "tag": 1, "image": 1}`)

	second := performJsonRequest(router, "POST", "/email", request1)

	assert.Equal(t, second.Code, 200, "HTTP request code should match")
	assert.JSONEq(t, second.Body.String(), fmt.Sprintf("{\"success_message\": \"%s\"}", audit.AuditAddTag), "HTTP response should match")

}
<commit_msg>add add tag test<commit_after>package controllers

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/eirka/eirka-libs/audit"
	"github.com/eirka/eirka-libs/config"
	"github.com/eirka/eirka-libs/db"

	local "github.com/eirka/eirka-post/config"
)

func init() {

	// Database connection settings
	dbase := db.Database{

		User:           local.Settings.Database.User,
		Password:       local.Settings.Database.Password,
		Proto:          local.Settings.Database.Proto,
		Host:           local.Settings.Database.Host,
		Database:       local.Settings.Database.Database,
		MaxIdle:        local.Settings.Database.MaxIdle,
		MaxConnections: local.Settings.Database.MaxConnections,
	}

	// Set up DB connection
	dbase.NewDb()

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

}

func performJsonRequest(r http.Handler, method, path string, body []byte) *httptest.ResponseRecorder {
	req, _ := http.NewRequest(method, path, bytes.NewBuffer(body))
	req.Header.Set("Content-Type", "application/json")
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req)
	return w
}

func TestAddTagController(t *testing.T) {

	gin.SetMode(gin.ReleaseMode)

	router := gin.New()

	router.Use(user.Auth(false))

	router.POST("/tag/add", AddTagController)

	first := performRequest(router, "POST", "/tag/add")

	assert.Equal(t, first.Code, 400, "HTTP request code should match")

	request1 := []byte(`{"ib": 1, "tag": 1, "image": 1}`)

	second := performJsonRequest(router, "POST", "/email", request1)

	assert.Equal(t, second.Code, 200, "HTTP request code should match")
	assert.JSONEq(t, second.Body.String(), fmt.Sprintf("{\"success_message\": \"%s\"}", audit.AuditAddTag), "HTTP response should match")

}
<|endoftext|>


<commit_before>package controllers

import (
"encoding/json"
"net/http"

"github.com/vonji/vonji-api/services"
"github.com/vonji/vonji-api/utils"
"github.com/vonji/vonji-api/models"
	"github.com/gorilla/mux"
)

type TransactionController struct {
	APIBaseController
}

func (ctrl TransactionController) GetAll() (interface{}, *utils.HttpError) {
	return services.Transaction.GetAll(), nil
}

func (ctrl TransactionController) GetOne(id uint) (interface{}, *utils.HttpError) {
	return services.Transaction.GetOne(id), nil
}

func (ctrl TransactionController) GetOneWhere(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	transaction := models.Transaction{}

	if err := json.Unmarshal([]byte(mux.Vars(r)["condition"]), &transaction); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	return *services.Transaction.GetOneWhere(&transaction), nil
}

func (ctrl TransactionController) GetAllWhere(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	transaction := models.Transaction{}

	if err := json.Unmarshal([]byte(mux.Vars(r)["condition"]), &transaction); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	return services.Transaction.GetAllWhere(&transaction), nil
}

func (ctrl TransactionController) Create(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	transaction := &models.Transaction{}

	if err := json.NewDecoder(r.Body).Decode(transaction); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	if transaction = services.Transaction.Create(transaction); transaction == nil {
		return nil, nil
	}

	if transaction.Type == "VACTION" {
		transaction.To.VAction += transaction.Amount
		services.User.Update(&transaction.To)
	} else if transaction.Type == "VCOINS" {
		transaction.From.VCoins -= transaction.Amount//TODO check if enough coins
		transaction.To.VCoins += transaction.Amount
		services.User.Update(&transaction.From)
		services.User.Update(&transaction.To)
	}

	return services.Transaction.GetOne(transaction.ID), nil
}

func (ctrl TransactionController) Update(w http.ResponseWriter, r *http.Request) *utils.HttpError {
	transaction := models.Transaction{}

	if err := json.NewDecoder(r.Body).Decode(&transaction); err != nil {
		return utils.BadRequest(err.Error())
	}

	services.Transaction.Update(&transaction)

	return nil
}

func (ctrl TransactionController) Delete(id uint) *utils.HttpError {
	services.Transaction.Delete(id)
	return nil
}

<commit_msg>Fix transactions<commit_after>package controllers

import (
"encoding/json"
"net/http"

"github.com/vonji/vonji-api/services"
"github.com/vonji/vonji-api/utils"
"github.com/vonji/vonji-api/models"
	"github.com/gorilla/mux"
)

type TransactionController struct {
	APIBaseController
}

func (ctrl TransactionController) GetAll() (interface{}, *utils.HttpError) {
	return services.Transaction.GetAll(), nil
}

func (ctrl TransactionController) GetOne(id uint) (interface{}, *utils.HttpError) {
	return services.Transaction.GetOne(id), nil
}

func (ctrl TransactionController) GetOneWhere(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	transaction := models.Transaction{}

	if err := json.Unmarshal([]byte(mux.Vars(r)["condition"]), &transaction); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	return *services.Transaction.GetOneWhere(&transaction), nil
}

func (ctrl TransactionController) GetAllWhere(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	transaction := models.Transaction{}

	if err := json.Unmarshal([]byte(mux.Vars(r)["condition"]), &transaction); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	return services.Transaction.GetAllWhere(&transaction), nil
}

func (ctrl TransactionController) Create(w http.ResponseWriter, r *http.Request) (interface{}, *utils.HttpError) {
	transaction := &models.Transaction{}

	if err := json.NewDecoder(r.Body).Decode(transaction); err != nil {
		return nil, utils.BadRequest(err.Error())
	}

	if transaction = services.Transaction.Create(transaction); transaction == nil {
		return nil, nil
	}

	if transaction.Type == "VACTION" {
		transaction.To.VAction += transaction.Amount
		services.User.Update(&transaction.To)
	} else if transaction.Type == "VCOIN" {
		transaction.From.VCoins -= transaction.Amount//TODO check if enough coins
		transaction.To.VCoins += transaction.Amount
		services.User.Update(&transaction.From)
		services.User.Update(&transaction.To)
	}

	return services.Transaction.GetOne(transaction.ID), nil
}

func (ctrl TransactionController) Update(w http.ResponseWriter, r *http.Request) *utils.HttpError {
	transaction := models.Transaction{}

	if err := json.NewDecoder(r.Body).Decode(&transaction); err != nil {
		return utils.BadRequest(err.Error())
	}

	services.Transaction.Update(&transaction)

	return nil
}

func (ctrl TransactionController) Delete(id uint) *utils.HttpError {
	services.Transaction.Delete(id)
	return nil
}

<|endoftext|>


<commit_before>package commands

import (
	"bytes"
	"errors"
	"io"
	"sort"

	cmds "github.com/ipfs/go-ipfs/commands"
	repo "github.com/ipfs/go-ipfs/repo"
	config "github.com/ipfs/go-ipfs/repo/config"
	"github.com/ipfs/go-ipfs/repo/fsrepo"
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
)

type BootstrapOutput struct {
	Peers []string
}

var peerOptionDesc = "A peer to add to the bootstrap list (in the format '<multiaddr>/<peerID>')"

var BootstrapCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Show or edit the list of bootstrap peers.",
		ShortDescription: `
Running 'ipfs bootstrap' with no arguments will run 'ipfs bootstrap list'.
` + bootstrapSecurityWarning,
	},

	Run:        bootstrapListCmd.Run,
	Marshalers: bootstrapListCmd.Marshalers,
	Type:       bootstrapListCmd.Type,

	Subcommands: map[string]*cmds.Command{
		"list": bootstrapListCmd,
		"add":  bootstrapAddCmd,
		"rm":   bootstrapRemoveCmd,
	},
}

var bootstrapAddCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Add peers to the bootstrap list.",
		ShortDescription: `Outputs a list of peers that were added (that weren't already
in the bootstrap list).
` + bootstrapSecurityWarning,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("peer", false, true, peerOptionDesc).EnableStdin(),
	},

	Options: []cmds.Option{
		cmds.BoolOption("default", "Add default bootstrap nodes.").Default(false),
	},

	Run: func(req cmds.Request, res cmds.Response) {
		deflt, _, err := req.Option("default").Bool()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		var inputPeers []config.BootstrapPeer
		if deflt {
			// parse separately for meaningful, correct error.
			defltPeers, err := config.DefaultBootstrapPeers()
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			inputPeers = defltPeers
		} else {
			parsedPeers, err := config.ParseBootstrapPeers(req.Arguments())
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			inputPeers = parsedPeers
		}

		if len(inputPeers) == 0 {
			res.SetError(errors.New("no bootstrap peers to add"), cmds.ErrClient)
			return
		}

		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		added, err := bootstrapAdd(r, cfg, inputPeers)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(added)})
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, ok := res.Output().(*BootstrapOutput)
			if !ok {
				return nil, u.ErrCast()
			}

			buf := new(bytes.Buffer)
			if err := bootstrapWritePeers(buf, "added ", v.Peers); err != nil {
				return nil, err
			}

			return buf, nil
		},
	},
}

var bootstrapRemoveCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Removes peers from the bootstrap list.",
		ShortDescription: `Outputs the list of peers that were removed.
` + bootstrapSecurityWarning,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("peer", false, true, peerOptionDesc).EnableStdin(),
	},
	Options: []cmds.Option{
		cmds.BoolOption("all", "Remove all bootstrap peers.").Default(false),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		all, _, err := req.Option("all").Bool()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		var removed []config.BootstrapPeer
		if all {
			removed, err = bootstrapRemoveAll(r, cfg)
		} else {
			input, perr := config.ParseBootstrapPeers(req.Arguments())
			if perr != nil {
				res.SetError(perr, cmds.ErrNormal)
				return
			}

			removed, err = bootstrapRemove(r, cfg, input)
		}
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(removed)})
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, ok := res.Output().(*BootstrapOutput)
			if !ok {
				return nil, u.ErrCast()
			}

			buf := new(bytes.Buffer)
			err := bootstrapWritePeers(buf, "removed ", v.Peers)
			return buf, err
		},
	},
}

var bootstrapListCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline:          "Show peers in the bootstrap list.",
		ShortDescription: "Peers are output in the format '<multiaddr>/<peerID>'.",
	},

	Run: func(req cmds.Request, res cmds.Response) {
		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		peers, err := cfg.BootstrapPeers()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(peers)})
		return
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: bootstrapMarshaler,
	},
}

func bootstrapMarshaler(res cmds.Response) (io.Reader, error) {
	v, ok := res.Output().(*BootstrapOutput)
	if !ok {
		return nil, u.ErrCast()
	}

	buf := new(bytes.Buffer)
	err := bootstrapWritePeers(buf, "", v.Peers)
	return buf, err
}

func bootstrapWritePeers(w io.Writer, prefix string, peers []string) error {

	sort.Stable(sort.StringSlice(peers))
	for _, peer := range peers {
		_, err := w.Write([]byte(peer + "\n"))
		if err != nil {
			return err
		}
	}
	return nil
}

func bootstrapAdd(r repo.Repo, cfg *config.Config, peers []config.BootstrapPeer) ([]config.BootstrapPeer, error) {
	addedMap := map[string]struct{}{}
	addedList := make([]config.BootstrapPeer, 0, len(peers))

	// re-add cfg bootstrap peers to rm dupes
	bpeers := cfg.Bootstrap
	cfg.Bootstrap = nil

	// add new peers
	for _, peer := range peers {
		s := peer.String()
		if _, found := addedMap[s]; found {
			continue
		}

		cfg.Bootstrap = append(cfg.Bootstrap, s)
		addedList = append(addedList, peer)
		addedMap[s] = struct{}{}
	}

	// add back original peers. in this order so that we output them.
	for _, s := range bpeers {
		if _, found := addedMap[s]; found {
			continue
		}

		cfg.Bootstrap = append(cfg.Bootstrap, s)
		addedMap[s] = struct{}{}
	}

	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return addedList, nil
}

func bootstrapRemove(r repo.Repo, cfg *config.Config, toRemove []config.BootstrapPeer) ([]config.BootstrapPeer, error) {
	removed := make([]config.BootstrapPeer, 0, len(toRemove))
	keep := make([]config.BootstrapPeer, 0, len(cfg.Bootstrap))

	peers, err := cfg.BootstrapPeers()
	if err != nil {
		return nil, err
	}

	for _, peer := range peers {
		found := false
		for _, peer2 := range toRemove {
			if peer.Equal(peer2) {
				found = true
				removed = append(removed, peer)
				break
			}
		}

		if !found {
			keep = append(keep, peer)
		}
	}
	cfg.SetBootstrapPeers(keep)

	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return removed, nil
}

func bootstrapRemoveAll(r repo.Repo, cfg *config.Config) ([]config.BootstrapPeer, error) {
	removed, err := cfg.BootstrapPeers()
	if err != nil {
		return nil, err
	}

	cfg.Bootstrap = nil
	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return removed, nil
}

const bootstrapSecurityWarning = `
SECURITY WARNING:

The bootstrap command manipulates the "bootstrap list", which contains
the addresses of bootstrap nodes. These are the *trusted peers* from
which to learn about other peers in the network. Only edit this list
if you understand the risks of adding or removing nodes from this list.

`
<commit_msg>add bootstrap add-default and rm-all subcommands to deprecate flags<commit_after>package commands

import (
	"bytes"
	"errors"
	"io"
	"sort"

	cmds "github.com/ipfs/go-ipfs/commands"
	repo "github.com/ipfs/go-ipfs/repo"
	config "github.com/ipfs/go-ipfs/repo/config"
	"github.com/ipfs/go-ipfs/repo/fsrepo"
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
)

type BootstrapOutput struct {
	Peers []string
}

var peerOptionDesc = "A peer to add to the bootstrap list (in the format '<multiaddr>/<peerID>')"

var BootstrapCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Show or edit the list of bootstrap peers.",
		ShortDescription: `
Running 'ipfs bootstrap' with no arguments will run 'ipfs bootstrap list'.
` + bootstrapSecurityWarning,
	},

	Run:        bootstrapListCmd.Run,
	Marshalers: bootstrapListCmd.Marshalers,
	Type:       bootstrapListCmd.Type,

	Subcommands: map[string]*cmds.Command{
		"list": bootstrapListCmd,
		"add":  bootstrapAddCmd,
		"rm":   bootstrapRemoveCmd,
	},
}

var bootstrapAddCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Add peers to the bootstrap list.",
		ShortDescription: `Outputs a list of peers that were added (that weren't already
in the bootstrap list).
` + bootstrapSecurityWarning,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("peer", false, true, peerOptionDesc).EnableStdin(),
	},

	Options: []cmds.Option{
		cmds.BoolOption("default", "Add default bootstrap nodes. (Deprecated, use 'default' subcommand instead)"),
	},
	Subcommands: map[string]*cmds.Command{
		"default": bootstrapAddDefaultCmd,
	},

	Run: func(req cmds.Request, res cmds.Response) {
		deflt, _, err := req.Option("default").Bool()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		var inputPeers []config.BootstrapPeer
		if deflt {
			// parse separately for meaningful, correct error.
			defltPeers, err := config.DefaultBootstrapPeers()
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			inputPeers = defltPeers
		} else {
			parsedPeers, err := config.ParseBootstrapPeers(req.Arguments())
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			inputPeers = parsedPeers
		}

		if len(inputPeers) == 0 {
			res.SetError(errors.New("no bootstrap peers to add"), cmds.ErrClient)
			return
		}

		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		added, err := bootstrapAdd(r, cfg, inputPeers)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(added)})
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, ok := res.Output().(*BootstrapOutput)
			if !ok {
				return nil, u.ErrCast()
			}

			buf := new(bytes.Buffer)
			if err := bootstrapWritePeers(buf, "added ", v.Peers); err != nil {
				return nil, err
			}

			return buf, nil
		},
	},
}

var bootstrapAddDefaultCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Add default peers to the bootstrap list.",
		ShortDescription: `Outputs a list of peers that were added (that weren't already
in the bootstrap list).`,
	},
	Run: func(req cmds.Request, res cmds.Response) {
		defltPeers, err := config.DefaultBootstrapPeers()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		added, err := bootstrapAdd(r, cfg, defltPeers)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(added)})
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, ok := res.Output().(*BootstrapOutput)
			if !ok {
				return nil, u.ErrCast()
			}

			buf := new(bytes.Buffer)
			if err := bootstrapWritePeers(buf, "added ", v.Peers); err != nil {
				return nil, err
			}

			return buf, nil
		},
	},
}

var bootstrapRemoveCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Removes peers from the bootstrap list.",
		ShortDescription: `Outputs the list of peers that were removed.
` + bootstrapSecurityWarning,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("peer", false, true, peerOptionDesc).EnableStdin(),
	},
	Options: []cmds.Option{
		cmds.BoolOption("all", "Remove all bootstrap peers. (Deprecated, use 'all' subcommand)"),
	},
	Subcommands: map[string]*cmds.Command{
		"all": bootstrapRemoveAllCmd,
	},
	Run: func(req cmds.Request, res cmds.Response) {
		all, _, err := req.Option("all").Bool()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		var removed []config.BootstrapPeer
		if all {
			removed, err = bootstrapRemoveAll(r, cfg)
		} else {
			input, perr := config.ParseBootstrapPeers(req.Arguments())
			if perr != nil {
				res.SetError(perr, cmds.ErrNormal)
				return
			}

			removed, err = bootstrapRemove(r, cfg, input)
		}
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(removed)})
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, ok := res.Output().(*BootstrapOutput)
			if !ok {
				return nil, u.ErrCast()
			}

			buf := new(bytes.Buffer)
			err := bootstrapWritePeers(buf, "removed ", v.Peers)
			return buf, err
		},
	},
}

var bootstrapRemoveAllCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline:          "Removes all peers from the bootstrap list.",
		ShortDescription: `Outputs the list of peers that were removed.`,
	},

	Run: func(req cmds.Request, res cmds.Response) {
		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		removed, err := bootstrapRemoveAll(r, cfg)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(removed)})
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			v, ok := res.Output().(*BootstrapOutput)
			if !ok {
				return nil, u.ErrCast()
			}

			buf := new(bytes.Buffer)
			err := bootstrapWritePeers(buf, "removed ", v.Peers)
			return buf, err
		},
	},
}

var bootstrapListCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline:          "Show peers in the bootstrap list.",
		ShortDescription: "Peers are output in the format '<multiaddr>/<peerID>'.",
	},

	Run: func(req cmds.Request, res cmds.Response) {
		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		peers, err := cfg.BootstrapPeers()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(&BootstrapOutput{config.BootstrapPeerStrings(peers)})
		return
	},
	Type: BootstrapOutput{},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: bootstrapMarshaler,
	},
}

func bootstrapMarshaler(res cmds.Response) (io.Reader, error) {
	v, ok := res.Output().(*BootstrapOutput)
	if !ok {
		return nil, u.ErrCast()
	}

	buf := new(bytes.Buffer)
	err := bootstrapWritePeers(buf, "", v.Peers)
	return buf, err
}

func bootstrapWritePeers(w io.Writer, prefix string, peers []string) error {

	sort.Stable(sort.StringSlice(peers))
	for _, peer := range peers {
		_, err := w.Write([]byte(peer + "\n"))
		if err != nil {
			return err
		}
	}
	return nil
}

func bootstrapAdd(r repo.Repo, cfg *config.Config, peers []config.BootstrapPeer) ([]config.BootstrapPeer, error) {
	addedMap := map[string]struct{}{}
	addedList := make([]config.BootstrapPeer, 0, len(peers))

	// re-add cfg bootstrap peers to rm dupes
	bpeers := cfg.Bootstrap
	cfg.Bootstrap = nil

	// add new peers
	for _, peer := range peers {
		s := peer.String()
		if _, found := addedMap[s]; found {
			continue
		}

		cfg.Bootstrap = append(cfg.Bootstrap, s)
		addedList = append(addedList, peer)
		addedMap[s] = struct{}{}
	}

	// add back original peers. in this order so that we output them.
	for _, s := range bpeers {
		if _, found := addedMap[s]; found {
			continue
		}

		cfg.Bootstrap = append(cfg.Bootstrap, s)
		addedMap[s] = struct{}{}
	}

	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return addedList, nil
}

func bootstrapRemove(r repo.Repo, cfg *config.Config, toRemove []config.BootstrapPeer) ([]config.BootstrapPeer, error) {
	removed := make([]config.BootstrapPeer, 0, len(toRemove))
	keep := make([]config.BootstrapPeer, 0, len(cfg.Bootstrap))

	peers, err := cfg.BootstrapPeers()
	if err != nil {
		return nil, err
	}

	for _, peer := range peers {
		found := false
		for _, peer2 := range toRemove {
			if peer.Equal(peer2) {
				found = true
				removed = append(removed, peer)
				break
			}
		}

		if !found {
			keep = append(keep, peer)
		}
	}
	cfg.SetBootstrapPeers(keep)

	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return removed, nil
}

func bootstrapRemoveAll(r repo.Repo, cfg *config.Config) ([]config.BootstrapPeer, error) {
	removed, err := cfg.BootstrapPeers()
	if err != nil {
		return nil, err
	}

	cfg.Bootstrap = nil
	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return removed, nil
}

const bootstrapSecurityWarning = `
SECURITY WARNING:

The bootstrap command manipulates the "bootstrap list", which contains
the addresses of bootstrap nodes. These are the *trusted peers* from
which to learn about other peers in the network. Only edit this list
if you understand the risks of adding or removing nodes from this list.

`
<|endoftext|>


<commit_before>package state

import (
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/txn"
	"strings"
)

// annotatorDoc represents the internal state of annotations for an Entity in
// MongoDB. Note that the annotations map is not maintained in local storage
// due to the fact that it is not accessed directly, but through
// Annotations/Annotation below.
type annotatorDoc struct {
	GlobalKey   string `bson:"_id"`
	EntityName  string
	Annotations map[string]string
}

// annotator stores information required to query MongoDB.
type annotator struct {
	globalKey  string
	entityName string
	st         *State
}

// SetAnnotations adds key/value pairs to annotations in MongoDB.
func (a *annotator) SetAnnotations(pairs map[string]string) error {
	if len(pairs) == 0 {
		return nil
	}
	// Collect in separate maps pairs to be inserted/updated or removed.
	toRemove := make(map[string]bool)
	toInsert := make(map[string]string)
	toUpdate := make(map[string]string)
	for key, value := range pairs {
		if strings.Contains(key, ".") {
			return fmt.Errorf("invalid key %q", key)
		}
		if value == "" {
			toRemove["annotations."+key] = true
		} else {
			toInsert[key] = value
			toUpdate["annotations."+key] = value
		}
	}
	id := a.globalKey
	coll := a.st.annotations.Name
	var ops []txn.Op

	if count, err := a.st.annotations.FindId(id).Count(); err != nil {
		return err
	} else if count == 0 {
		// The document is missing: no need to remove pairs.
		// Insert pairs if required.
		if len(toInsert) == 0 {
			return nil
		}
		insertOp := txn.Op{
			C:      coll,
			Id:     id,
			Assert: txn.DocMissing,
			Insert: &annotatorDoc{id, a.entityName, toInsert},
		}
		ops = append(ops, insertOp)
	} else {
		// The document exists.
		if len(toRemove) != 0 {
			// Remove pairs.
			removeOp := txn.Op{
				C:      coll,
				Id:     id,
				Assert: txn.DocExists,
				Update: D{{"$unset", toRemove}},
			}
			ops = append(ops, removeOp)
		}
		if len(toUpdate) != 0 {
			// Insert/update pairs.
			updateOp := txn.Op{
				C:      coll,
				Id:     id,
				Assert: txn.DocExists,
				Update: D{{"$set", toUpdate}},
			}
			ops = append(ops, updateOp)
		}
	}
	if len(ops) == 0 {
		return nil
	}
	if err := a.st.runner.Run(ops, "", nil); err != nil {
		return fmt.Errorf("cannot update annotations on %s: %v", id, err)
	}
	return nil
}

// Annotations returns all the annotations corresponding to an entity.
func (a annotator) Annotations() (map[string]string, error) {
	doc := new(annotatorDoc)
	err := a.st.annotations.FindId(a.globalKey).One(doc)
	if err == mgo.ErrNotFound {
		// Returning an empty map if there are no annotations.
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return doc.Annotations, nil
}

// Annotation returns the annotation value corresponding to the given key.
// If the requested annotation is not found, an empty string is returned.
func (a annotator) Annotation(key string) (string, error) {
	ann, err := a.Annotations()
	if err != nil {
		return "", err
	}
	return ann[key], nil
}

// annotationRemoveOp returns an operation to remove a given annotation
// document from MongoDB.
func annotationRemoveOp(st *State, id string) txn.Op {
	return txn.Op{
		C:      st.annotations.Name,
		Id:     id,
		Remove: true,
	}
}
<commit_msg>Checkpoint.<commit_after>package state

import (
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/txn"
	"strings"
)

// annotatorDoc represents the internal state of annotations for an Entity in
// MongoDB. Note that the annotations map is not maintained in local storage
// due to the fact that it is not accessed directly, but through
// Annotations/Annotation below.
type annotatorDoc struct {
	GlobalKey   string `bson:"_id"`
	EntityName  string
	Annotations map[string]string
}

// annotator stores information required to query MongoDB.
type annotator struct {
	globalKey  string
	entityName string
	st         *State
}

// SetAnnotations adds key/value pairs to annotations in MongoDB.
func (a *annotator) SetAnnotations(pairs map[string]string) error {
	if len(pairs) == 0 {
		return nil
	}
	// Collect in separate maps pairs to be inserted/updated or removed.
	toRemove := make(map[string]bool)
	toInsert := make(map[string]string)
	toUpdate := make(map[string]string)
	for key, value := range pairs {
		if strings.Contains(key, ".") {
			return fmt.Errorf("invalid key %q", key)
		}
		if value == "" {
			toRemove["annotations."+key] = true
		} else {
			toInsert[key] = value
			toUpdate["annotations."+key] = value
		}
	}
	id := a.globalKey
	coll := a.st.annotations.Name
	var ops []txn.Op

	if count, err := a.st.annotations.FindId(id).Count(); err != nil {
		return err
	} else if count == 0 {
		// The document is missing: no need to remove pairs.
		// Insert pairs if required.
		if len(toInsert) == 0 {
			return nil
		}
		insertOp := txn.Op{
			C:      coll,
			Id:     id,
			Assert: txn.DocMissing,
			Insert: &annotatorDoc{id, a.entityName, toInsert},
		}
		ops = append(ops, insertOp)
	} else {
		// The document exists.
		if len(toRemove) != 0 {
			// Remove pairs.
			removeOp := txn.Op{
				C:      coll,
				Id:     id,
				Assert: txn.DocExists,
				Update: D{{"$unset", toRemove}},
			}
			ops = append(ops, removeOp)
		}
		if len(toUpdate) != 0 {
			// Insert/update pairs.
			updateOp := txn.Op{
				C:      coll,
				Id:     id,
				Assert: txn.DocExists,
				Update: D{{"$set", toUpdate}},
			}
			ops = append(ops, updateOp)
		}
	}
	if err := a.st.runner.Run(ops, "", nil); err != nil {
		return fmt.Errorf("cannot update annotations on %s: %v", id, err)
	}
	return nil
}

// Annotations returns all the annotations corresponding to an entity.
func (a annotator) Annotations() (map[string]string, error) {
	doc := new(annotatorDoc)
	err := a.st.annotations.FindId(a.globalKey).One(doc)
	if err == mgo.ErrNotFound {
		// Returning an empty map if there are no annotations.
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return doc.Annotations, nil
}

// Annotation returns the annotation value corresponding to the given key.
// If the requested annotation is not found, an empty string is returned.
func (a annotator) Annotation(key string) (string, error) {
	ann, err := a.Annotations()
	if err != nil {
		return "", err
	}
	return ann[key], nil
}

// annotationRemoveOp returns an operation to remove a given annotation
// document from MongoDB.
func annotationRemoveOp(st *State, id string) txn.Op {
	return txn.Op{
		C:      st.annotations.Name,
		Id:     id,
		Remove: true,
	}
}
<|endoftext|>