<commit_before>package main

import (
	"log"
	"runtime"
	"time"

	"github.com/go-gl/gl/v3.2-core/gl"
	"github.com/golang-ui/nuklear/nk"
	"github.com/veandco/go-sdl2/sdl"
	"github.com/xlab/closer"
)

const (
	winWidth  = 400
	winHeight = 500

	maxVertexBuffer  = 512 * 1024
	maxElementBuffer = 128 * 1024
)

func init() {
	runtime.LockOSThread()
}

func main() {
	var err error
	sdl.Init(sdl.INIT_EVERYTHING)

	win, err := sdl.CreateWindow("Nuklear Demo", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_OPENGL)
	if err != nil {
		closer.Fatalln(err)
	}
	defer win.Destroy()

	sdl.GLSetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, 3)
	sdl.GLSetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, 2)
	sdl.GLSetAttribute(sdl.GL_CONTEXT_PROFILE_MASK, sdl.GL_CONTEXT_PROFILE_CORE)

	context, err := win.GLCreateContext()
	if err != nil {
		closer.Fatalln(err)
	}

	width, height := win.GetSize()
	log.Printf("SDL2: created window %dx%d", width, height)

	if err := gl.Init(); err != nil {
		closer.Fatalln("opengl: init failed:", err)
	}
	gl.Viewport(0, 0, int32(width), int32(height))

	ctx := nk.NkPlatformInit(win, context, nk.PlatformInstallCallbacks)

	atlas := nk.NewFontAtlas()
	nk.NkFontStashBegin(&atlas)
	sansFont := nk.NkFontAtlasAddFromBytes(atlas, MustAsset("assets/FreeSans.ttf"), 16, nil)
	nk.NkFontStashEnd()
	if sansFont != nil {
		nk.NkStyleSetFont(ctx, sansFont.Handle())
	}

	exitC := make(chan struct{}, 1)
	doneC := make(chan struct{}, 1)
	closer.Bind(func() {
		close(exitC)
		<-doneC
	})

	state := &State{
		bgColor: nk.NkRgba(28, 48, 62, 255),
	}
	fpsTicker := time.NewTicker(time.Second / 30)
	for {
		select {
		case <-exitC:
			nk.NkPlatformShutdown()
			sdl.Quit()
			fpsTicker.Stop()
			close(doneC)
			return
		case <-fpsTicker.C:
			for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
				switch event.(type) {
				case *sdl.QuitEvent:
					close(exitC)
				}
			}
			gfxMain(win, ctx, state)
		}
	}
}

func gfxMain(win *sdl.Window, ctx *nk.Context, state *State) {
	nk.NkPlatformNewFrame()

	// Layout
	bounds := nk.NkRect(50, 50, 230, 250)
	update := nk.NkBegin(ctx, "Demo", bounds,
		nk.WindowBorder|nk.WindowMovable|nk.WindowScalable|nk.WindowMinimizable|nk.WindowTitle)

	if update > 0 {
		nk.NkLayoutRowStatic(ctx, 30, 80, 1)
		{
			if nk.NkButtonLabel(ctx, "button") > 0 {
				log.Println("[INFO] button pressed!")
			}
		}
		nk.NkLayoutRowDynamic(ctx, 30, 2)
		{
			if nk.NkOptionLabel(ctx, "easy", flag(state.opt == Easy)) > 0 {
				state.opt = Easy
			}
			if nk.NkOptionLabel(ctx, "hard", flag(state.opt == Hard)) > 0 {
				state.opt = Hard
			}
		}
		nk.NkLayoutRowDynamic(ctx, 25, 1)
		{
			nk.NkPropertyInt(ctx, "Compression:", 0, &state.prop, 100, 10, 1)
		}
		nk.NkLayoutRowDynamic(ctx, 20, 1)
		{
			nk.NkLabel(ctx, "background:", nk.TextLeft)
		}
		nk.NkLayoutRowDynamic(ctx, 25, 1)
		{
			size := nk.NkVec2(nk.NkWidgetWidth(ctx), 400)
			if nk.NkComboBeginColor(ctx, state.bgColor, size) > 0 {
				nk.NkLayoutRowDynamic(ctx, 120, 1)
				state.bgColor = nk.NkColorPicker(ctx, state.bgColor, nk.ColorFormatRGBA)
				nk.NkLayoutRowDynamic(ctx, 25, 1)
				r, g, b, a := state.bgColor.RGBAi()
				r = nk.NkPropertyi(ctx, "#R:", 0, r, 255, 1, 1)
				g = nk.NkPropertyi(ctx, "#G:", 0, g, 255, 1, 1)
				b = nk.NkPropertyi(ctx, "#B:", 0, b, 255, 1, 1)
				a = nk.NkPropertyi(ctx, "#A:", 0, a, 255, 1, 1)
				state.bgColor.SetRGBAi(r, g, b, a)
				nk.NkComboEnd(ctx)
			}
		}
	}
	nk.NkEnd(ctx)

	// Render
	bg := make([]float32, 4)
	nk.NkColorFv(bg, state.bgColor)
	width, height := win.GetSize()
	gl.Viewport(0, 0, int32(width), int32(height))
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.ClearColor(bg[0], bg[1], bg[2], bg[3])
	nk.NkPlatformRender(nk.AntiAliasingOn, maxVertexBuffer, maxElementBuffer)
	win.GLSwap()
}

type Option uint8

const (
	Easy Option = 0
	Hard Option = 1
)

type State struct {
	bgColor nk.Color
	prop    int32
	opt     Option
}

func onError(code int32, msg string) {
	log.Printf("[ERR]: error %d: %s", code, msg)
}
<commit_msg>	- fix SDL2 example build (#85)<commit_after>package main

import (
	"log"
	"runtime"
	"time"

	"github.com/go-gl/gl/v3.2-core/gl"
	"github.com/golang-ui/nuklear/nk"
	"github.com/veandco/go-sdl2/sdl"
	"github.com/xlab/closer"
)

const (
	winWidth  = 400
	winHeight = 500

	maxVertexBuffer  = 512 * 1024
	maxElementBuffer = 128 * 1024
)

func init() {
	runtime.LockOSThread()
}

func main() {
	var err error
	sdl.Init(sdl.INIT_EVERYTHING)

	win, err := sdl.CreateWindow("Nuklear Demo", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_OPENGL)
	if err != nil {
		closer.Fatalln(err)
	}
	defer win.Destroy()

	sdl.GLSetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, 3)
	sdl.GLSetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, 2)
	sdl.GLSetAttribute(sdl.GL_CONTEXT_PROFILE_MASK, sdl.GL_CONTEXT_PROFILE_CORE)

	context, err := win.GLCreateContext()
	if err != nil {
		closer.Fatalln(err)
	}

	width, height := win.GetSize()
	log.Printf("SDL2: created window %dx%d", width, height)

	if err := gl.Init(); err != nil {
		closer.Fatalln("opengl: init failed:", err)
	}
	gl.Viewport(0, 0, int32(width), int32(height))

	ctx := nk.NkPlatformInit(win, context, nk.PlatformInstallCallbacks)

	atlas := nk.NewFontAtlas()
	nk.NkFontStashBegin(&atlas)
	sansFont := nk.NkFontAtlasAddFromBytes(atlas, MustAsset("assets/FreeSans.ttf"), 16, nil)
	nk.NkFontStashEnd()
	if sansFont != nil {
		nk.NkStyleSetFont(ctx, sansFont.Handle())
	}

	exitC := make(chan struct{}, 1)
	doneC := make(chan struct{}, 1)
	closer.Bind(func() {
		close(exitC)
		<-doneC
	})

	state := &State{
		bgColor: nk.NkRgba(28, 48, 62, 255),
	}
	fpsTicker := time.NewTicker(time.Second / 30)
	for {
		select {
		case <-exitC:
			nk.NkPlatformShutdown()
			sdl.Quit()
			fpsTicker.Stop()
			close(doneC)
			return
		case <-fpsTicker.C:
			for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
				switch event.(type) {
				case *sdl.QuitEvent:
					close(exitC)
				}
			}
			gfxMain(win, ctx, state)
		}
	}
}

func gfxMain(win *sdl.Window, ctx *nk.Context, state *State) {
	nk.NkPlatformNewFrame()

	// Layout
	bounds := nk.NkRect(50, 50, 230, 250)
	update := nk.NkBegin(ctx, "Demo", bounds,
		nk.WindowBorder|nk.WindowMovable|nk.WindowScalable|nk.WindowMinimizable|nk.WindowTitle)

	if update > 0 {
		nk.NkLayoutRowStatic(ctx, 30, 80, 1)
		{
			if nk.NkButtonLabel(ctx, "button") > 0 {
				log.Println("[INFO] button pressed!")
			}
		}
		nk.NkLayoutRowDynamic(ctx, 30, 2)
		{
			if nk.NkOptionLabel(ctx, "easy", flag(state.opt == Easy)) > 0 {
				state.opt = Easy
			}
			if nk.NkOptionLabel(ctx, "hard", flag(state.opt == Hard)) > 0 {
				state.opt = Hard
			}
		}
		nk.NkLayoutRowDynamic(ctx, 25, 1)
		{
			nk.NkPropertyInt(ctx, "Compression:", 0, &state.prop, 100, 10, 1)
		}
		nk.NkLayoutRowDynamic(ctx, 20, 1)
		{
			nk.NkLabel(ctx, "background:", nk.TextLeft)
		}
		nk.NkLayoutRowDynamic(ctx, 25, 1)
		{
			size := nk.NkVec2(nk.NkWidgetWidth(ctx), 400)
			if nk.NkComboBeginColor(ctx, state.bgColor, size) > 0 {
				nk.NkLayoutRowDynamic(ctx, 120, 1)
				cf := nk.NkColorCf(state.bgColor)
				cf = nk.NkColorPicker(ctx, cf, nk.ColorFormatRGBA)
				state.bgColor = nk.NkRgbCf(cf)
				nk.NkLayoutRowDynamic(ctx, 25, 1)
				r, g, b, a := state.bgColor.RGBAi()
				r = nk.NkPropertyi(ctx, "#R:", 0, r, 255, 1, 1)
				g = nk.NkPropertyi(ctx, "#G:", 0, g, 255, 1, 1)
				b = nk.NkPropertyi(ctx, "#B:", 0, b, 255, 1, 1)
				a = nk.NkPropertyi(ctx, "#A:", 0, a, 255, 1, 1)
				state.bgColor.SetRGBAi(r, g, b, a)
				nk.NkComboEnd(ctx)
			}
		}
	}
	nk.NkEnd(ctx)

	// Render
	bg := make([]float32, 4)
	nk.NkColorFv(bg, state.bgColor)
	width, height := win.GetSize()
	gl.Viewport(0, 0, int32(width), int32(height))
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.ClearColor(bg[0], bg[1], bg[2], bg[3])
	nk.NkPlatformRender(nk.AntiAliasingOn, maxVertexBuffer, maxElementBuffer)
	win.GLSwap()
}

type Option uint8

const (
	Easy Option = 0
	Hard Option = 1
)

type State struct {
	bgColor nk.Color
	prop    int32
	opt     Option
}

func onError(code int32, msg string) {
	log.Printf("[ERR]: error %d: %s", code, msg)
}
<|endoftext|>


<commit_before>// Copyright (C) 2012-2016 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.

package user_agent

import (
	"regexp"
	"strings"
)

var ie11Regexp = regexp.MustCompile("^rv:(.+)$")

// A struct containing all the information that we might be
// interested from the browser.
type Browser struct {
	// The name of the browser's engine.
	Engine string

	// The version of the browser's engine.
	EngineVersion string

	// The name of the browser.
	Name string

	// The version of the browser.
	Version string
}

// Extract all the information that we can get from the User-Agent string
// about the browser and update the receiver with this information.
//
// The function receives just one argument "sections", that contains the
// sections from the User-Agent string after being parsed.
func (p *UserAgent) detectBrowser(sections []section) {
	slen := len(sections)

	if sections[0].name == "Opera" {
		p.browser.Name = "Opera"
		p.browser.Version = sections[0].version
		p.browser.Engine = "Presto"
		if slen > 1 {
			p.browser.EngineVersion = sections[1].version
		}
	} else if sections[0].name == "Dalvik" {
		// When Dalvik VM is in use, there is no browser info attached to ua.
		// Although browser is still a Mozilla/5.0 compatible.
		p.mozilla = "5.0"
	} else if slen > 1 {
		engine := sections[1]
		p.browser.Engine = engine.name
		p.browser.EngineVersion = engine.version
		if slen > 2 {
			p.browser.Version = sections[2].version
			if engine.name == "AppleWebKit" {
				switch sections[slen-1].name {
				case "Edge":
					p.browser.Name = "Edge"
					p.browser.Version = sections[slen-1].version
					p.browser.Engine = "EdgeHTML"
					p.browser.EngineVersion = ""
				case "OPR":
					p.browser.Name = "Opera"
					p.browser.Version = sections[slen-1].version
				default:
					if (len(sections) > 5 && sections[5].name == "QIHU") || (len(sections) > 5 && sections[5].name == "360EE") || (len(sections) > 5 && sections[5].name == "360SE") {
						p.browser.Name = "360"
					} else if len(sections) > 5 && sections[5].name == "QQBrowser" {
						p.browser.Name = "QQ"
						p.browser.Version = sections[5].version
					} else if len(sections) > 4 && sections[4].name == "SE" {
						p.browser.Name = "sougou"
						p.browser.Version = sections[4].version
					} else if len(sections) > 4 && sections[4].name == "2345Explorer" {
						p.browser.Name = "2345"
						p.browser.Version = sections[4].version
					} else if len(sections) > 4 && sections[4].name == "LBBROWSER" {
						p.browser.Name = "liebao"
						p.browser.Version = sections[4].version
					} else if sections[2].name == "Chrome" {
						p.browser.Name = "Chrome"
					} else if sections[3].name == "MQQBrowser" {
						p.browser.Name = "QQbrowser mobile"
						p.browser.Version = sections[3].version
					} else {
						p.browser.Name = "Safari"
					}
				}
			} else if engine.name == "Gecko" {
				name := sections[2].name
				if name == "MRA" && slen > 4 {
					name = sections[4].name
					p.browser.Version = sections[4].version
				}
				p.browser.Name = name
			} else if engine.name == "like" && sections[2].name == "Gecko" {
				// This is the new user agent from Internet Explorer 11.
				p.browser.Engine = "Trident"
				p.browser.Name = "Internet Explorer"
				for _, c := range sections[0].comment {
					version := ie11Regexp.FindStringSubmatch(c)
					if len(version) > 0 {
						p.browser.Version = version[1]
						return
					}
				}
				p.browser.Version = ""
			}
		}
	} else if slen == 1 && len(sections[0].comment) > 1 {
		comment := sections[0].comment
		if comment[0] == "compatible" && strings.HasPrefix(comment[1], "MSIE") {
			p.browser.Engine = "Trident"
			p.browser.Name = "Internet Explorer"
			// The MSIE version may be reported as the compatibility version.
			// For IE 8 through 10, the Trident token is more accurate.
			// http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx#VerToken
			for _, v := range comment {
				if strings.HasPrefix(v, "Trident/") {
					switch v[8:] {
					case "4.0":
						p.browser.Version = "8.0"
					case "5.0":
						p.browser.Version = "9.0"
					case "6.0":
						p.browser.Version = "10.0"
					}
					break
				}
			}
			// If the Trident token is not provided, fall back to MSIE token.
			if p.browser.Version == "" {
				p.browser.Version = strings.TrimSpace(comment[1][4:])
			}
		}
	}
}

// Returns two strings. The first string is the name of the engine and the
// second one is the version of the engine.
func (p *UserAgent) Engine() (string, string) {
	return p.browser.Engine, p.browser.EngineVersion
}

// Returns two strings. The first string is the name of the browser and the
// second one is the version of the browser.
func (p *UserAgent) Browser() (string, string) {
	return p.browser.Name, p.browser.Version
}
<commit_msg>bugfixed out index<commit_after>// Copyright (C) 2012-2016 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.

package user_agent

import (
	"regexp"
	"strings"
)

var ie11Regexp = regexp.MustCompile("^rv:(.+)$")

// A struct containing all the information that we might be
// interested from the browser.
type Browser struct {
	// The name of the browser's engine.
	Engine string

	// The version of the browser's engine.
	EngineVersion string

	// The name of the browser.
	Name string

	// The version of the browser.
	Version string
}

// Extract all the information that we can get from the User-Agent string
// about the browser and update the receiver with this information.
//
// The function receives just one argument "sections", that contains the
// sections from the User-Agent string after being parsed.
func (p *UserAgent) detectBrowser(sections []section) {
	slen := len(sections)

	if sections[0].name == "Opera" {
		p.browser.Name = "Opera"
		p.browser.Version = sections[0].version
		p.browser.Engine = "Presto"
		if slen > 1 {
			p.browser.EngineVersion = sections[1].version
		}
	} else if sections[0].name == "Dalvik" {
		// When Dalvik VM is in use, there is no browser info attached to ua.
		// Although browser is still a Mozilla/5.0 compatible.
		p.mozilla = "5.0"
	} else if slen > 1 {
		engine := sections[1]
		p.browser.Engine = engine.name
		p.browser.EngineVersion = engine.version
		if slen > 2 {
			p.browser.Version = sections[2].version
			if engine.name == "AppleWebKit" {
				switch sections[slen-1].name {
				case "Edge":
					p.browser.Name = "Edge"
					p.browser.Version = sections[slen-1].version
					p.browser.Engine = "EdgeHTML"
					p.browser.EngineVersion = ""
				case "OPR":
					p.browser.Name = "Opera"
					p.browser.Version = sections[slen-1].version
				default:
					if (len(sections) > 5 && sections[5].name == "QIHU") || (len(sections) > 5 && sections[5].name == "360EE") || (len(sections) > 5 && sections[5].name == "360SE") {
						p.browser.Name = "360"
					} else if len(sections) > 5 && sections[5].name == "QQBrowser" {
						p.browser.Name = "QQ"
						p.browser.Version = sections[5].version
					} else if len(sections) > 4 && sections[4].name == "SE" {
						p.browser.Name = "sougou"
						p.browser.Version = sections[4].version
					} else if len(sections) > 4 && sections[4].name == "2345Explorer" {
						p.browser.Name = "2345"
						p.browser.Version = sections[4].version
					} else if len(sections) > 4 && sections[4].name == "LBBROWSER" {
						p.browser.Name = "liebao"
						p.browser.Version = sections[4].version
					} else if len(sections) > 2 && sections[2].name == "Chrome" {
						p.browser.Name = "Chrome"
					} else if len(sections) > 3 && sections[3].name == "MQQBrowser" {
						p.browser.Name = "QQbrowser mobile"
						p.browser.Version = sections[3].version
					} else {
						p.browser.Name = "Safari"
					}
				}
			} else if engine.name == "Gecko" {
				name := sections[2].name
				if name == "MRA" && slen > 4 {
					name = sections[4].name
					p.browser.Version = sections[4].version
				}
				p.browser.Name = name
			} else if engine.name == "like" && sections[2].name == "Gecko" {
				// This is the new user agent from Internet Explorer 11.
				p.browser.Engine = "Trident"
				p.browser.Name = "Internet Explorer"
				for _, c := range sections[0].comment {
					version := ie11Regexp.FindStringSubmatch(c)
					if len(version) > 0 {
						p.browser.Version = version[1]
						return
					}
				}
				p.browser.Version = ""
			}
		}
	} else if slen == 1 && len(sections[0].comment) > 1 {
		comment := sections[0].comment
		if comment[0] == "compatible" && strings.HasPrefix(comment[1], "MSIE") {
			p.browser.Engine = "Trident"
			p.browser.Name = "Internet Explorer"
			// The MSIE version may be reported as the compatibility version.
			// For IE 8 through 10, the Trident token is more accurate.
			// http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx#VerToken
			for _, v := range comment {
				if strings.HasPrefix(v, "Trident/") {
					switch v[8:] {
					case "4.0":
						p.browser.Version = "8.0"
					case "5.0":
						p.browser.Version = "9.0"
					case "6.0":
						p.browser.Version = "10.0"
					}
					break
				}
			}
			// If the Trident token is not provided, fall back to MSIE token.
			if p.browser.Version == "" {
				p.browser.Version = strings.TrimSpace(comment[1][4:])
			}
		}
	}
}

// Returns two strings. The first string is the name of the engine and the
// second one is the version of the engine.
func (p *UserAgent) Engine() (string, string) {
	return p.browser.Engine, p.browser.EngineVersion
}

// Returns two strings. The first string is the name of the browser and the
// second one is the version of the browser.
func (p *UserAgent) Browser() (string, string) {
	return p.browser.Name, p.browser.Version
}
<|endoftext|>


<commit_before>package katja

import (
	"context"
	"fmt"
	cid "gx/ipfs/QmYhQaCYEcaPPjxJX7YcPcVKkQfRy6sJ7B3XmGFk82XYdQ/go-cid"

	"runtime"

	"github.com/ipfs/go-ipfs/core"
	"github.com/ipfs/go-ipfs/merkledag"
	"github.com/ipfs/go-ipfs/path"
	"github.com/ipfs/go-ipfs/repo/fsrepo"
)

func defaultPath() string {
	if runtime.GOOS == "windows" {
		return "C:\\Users\\username\\.ipfs"
	}
	return "~/.ipfs"
}

// StartNode Start IPFS Node
func StartNode() (*core.IpfsNode, error) {
	// Assume the user has run 'ipfs init'
	repo := defaultPath()
	r, err := fsrepo.Open(repo)
	if err != nil {
		return nil, err
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cfg := &core.BuildCfg{
		Repo:   r,
		Online: true,
	}

	return core.NewNode(ctx, cfg)
}

// GetStrings get strings by cid
func GetStrings(node *core.IpfsNode, cid *cid.Cid) (stringArr []string, err error) {
	ctx, cancel := context.WithCancel(context.Background())
	nodeGetter := node.DAG
	defer cancel()
	// merkledag proto Node
	nd, err := nodeGetter.Get(ctx, cid)
	fmt.Println("the node is", nd)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("bout to crash")
	fmt.Printf("%s", nd.String())
	fmt.Println("not crashed ")

	for {
		var err error
		if len(nd.Links()) == 0 {
			break
		}

		nd, err = nd.Links()[0].GetNode(ctx, nodeGetter)
		if err != nil {
			fmt.Println(err)
			break
		}

		data := nd.String()
		fmt.Println(data)
		stringArr = append(stringArr, data)
	}

	return stringArr, nil
}

// AddString add input string to ipfs node
func AddString(node *core.IpfsNode, inputString string) (*cid.Cid, error) {
	pointsTo, err := node.Namesys.Resolve(node.Context(), node.Identity.Pretty())
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	//If there is an error, user is new and hasn't yet created a DAG.
	if err != nil {
		newProtoNode := makeStringNode(inputString)
		cid, err := node.DAG.Add(newProtoNode)
		if err != nil {
			return nil, err
		}

		err = node.Namesys.Publish(ctx, node.PrivateKey, path.FromCid(cid))
		if err != nil {
			return nil, err
		}

		return cid, nil
	}

	// Else user has already creatd a DAG
	newProtoNode := makeStringNode(inputString)
	cid, err := cid.Decode(pointsTo.String())
	if err != nil {
		return nil, err
	}

	oldProtoNode, err := node.DAG.Get(ctx, cid)
	if err != nil {
		return nil, err
	}

	err = newProtoNode.AddNodeLink("next", oldProtoNode)
	if err != nil {
		return nil, err
	}

	node.DAG.Add(newProtoNode)
	err = node.Namesys.Publish(ctx, node.PrivateKey, pointsTo)
	if err != nil {
		return nil, err
	}

	return cid, nil
}

func makeStringNode(s string) *merkledag.ProtoNode {
	nd := new(merkledag.ProtoNode)
	nd.SetData([]byte(s))
	return nd
}
<commit_msg>getDAG<commit_after>package katja

import (
	"context"
	"fmt"
	cid "gx/ipfs/QmYhQaCYEcaPPjxJX7YcPcVKkQfRy6sJ7B3XmGFk82XYdQ/go-cid"

	"runtime"

	node "gx/ipfs/Qmb3Hm9QDFmfYuET4pu7Kyg8JV78jFa1nvZx5vnCZsK4ck/go-ipld-format"

	"github.com/ipfs/go-ipfs/core"
	"github.com/ipfs/go-ipfs/merkledag"
	"github.com/ipfs/go-ipfs/path"
	"github.com/ipfs/go-ipfs/repo/fsrepo"
)

func defaultPath() string {
	if runtime.GOOS == "windows" {
		return "C:\\Users\\username\\.ipfs"
	}
	return "~/.ipfs"
}

// StartNode Start IPFS Node
func StartNode() (*core.IpfsNode, error) {
	// Assume the user has run 'ipfs init'
	repo := defaultPath()
	r, err := fsrepo.Open(repo)
	if err != nil {
		return nil, err
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cfg := &core.BuildCfg{
		Repo:   r,
		Online: true,
	}

	return core.NewNode(ctx, cfg)
}

// GetStrings get strings by cid
func GetStrings(node *core.IpfsNode, cid *cid.Cid) (stringArr []string, err error) {
	ctx, cancel := context.WithCancel(context.Background())
	nodeGetter := node.DAG
	defer cancel()
	// merkledag proto Node
	nd, err := nodeGetter.Get(ctx, cid)
	fmt.Println("the node is", nd)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("bout to crash")
	fmt.Printf("%s", nd.String())
	fmt.Println("not crashed ")

	for {
		var err error
		if len(nd.Links()) == 0 {
			break
		}

		nd, err = nd.Links()[0].GetNode(ctx, nodeGetter)
		if err != nil {
			fmt.Println(err)
			break
		}

		data := nd.String()
		fmt.Println(data)
		stringArr = append(stringArr, data)
	}

	return stringArr, nil
}

// GetDAG get DAG proto node
func GetDAG(node *core.IpfsNode, cid *cid.Cid) (node.Node, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	return node.DAG.Get(ctx, cid)
}

// AddString add input string to ipfs node
func AddString(node *core.IpfsNode, inputString string) (*cid.Cid, error) {
	pointsTo, err := node.Namesys.Resolve(node.Context(), node.Identity.Pretty())
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	//If there is an error, user is new and hasn't yet created a DAG.
	if err != nil {
		newProtoNode := makeStringNode(inputString)
		cid, err := node.DAG.Add(newProtoNode)
		if err != nil {
			return nil, err
		}

		err = node.Namesys.Publish(ctx, node.PrivateKey, path.FromCid(cid))
		if err != nil {
			return nil, err
		}

		return cid, nil
	}

	// Else user has already creatd a DAG
	newProtoNode := makeStringNode(inputString)
	cid, err := cid.Decode(pointsTo.String())
	if err != nil {
		return nil, err
	}

	oldProtoNode, err := node.DAG.Get(ctx, cid)
	if err != nil {
		return nil, err
	}

	err = newProtoNode.AddNodeLink("next", oldProtoNode)
	if err != nil {
		return nil, err
	}

	node.DAG.Add(newProtoNode)
	err = node.Namesys.Publish(ctx, node.PrivateKey, pointsTo)
	if err != nil {
		return nil, err
	}

	return cid, nil
}

func makeStringNode(s string) *merkledag.ProtoNode {
	nd := new(merkledag.ProtoNode)
	nd.SetData([]byte(s))
	return nd
}
<|endoftext|>


<commit_before>// Copyright 2014 The roc Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package rocserv

import (
	"context"
	"fmt"
	"net"
	"net/http"

	"gitlab.pri.ibanyu.com/middleware/seaweed/xlog"
	"gitlab.pri.ibanyu.com/middleware/seaweed/xtrace"

	"git.apache.org/thrift.git/lib/go/thrift"
	"github.com/gin-gonic/gin"
	"github.com/julienschmidt/httprouter"
	"github.com/opentracing-contrib/go-stdlib/nethttp"
	"github.com/shawnfeng/sutil/snetutil"
	"github.com/shawnfeng/sutil/trace"
)

func powerHttp(addr string, router *httprouter.Router) (string, error) {
	fun := "powerHttp -->"
	ctx := context.Background()

	paddr, err := snetutil.GetListenAddr(addr)
	if err != nil {
		return "", err
	}

	xlog.Infof(ctx, "%s config addr[%s]", fun, paddr)

	tcpAddr, err := net.ResolveTCPAddr("tcp", paddr)
	if err != nil {
		return "", err
	}

	netListen, err := net.Listen(tcpAddr.Network(), tcpAddr.String())
	if err != nil {
		return "", err
	}

	laddr, err := snetutil.GetServAddr(netListen.Addr())
	if err != nil {
		netListen.Close()
		return "", err
	}

	xlog.Infof(ctx, "%s listen addr[%s]", fun, laddr)

	// tracing
	mw := nethttp.Middleware(
		xtrace.GlobalTracer(),
		// add logging middleware
		httpTrafficLogMiddleware(router),
		nethttp.OperationNameFunc(func(r *http.Request) string {
			return "HTTP " + r.Method + ": " + r.URL.Path
		}),
		nethttp.MWSpanFilter(trace.UrlSpanFilter))

	go func() {
		err := http.Serve(netListen, mw)
		if err != nil {
			xlog.Panicf(ctx, "%s laddr[%s]", fun, laddr)
		}
	}()

	return laddr, nil
}

func powerThrift(addr string, processor thrift.TProcessor) (string, error) {
	fun := "powerThrift -->"
	ctx := context.Background()

	paddr, err := snetutil.GetListenAddr(addr)
	if err != nil {
		return "", err
	}

	xlog.Infof(ctx, "%s config addr[%s]", fun, paddr)

	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
	//protocolFactory := thrift.NewTCompactProtocolFactory()

	serverTransport, err := thrift.NewTServerSocket(paddr)
	if err != nil {
		return "", err
	}

	server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)

	// Listen后就可以拿到端口了
	//err = server.Listen()
	err = serverTransport.Listen()
	if err != nil {
		return "", err
	}

	laddr, err := snetutil.GetServAddr(serverTransport.Addr())
	if err != nil {
		return "", err
	}

	xlog.Infof(ctx, "%s listen addr[%s]", fun, laddr)

	go func() {
		err := server.Serve()
		if err != nil {
			xlog.Panicf(ctx, "%s laddr[%s]", fun, laddr)
		}
	}()

	return laddr, nil

}

//启动grpc ，并返回端口信息
func powerGrpc(addr string, server *GrpcServer) (string, error) {
	fun := "powerGrpc -->"
	ctx := context.Background()
	paddr, err := snetutil.GetListenAddr(addr)
	if err != nil {
		return "", err
	}
	xlog.Infof(ctx, "%s config addr[%s]", fun, paddr)
	lis, err := net.Listen("tcp", paddr)
	if err != nil {
		return "", fmt.Errorf("grpc tcp Listen err:%v", err)
	}
	laddr, err := snetutil.GetServAddr(lis.Addr())
	if err != nil {
		return "", fmt.Errorf(" GetServAddr err:%v", err)
	}
	xlog.Infof(ctx, "%s listen grpc addr[%s]", fun, laddr)
	go func() {
		grpcServer, err := server.buildServer()
		if err != nil {
			xlog.Panicf(ctx, "%s server.buildServer error, addr: %s, err: %v", fun, addr, err)
		}
		if err := grpcServer.Serve(lis); err != nil {
			xlog.Panicf(ctx, "%s grpc laddr[%s]", fun, laddr)
		}
	}()
	return laddr, nil
}

func powerGin(addr string, router *gin.Engine) (string, error) {
	fun := "powerGin -->"
	ctx := context.Background()

	paddr, err := snetutil.GetListenAddr(addr)
	if err != nil {
		return "", err
	}

	xlog.Infof(ctx, "%s config addr[%s]", fun, paddr)

	tcpAddr, err := net.ResolveTCPAddr("tcp", paddr)
	if err != nil {
		return "", err
	}

	netListen, err := net.Listen(tcpAddr.Network(), tcpAddr.String())
	if err != nil {
		return "", err
	}

	laddr, err := snetutil.GetServAddr(netListen.Addr())
	if err != nil {
		netListen.Close()
		return "", err
	}

	xlog.Infof(ctx, "%s listen addr[%s]", fun, laddr)

	// tracing
	mw := nethttp.Middleware(
		xtrace.GlobalTracer(),
		httpTrafficLogMiddleware(router),
		nethttp.OperationNameFunc(func(r *http.Request) string {
			return "HTTP " + r.Method + ": " + r.URL.Path
		}),
		nethttp.MWSpanFilter(trace.UrlSpanFilter))

	serv := &http.Server{Handler: mw}
	go func() {
		err := serv.Serve(netListen)
		if err != nil {
			xlog.Panicf(ctx, "%s laddr[%s]", fun, laddr)
		}
	}()

	return laddr, nil
}

func reloadRouter(processor string, server interface{}, driver interface{}) error {
	fun := "reloadRouter -->"

	s, ok := server.(*http.Server)
	if !ok {
		return fmt.Errorf("server type error")
	}

	switch router := driver.(type) {
	case *gin.Engine:
		mw := nethttp.Middleware(
			xtrace.GlobalTracer(),
			router,
			nethttp.OperationNameFunc(func(r *http.Request) string {
				return "HTTP " + r.Method + ": " + r.URL.Path
			}))
		s.Handler = mw
		xlog.Infof(context.Background(), "%s reload ok, processors:%s", fun, processor)
	default:
		return fmt.Errorf("processor:%s driver not recognition", processor)
	}

	return nil
}
<commit_msg>refactor: powerGin and powerHttp<commit_after>// Copyright 2014 The roc Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package rocserv

import (
	"context"
	"fmt"
	"net"
	"net/http"

	"gitlab.pri.ibanyu.com/middleware/seaweed/xlog"
	"gitlab.pri.ibanyu.com/middleware/seaweed/xtrace"

	"git.apache.org/thrift.git/lib/go/thrift"
	"github.com/gin-gonic/gin"
	"github.com/julienschmidt/httprouter"
	"github.com/opentracing-contrib/go-stdlib/nethttp"
	"github.com/shawnfeng/sutil/snetutil"
	"github.com/shawnfeng/sutil/trace"
)

func powerHttp(addr string, router *httprouter.Router) (string, error) {
	fun := "powerHttp -->"
	ctx := context.Background()

	netListen, laddr, err := listenServAddr(ctx, addr)
	if err != nil {
		return "", err
	}

	// tracing
	mw := decorateHttpMiddleware(router)

	go func() {
		err := http.Serve(netListen, mw)
		if err != nil {
			xlog.Panicf(ctx, "%s laddr[%s]", fun, laddr)
		}
	}()

	return laddr, nil
}

// 打开端口监听, 并返回服务地址
func listenServAddr(ctx context.Context, addr string) (net.Listener, string, error) {
	fun := "listenServAddr --> "
	paddr, err := snetutil.GetListenAddr(addr)
	if err != nil {
		return nil, "", err
	}

	xlog.Infof(ctx, "%s config addr[%s]", fun, paddr)

	tcpAddr, err := net.ResolveTCPAddr("tcp", paddr)
	if err != nil {
		return nil, "", err
	}

	netListen, err := net.Listen(tcpAddr.Network(), tcpAddr.String())
	if err != nil {
		return nil, "", err
	}

	laddr, err := snetutil.GetServAddr(netListen.Addr())
	if err != nil {
		netListen.Close()
		return nil, "", err
	}

	xlog.Infof(ctx, "%s listen addr[%s]", fun, laddr)
	return netListen, laddr, nil
}

// 添加http middleware
func decorateHttpMiddleware(router http.Handler) http.Handler {
	// tracing
	mw := nethttp.Middleware(
		xtrace.GlobalTracer(),
		// add logging middleware
		httpTrafficLogMiddleware(router),
		nethttp.OperationNameFunc(func(r *http.Request) string {
			return "HTTP " + r.Method + ": " + r.URL.Path
		}),
		nethttp.MWSpanFilter(trace.UrlSpanFilter))

	return mw
}

func powerThrift(addr string, processor thrift.TProcessor) (string, error) {
	fun := "powerThrift -->"
	ctx := context.Background()

	paddr, err := snetutil.GetListenAddr(addr)
	if err != nil {
		return "", err
	}

	xlog.Infof(ctx, "%s config addr[%s]", fun, paddr)

	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
	//protocolFactory := thrift.NewTCompactProtocolFactory()

	serverTransport, err := thrift.NewTServerSocket(paddr)
	if err != nil {
		return "", err
	}

	server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)

	// Listen后就可以拿到端口了
	//err = server.Listen()
	err = serverTransport.Listen()
	if err != nil {
		return "", err
	}

	laddr, err := snetutil.GetServAddr(serverTransport.Addr())
	if err != nil {
		return "", err
	}

	xlog.Infof(ctx, "%s listen addr[%s]", fun, laddr)

	go func() {
		err := server.Serve()
		if err != nil {
			xlog.Panicf(ctx, "%s laddr[%s]", fun, laddr)
		}
	}()

	return laddr, nil

}

//启动grpc ，并返回端口信息
func powerGrpc(addr string, server *GrpcServer) (string, error) {
	fun := "powerGrpc -->"
	ctx := context.Background()
	paddr, err := snetutil.GetListenAddr(addr)
	if err != nil {
		return "", err
	}
	xlog.Infof(ctx, "%s config addr[%s]", fun, paddr)
	lis, err := net.Listen("tcp", paddr)
	if err != nil {
		return "", fmt.Errorf("grpc tcp Listen err:%v", err)
	}
	laddr, err := snetutil.GetServAddr(lis.Addr())
	if err != nil {
		return "", fmt.Errorf(" GetServAddr err:%v", err)
	}
	xlog.Infof(ctx, "%s listen grpc addr[%s]", fun, laddr)
	go func() {
		grpcServer, err := server.buildServer()
		if err != nil {
			xlog.Panicf(ctx, "%s server.buildServer error, addr: %s, err: %v", fun, addr, err)
		}
		if err := grpcServer.Serve(lis); err != nil {
			xlog.Panicf(ctx, "%s grpc laddr[%s]", fun, laddr)
		}
	}()
	return laddr, nil
}

func powerGin(addr string, router *gin.Engine) (string, error) {
	fun := "powerGin -->"
	ctx := context.Background()

	netListen, laddr, err := listenServAddr(ctx, addr)
	if err != nil {
		return "", err
	}

	// tracing
	mw := decorateHttpMiddleware(router)

	serv := &http.Server{Handler: mw}
	go func() {
		err := serv.Serve(netListen)
		if err != nil {
			xlog.Panicf(ctx, "%s laddr[%s]", fun, laddr)
		}
	}()

	return laddr, nil
}

func reloadRouter(processor string, server interface{}, driver interface{}) error {
	fun := "reloadRouter -->"

	s, ok := server.(*http.Server)
	if !ok {
		return fmt.Errorf("server type error")
	}

	switch router := driver.(type) {
	case *gin.Engine:
		mw := nethttp.Middleware(
			xtrace.GlobalTracer(),
			router,
			nethttp.OperationNameFunc(func(r *http.Request) string {
				return "HTTP " + r.Method + ": " + r.URL.Path
			}))
		s.Handler = mw
		xlog.Infof(context.Background(), "%s reload ok, processors:%s", fun, processor)
	default:
		return fmt.Errorf("processor:%s driver not recognition", processor)
	}

	return nil
}
<|endoftext|>


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

package tracer

import (
	"bytes"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"

	ntrace "golang.org/x/net/trace"

	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/caller"
	"github.com/cockroachdb/cockroach/util/log"
)

// Node is the family used for the node.
const Node = "node"

// Coord is the family used for the coordinator/gateway.
const Coord = "coord"

// A Traceable object has a Trace identifier attached to it.
type Traceable interface {
	// TraceID is the unique ID for the tracee.
	TraceID() string
	// TraceName is a short and "sufficiently unique" human-readable
	// representation of the tracee.
	TraceName() string
}

// A TraceItem is an entry in a Trace.
type TraceItem struct {
	depth     int32
	Origin    string
	Name      string
	Timestamp time.Time
	Duration  time.Duration
	File      string
	Line      int
	Func      string
	HLC       time.Time // TODO(tschottdorf) HLC timestamp
}

// A Trace is created by a Tracer and records the path of a request within (a
// connected part of) the system. It contains the ID of the traced object and a
// slice of trace entries. In typical usage the Epoch() and Event() methods are
// called at various stages to record the path the associated request takes
// through the system; when the request goes out of scope, a call to Finalize
// marks the end of the Trace, at which point it publishes itself to an
// associated `util.Feed`. A request may create multiple Traces as it passes
// through different parts of a distributed systems.
// A Trace is not safe for concurrent access.
//
// TODO(tschottdorf): not allowing concurrent access is the right thing to do
// semantically, but we pass a Trace along with a context.Context, which
// explicitly encourages sharing of values. Might want to add that just for
// that reason, but for now it's convenient to let the race detector check what
// we do with the Trace.
type Trace struct {
	// IDs is the unique identifier for the request in this trace.
	ID string
	// Name is a human-readable identifier for the request in this trace.
	Name string
	// Content is a trace, containing call sites and timings in the order in
	// which they happened.
	Content []TraceItem
	tracer  *Tracer // origin tracer for clock, publishing...
	depth   int32
	family  string
	nTrace  ntrace.Trace
}

// Event adds an Epoch with zero duration to the Trace.
func (t *Trace) Event(name string) {
	if t == nil {
		return
	}
	t.epoch(name)()
	t.Content[len(t.Content)-1].Duration = 0
}

// SetError marks the request associated to the Trace as failed.
func (t *Trace) SetError() {
	if t != nil {
		t.nTrace.SetError()
	}
}

// Epoch begins a phase in the life of the Trace, starting the measurement of
// its duration. The returned function needs to be called when the measurement
// is complete; failure to do so results in a panic() when Finalize() is
// called. The suggested pattern of usage is, where possible,
// `defer trace.Epoch("<name>")()`.
func (t *Trace) Epoch(name string) func() {
	if t == nil {
		return func() {}
	}
	return t.epoch(name)
}

func (t *Trace) epoch(name string) func() {
	if t.depth < 0 {
		panic("use of finalized Trace:\n" + t.String())
	}
	t.depth++
	t.nTrace.LazyPrintf(name)
	pos := t.add(name)
	called := false
	return func() {
		if called {
			panic("epoch terminated twice")
		}
		called = true
		t.Content[pos].Duration = t.tracer.now().Sub(t.Content[pos].Timestamp)
		t.depth--
		t.nTrace.LazyPrintf(name + " [end]")
	}
}

// Finalize submits the Trace to the underlying feed. If there is an open
// Epoch, a panic occurs.
func (t *Trace) Finalize() {
	if t == nil {
		return
	}
	defer t.nTrace.Finish()
	if t == nil || len(t.Content) == 0 {
		return
	}
	if r := recover(); r != nil {
		t.Epoch(fmt.Sprintf("panic: %v", r))
		panic(r)
	}
	if t.depth != 0 {
		panic("attempt to finalize unbalanced trace:\n" + t.String())
	}
	t.depth = math.MinInt32
	if t.tracer.feed != nil {
		t.tracer.feed.Publish(t) // by reference
	} else if log.V(2) {
		log.Info(t)
	}
}

func (t *Trace) add(name string) int {
	// Must be called with two callers to the client.
	// (Client->Event|Epoch->epoch->add)
	file, line, fun := caller.Lookup(3)
	t.Content = append(t.Content, TraceItem{
		depth:     t.depth,
		Origin:    t.tracer.origin,
		File:      file,
		Line:      line,
		Func:      fun,
		Timestamp: t.tracer.now(),
		Name:      name,
	})
	return len(t.Content) - 1
}

// Fork creates a new Trace, equal to (but autonomous from) that which created
// the original Trace.
func (t *Trace) Fork() *Trace {
	if t == nil {
		return nil
	}
	return t.tracer.newTrace(t.family, t.ID, t.Name)
}

// String implements fmt.Stringer. It prints a human-readable breakdown of the
// Trace.
func (t Trace) String() string {
	const tab = "\t"
	var buf bytes.Buffer
	w := tabwriter.NewWriter(&buf, 1, 1, 0, ' ', 0)
	fmt.Fprintln(w, "Trace", t.Name)
	fmt.Fprintln(w, "Origin", tab, "Ts", tab, "Dur", tab, "Desc", tab, "File")

	const traceTimeFormat = "15:04:05.000000"
	for _, c := range t.Content {
		var namePrefix string
		if c.depth > 1 {
			namePrefix = strings.Repeat("·", int(c.depth-1))
		}
		fmt.Fprintln(w, c.Origin, tab, c.Timestamp.Format(traceTimeFormat),
			tab, c.Duration, tab, namePrefix+c.Name, tab,
			c.File+":"+strconv.Itoa(c.Line))
	}

	_ = w.Flush()
	return buf.String()
}

// A Tracer is used to follow requests across the system (or across systems).
// Requests must implement the Traceable interface and can be traced by invoking
// NewTrace(), which returns a Trace object initialized to publish itself to a
// util.Feed registered by the Tracer on completion.
type Tracer struct {
	origin string // owner of this Tracer, i.e. Host ID
	feed   *util.Feed
	now    func() time.Time
}

// NewTracer returns a new Tracer whose created Traces publish to the given feed.
// The origin is an identifier of the system, for instance a host ID.
func NewTracer(f *util.Feed, origin string) *Tracer {
	return &Tracer{
		origin: origin,
		now:    time.Now,
		feed:   f,
	}
}

var dummyTracer = &Tracer{
	now: time.Now,
}

// TODO(pmattis): Tracing every operation has a very noticeable performance
// impact. This is a hammer to disble it. We need to either optimize tracing,
// or make it sample only a fraction of operations or both.
var tracerDisabled = os.Getenv("DISABLE_TRACER") == "1"

// NewTrace creates a Trace for the given Traceable.
func (t *Tracer) NewTrace(family string, tracee Traceable) *Trace {
	if tracerDisabled {
		return nil
	}
	if t == nil {
		t = dummyTracer
	}
	return t.newTrace(family, tracee.TraceID(), tracee.TraceName())
}

func (t *Tracer) newTrace(family string, id, name string) *Trace {
	nt := ntrace.New(family, name)
	nt.SetMaxEvents(100)
	return &Trace{
		ID:     id,
		Name:   name,
		family: family,
		tracer: t,
		nTrace: nt,
	}
}
<commit_msg>Remove redundant nil check.<commit_after>// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Tobias Schottdorf (tobias.schottdorf@gmail.com)

package tracer

import (
	"bytes"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"

	ntrace "golang.org/x/net/trace"

	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/caller"
	"github.com/cockroachdb/cockroach/util/log"
)

// Node is the family used for the node.
const Node = "node"

// Coord is the family used for the coordinator/gateway.
const Coord = "coord"

// A Traceable object has a Trace identifier attached to it.
type Traceable interface {
	// TraceID is the unique ID for the tracee.
	TraceID() string
	// TraceName is a short and "sufficiently unique" human-readable
	// representation of the tracee.
	TraceName() string
}

// A TraceItem is an entry in a Trace.
type TraceItem struct {
	depth     int32
	Origin    string
	Name      string
	Timestamp time.Time
	Duration  time.Duration
	File      string
	Line      int
	Func      string
	HLC       time.Time // TODO(tschottdorf) HLC timestamp
}

// A Trace is created by a Tracer and records the path of a request within (a
// connected part of) the system. It contains the ID of the traced object and a
// slice of trace entries. In typical usage the Epoch() and Event() methods are
// called at various stages to record the path the associated request takes
// through the system; when the request goes out of scope, a call to Finalize
// marks the end of the Trace, at which point it publishes itself to an
// associated `util.Feed`. A request may create multiple Traces as it passes
// through different parts of a distributed systems.
// A Trace is not safe for concurrent access.
//
// TODO(tschottdorf): not allowing concurrent access is the right thing to do
// semantically, but we pass a Trace along with a context.Context, which
// explicitly encourages sharing of values. Might want to add that just for
// that reason, but for now it's convenient to let the race detector check what
// we do with the Trace.
type Trace struct {
	// IDs is the unique identifier for the request in this trace.
	ID string
	// Name is a human-readable identifier for the request in this trace.
	Name string
	// Content is a trace, containing call sites and timings in the order in
	// which they happened.
	Content []TraceItem
	tracer  *Tracer // origin tracer for clock, publishing...
	depth   int32
	family  string
	nTrace  ntrace.Trace
}

// Event adds an Epoch with zero duration to the Trace.
func (t *Trace) Event(name string) {
	if t == nil {
		return
	}
	t.epoch(name)()
	t.Content[len(t.Content)-1].Duration = 0
}

// SetError marks the request associated to the Trace as failed.
func (t *Trace) SetError() {
	if t != nil {
		t.nTrace.SetError()
	}
}

// Epoch begins a phase in the life of the Trace, starting the measurement of
// its duration. The returned function needs to be called when the measurement
// is complete; failure to do so results in a panic() when Finalize() is
// called. The suggested pattern of usage is, where possible,
// `defer trace.Epoch("<name>")()`.
func (t *Trace) Epoch(name string) func() {
	if t == nil {
		return func() {}
	}
	return t.epoch(name)
}

func (t *Trace) epoch(name string) func() {
	if t.depth < 0 {
		panic("use of finalized Trace:\n" + t.String())
	}
	t.depth++
	t.nTrace.LazyPrintf(name)
	pos := t.add(name)
	called := false
	return func() {
		if called {
			panic("epoch terminated twice")
		}
		called = true
		t.Content[pos].Duration = t.tracer.now().Sub(t.Content[pos].Timestamp)
		t.depth--
		t.nTrace.LazyPrintf(name + " [end]")
	}
}

// Finalize submits the Trace to the underlying feed. If there is an open
// Epoch, a panic occurs.
func (t *Trace) Finalize() {
	if t == nil {
		return
	}
	defer t.nTrace.Finish()
	if len(t.Content) == 0 {
		return
	}
	if r := recover(); r != nil {
		t.Epoch(fmt.Sprintf("panic: %v", r))
		panic(r)
	}
	if t.depth != 0 {
		panic("attempt to finalize unbalanced trace:\n" + t.String())
	}
	t.depth = math.MinInt32
	if t.tracer.feed != nil {
		t.tracer.feed.Publish(t) // by reference
	} else if log.V(2) {
		log.Info(t)
	}
}

func (t *Trace) add(name string) int {
	// Must be called with two callers to the client.
	// (Client->Event|Epoch->epoch->add)
	file, line, fun := caller.Lookup(3)
	t.Content = append(t.Content, TraceItem{
		depth:     t.depth,
		Origin:    t.tracer.origin,
		File:      file,
		Line:      line,
		Func:      fun,
		Timestamp: t.tracer.now(),
		Name:      name,
	})
	return len(t.Content) - 1
}

// Fork creates a new Trace, equal to (but autonomous from) that which created
// the original Trace.
func (t *Trace) Fork() *Trace {
	if t == nil {
		return nil
	}
	return t.tracer.newTrace(t.family, t.ID, t.Name)
}

// String implements fmt.Stringer. It prints a human-readable breakdown of the
// Trace.
func (t Trace) String() string {
	const tab = "\t"
	var buf bytes.Buffer
	w := tabwriter.NewWriter(&buf, 1, 1, 0, ' ', 0)
	fmt.Fprintln(w, "Trace", t.Name)
	fmt.Fprintln(w, "Origin", tab, "Ts", tab, "Dur", tab, "Desc", tab, "File")

	const traceTimeFormat = "15:04:05.000000"
	for _, c := range t.Content {
		var namePrefix string
		if c.depth > 1 {
			namePrefix = strings.Repeat("·", int(c.depth-1))
		}
		fmt.Fprintln(w, c.Origin, tab, c.Timestamp.Format(traceTimeFormat),
			tab, c.Duration, tab, namePrefix+c.Name, tab,
			c.File+":"+strconv.Itoa(c.Line))
	}

	_ = w.Flush()
	return buf.String()
}

// A Tracer is used to follow requests across the system (or across systems).
// Requests must implement the Traceable interface and can be traced by invoking
// NewTrace(), which returns a Trace object initialized to publish itself to a
// util.Feed registered by the Tracer on completion.
type Tracer struct {
	origin string // owner of this Tracer, i.e. Host ID
	feed   *util.Feed
	now    func() time.Time
}

// NewTracer returns a new Tracer whose created Traces publish to the given feed.
// The origin is an identifier of the system, for instance a host ID.
func NewTracer(f *util.Feed, origin string) *Tracer {
	return &Tracer{
		origin: origin,
		now:    time.Now,
		feed:   f,
	}
}

var dummyTracer = &Tracer{
	now: time.Now,
}

// TODO(pmattis): Tracing every operation has a very noticeable performance
// impact. This is a hammer to disble it. We need to either optimize tracing,
// or make it sample only a fraction of operations or both.
var tracerDisabled = os.Getenv("DISABLE_TRACER") == "1"

// NewTrace creates a Trace for the given Traceable.
func (t *Tracer) NewTrace(family string, tracee Traceable) *Trace {
	if tracerDisabled {
		return nil
	}
	if t == nil {
		t = dummyTracer
	}
	return t.newTrace(family, tracee.TraceID(), tracee.TraceName())
}

func (t *Tracer) newTrace(family string, id, name string) *Trace {
	nt := ntrace.New(family, name)
	nt.SetMaxEvents(100)
	return &Trace{
		ID:     id,
		Name:   name,
		family: family,
		tracer: t,
		nTrace: nt,
	}
}
<|endoftext|>


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

package tracer

import (
	"bytes"
	"fmt"
	"math"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"

	ntrace "golang.org/x/net/trace"

	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/caller"
	"github.com/cockroachdb/cockroach/util/log"
)

// Node is the family used for the node.
const Node = "node"

// Coord is the family used for the coordinator/gateway.
const Coord = "coord"

// A Traceable object has a Trace identifier attached to it.
type Traceable interface {
	// TraceID is the unique ID for the tracee.
	TraceID() string
	// TraceName is a short and "sufficiently unique" human-readable
	// representation of the tracee.
	TraceName() string
}

// A TraceItem is an entry in a Trace.
type TraceItem struct {
	depth     int32
	Origin    string
	Name      string
	Timestamp time.Time
	Duration  time.Duration
	File      string
	Line      int
	Func      string
	HLC       time.Time // TODO(tschottdorf) HLC timestamp
}

// A Trace is created by a Tracer and records the path of a request within (a
// connected part of) the system. It contains the ID of the traced object and a
// slice of trace entries. In typical usage the Epoch() and Event() methods are
// called at various stages to record the path the associated request takes
// through the system; when the request goes out of scope, a call to Finalize
// marks the end of the Trace, at which point it publishes itself to an
// associated `util.Feed`. A request may create multiple Traces as it passes
// through different parts of a distributed systems.
// A Trace is not safe for concurrent access.
//
// TODO(tschottdorf): not allowing concurrent access is the right thing to do
// semantically, but we pass a Trace along with a context.Context, which
// explicitly encourages sharing of values. Might want to add that just for
// that reason, but for now it's convenient to let the race detector check what
// we do with the Trace.
type Trace struct {
	// IDs is the unique identifier for the request in this trace.
	ID string
	// Name is a human-readable identifier for the request in this trace.
	Name string
	// Content is a trace, containing call sites and timings in the order in
	// which they happened.
	Content []TraceItem
	tracer  *Tracer // origin tracer for clock, publishing...
	depth   int32
	family  string
	nTrace  ntrace.Trace
}

// Event adds an Epoch with zero duration to the Trace.
func (t *Trace) Event(name string) {
	if t == nil {
		return
	}
	t.epoch(name)()
	t.Content[len(t.Content)-1].Duration = 0
}

// SetError marks the request associated to the Trace as failed.
func (t *Trace) SetError() {
	if t != nil {
		t.nTrace.SetError()
	}
}

// Epoch begins a phase in the life of the Trace, starting the measurement of
// its duration. The returned function needs to be called when the measurement
// is complete; failure to do so results in a panic() when Finalize() is
// called. The suggested pattern of usage is, where possible,
// `defer trace.Epoch("<name>")()`.
func (t *Trace) Epoch(name string) func() {
	if t == nil {
		return func() {}
	}
	return t.epoch(name)
}

func (t *Trace) epoch(name string) func() {
	if t.depth < 0 {
		panic("use of finalized Trace:\n" + t.String())
	}
	t.depth++
	t.nTrace.LazyPrintf(name)
	pos := t.add(name)
	called := false
	return func() {
		if called {
			panic("epoch terminated twice")
		}
		called = true
		t.Content[pos].Duration = t.tracer.now().Sub(t.Content[pos].Timestamp)
		t.depth--
		t.nTrace.LazyPrintf(name + " [end]")
	}
}

// Finalize submits the Trace to the underlying feed. If there is an open
// Epoch, a panic occurs.
func (t *Trace) Finalize() {
	defer t.nTrace.Finish()
	if t == nil || len(t.Content) == 0 {
		return
	}
	if r := recover(); r != nil {
		t.Epoch(fmt.Sprintf("panic: %v", r))
		panic(r)
	}
	if t.depth != 0 {
		panic("attempt to finalize unbalanced trace:\n" + t.String())
	}
	t.depth = math.MinInt32
	if t.tracer.feed != nil {
		t.tracer.feed.Publish(t) // by reference
	} else if log.V(2) {
		log.Info(t)
	}
}

func (t *Trace) add(name string) int {
	// Must be called with two callers to the client.
	// (Client->Event|Epoch->epoch->add)
	file, line, fun := caller.Lookup(3)
	t.Content = append(t.Content, TraceItem{
		depth:     t.depth,
		Origin:    t.tracer.origin,
		File:      file,
		Line:      line,
		Func:      fun,
		Timestamp: t.tracer.now(),
		Name:      name,
	})
	return len(t.Content) - 1
}

// Fork creates a new Trace, equal to (but autonomous from) that which created
// the original Trace.
func (t *Trace) Fork() *Trace {
	if t == nil {
		return nil
	}
	return t.tracer.newTrace(t.family, t.ID, t.Name)
}

// String implements fmt.Stringer. It prints a human-readable breakdown of the
// Trace.
func (t Trace) String() string {
	const tab = "\t"
	var buf bytes.Buffer
	w := tabwriter.NewWriter(&buf, 1, 1, 0, ' ', 0)
	fmt.Fprintln(w, "Trace", t.Name)
	fmt.Fprintln(w, "Origin", tab, "Ts", tab, "Dur", tab, "Desc", tab, "File")

	const traceTimeFormat = "15:04:05.000000"
	for _, c := range t.Content {
		var namePrefix string
		if c.depth > 1 {
			namePrefix = strings.Repeat("·", int(c.depth-1))
		}
		fmt.Fprintln(w, c.Origin, tab, c.Timestamp.Format(traceTimeFormat),
			tab, c.Duration, tab, namePrefix+c.Name, tab,
			c.File+":"+strconv.Itoa(c.Line))
	}

	_ = w.Flush()
	return buf.String()
}

// A Tracer is used to follow requests across the system (or across systems).
// Requests must implement the Traceable interface and can be traced by invoking
// NewTrace(), which returns a Trace object initialized to publish itself to a
// util.Feed registered by the Tracer on completion.
type Tracer struct {
	origin string // owner of this Tracer, i.e. Host ID
	feed   *util.Feed
	now    func() time.Time
}

// NewTracer returns a new Tracer whose created Traces publish to the given feed.
// The origin is an identifier of the system, for instance a host ID.
func NewTracer(f *util.Feed, origin string) *Tracer {
	return &Tracer{
		origin: origin,
		now:    time.Now,
		feed:   f,
	}
}

var dummyTracer = &Tracer{
	now: time.Now,
}

// NewTrace creates a Trace for the given Traceable.
func (t *Tracer) NewTrace(family string, tracee Traceable) *Trace {
	if t == nil {
		t = dummyTracer
	}
	return t.newTrace(family, tracee.TraceID(), tracee.TraceName())
}

func (t *Tracer) newTrace(family string, id, name string) *Trace {
	nt := ntrace.New(family, name)
	nt.SetMaxEvents(100)
	return &Trace{
		ID:     id,
		Name:   name,
		family: family,
		tracer: t,
		nTrace: nt,
	}
}
<commit_msg>util/tracer: Add DISABLE_TRACER env variable.<commit_after>// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Tobias Schottdorf (tobias.schottdorf@gmail.com)

package tracer

import (
	"bytes"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"

	ntrace "golang.org/x/net/trace"

	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/caller"
	"github.com/cockroachdb/cockroach/util/log"
)

// Node is the family used for the node.
const Node = "node"

// Coord is the family used for the coordinator/gateway.
const Coord = "coord"

// A Traceable object has a Trace identifier attached to it.
type Traceable interface {
	// TraceID is the unique ID for the tracee.
	TraceID() string
	// TraceName is a short and "sufficiently unique" human-readable
	// representation of the tracee.
	TraceName() string
}

// A TraceItem is an entry in a Trace.
type TraceItem struct {
	depth     int32
	Origin    string
	Name      string
	Timestamp time.Time
	Duration  time.Duration
	File      string
	Line      int
	Func      string
	HLC       time.Time // TODO(tschottdorf) HLC timestamp
}

// A Trace is created by a Tracer and records the path of a request within (a
// connected part of) the system. It contains the ID of the traced object and a
// slice of trace entries. In typical usage the Epoch() and Event() methods are
// called at various stages to record the path the associated request takes
// through the system; when the request goes out of scope, a call to Finalize
// marks the end of the Trace, at which point it publishes itself to an
// associated `util.Feed`. A request may create multiple Traces as it passes
// through different parts of a distributed systems.
// A Trace is not safe for concurrent access.
//
// TODO(tschottdorf): not allowing concurrent access is the right thing to do
// semantically, but we pass a Trace along with a context.Context, which
// explicitly encourages sharing of values. Might want to add that just for
// that reason, but for now it's convenient to let the race detector check what
// we do with the Trace.
type Trace struct {
	// IDs is the unique identifier for the request in this trace.
	ID string
	// Name is a human-readable identifier for the request in this trace.
	Name string
	// Content is a trace, containing call sites and timings in the order in
	// which they happened.
	Content []TraceItem
	tracer  *Tracer // origin tracer for clock, publishing...
	depth   int32
	family  string
	nTrace  ntrace.Trace
}

// Event adds an Epoch with zero duration to the Trace.
func (t *Trace) Event(name string) {
	if t == nil {
		return
	}
	t.epoch(name)()
	t.Content[len(t.Content)-1].Duration = 0
}

// SetError marks the request associated to the Trace as failed.
func (t *Trace) SetError() {
	if t != nil {
		t.nTrace.SetError()
	}
}

// Epoch begins a phase in the life of the Trace, starting the measurement of
// its duration. The returned function needs to be called when the measurement
// is complete; failure to do so results in a panic() when Finalize() is
// called. The suggested pattern of usage is, where possible,
// `defer trace.Epoch("<name>")()`.
func (t *Trace) Epoch(name string) func() {
	if t == nil {
		return func() {}
	}
	return t.epoch(name)
}

func (t *Trace) epoch(name string) func() {
	if t.depth < 0 {
		panic("use of finalized Trace:\n" + t.String())
	}
	t.depth++
	t.nTrace.LazyPrintf(name)
	pos := t.add(name)
	called := false
	return func() {
		if called {
			panic("epoch terminated twice")
		}
		called = true
		t.Content[pos].Duration = t.tracer.now().Sub(t.Content[pos].Timestamp)
		t.depth--
		t.nTrace.LazyPrintf(name + " [end]")
	}
}

// Finalize submits the Trace to the underlying feed. If there is an open
// Epoch, a panic occurs.
func (t *Trace) Finalize() {
	if t == nil {
		return
	}
	defer t.nTrace.Finish()
	if t == nil || len(t.Content) == 0 {
		return
	}
	if r := recover(); r != nil {
		t.Epoch(fmt.Sprintf("panic: %v", r))
		panic(r)
	}
	if t.depth != 0 {
		panic("attempt to finalize unbalanced trace:\n" + t.String())
	}
	t.depth = math.MinInt32
	if t.tracer.feed != nil {
		t.tracer.feed.Publish(t) // by reference
	} else if log.V(2) {
		log.Info(t)
	}
}

func (t *Trace) add(name string) int {
	// Must be called with two callers to the client.
	// (Client->Event|Epoch->epoch->add)
	file, line, fun := caller.Lookup(3)
	t.Content = append(t.Content, TraceItem{
		depth:     t.depth,
		Origin:    t.tracer.origin,
		File:      file,
		Line:      line,
		Func:      fun,
		Timestamp: t.tracer.now(),
		Name:      name,
	})
	return len(t.Content) - 1
}

// Fork creates a new Trace, equal to (but autonomous from) that which created
// the original Trace.
func (t *Trace) Fork() *Trace {
	if t == nil {
		return nil
	}
	return t.tracer.newTrace(t.family, t.ID, t.Name)
}

// String implements fmt.Stringer. It prints a human-readable breakdown of the
// Trace.
func (t Trace) String() string {
	const tab = "\t"
	var buf bytes.Buffer
	w := tabwriter.NewWriter(&buf, 1, 1, 0, ' ', 0)
	fmt.Fprintln(w, "Trace", t.Name)
	fmt.Fprintln(w, "Origin", tab, "Ts", tab, "Dur", tab, "Desc", tab, "File")

	const traceTimeFormat = "15:04:05.000000"
	for _, c := range t.Content {
		var namePrefix string
		if c.depth > 1 {
			namePrefix = strings.Repeat("·", int(c.depth-1))
		}
		fmt.Fprintln(w, c.Origin, tab, c.Timestamp.Format(traceTimeFormat),
			tab, c.Duration, tab, namePrefix+c.Name, tab,
			c.File+":"+strconv.Itoa(c.Line))
	}

	_ = w.Flush()
	return buf.String()
}

// A Tracer is used to follow requests across the system (or across systems).
// Requests must implement the Traceable interface and can be traced by invoking
// NewTrace(), which returns a Trace object initialized to publish itself to a
// util.Feed registered by the Tracer on completion.
type Tracer struct {
	origin string // owner of this Tracer, i.e. Host ID
	feed   *util.Feed
	now    func() time.Time
}

// NewTracer returns a new Tracer whose created Traces publish to the given feed.
// The origin is an identifier of the system, for instance a host ID.
func NewTracer(f *util.Feed, origin string) *Tracer {
	return &Tracer{
		origin: origin,
		now:    time.Now,
		feed:   f,
	}
}

var dummyTracer = &Tracer{
	now: time.Now,
}

// TODO(pmattis): Tracing every operation has a very noticeable performance
// impact. This is a hammer to disble it. We need to either optimize tracing,
// or make it sample only a fraction of operations or both.
var tracerDisabled = os.Getenv("DISABLE_TRACER") == "1"

// NewTrace creates a Trace for the given Traceable.
func (t *Tracer) NewTrace(family string, tracee Traceable) *Trace {
	if tracerDisabled {
		return nil
	}
	if t == nil {
		t = dummyTracer
	}
	return t.newTrace(family, tracee.TraceID(), tracee.TraceName())
}

func (t *Tracer) newTrace(family string, id, name string) *Trace {
	nt := ntrace.New(family, name)
	nt.SetMaxEvents(100)
	return &Trace{
		ID:     id,
		Name:   name,
		family: family,
		tracer: t,
		nTrace: nt,
	}
}
<|endoftext|>


<commit_before>package generate

import (
	"errors"

	"github.com/gobuffalo/buffalo/generators/resource"
	"github.com/gobuffalo/makr"
	"github.com/markbates/inflect"
	"github.com/spf13/cobra"
)

const resourceExamples = `

$ buffalo g resource users
Generates:

- actions/users.go
- actions/users_test.go
- models/user.go
- models/user_test.go
- migrations/XXXXX_create_table_users.fizz
- migrations/XXXXX_drop_table_users.fizz

$ buffalo g resource users --skip-migration
Generates:

- actions/users.go
- actions/users_test.go
- models/user.go
- models/user_test.go

$ buffalo g resource users --skip-model
Generates:

- actions/users.go
- actions/users_test.go

`

//SkipResourceMigration allows to generate a resource without the migration.
var SkipResourceMigration = false

//SkipResourceModel allows to generate a resource without the model and Migration.
var SkipResourceModel = false

// ResourceCmd generates a new actions/resource file and a stub test.
var ResourceCmd = &cobra.Command{
	Use:     "resource [name]",
	Example: resourceExamples,
	Aliases: []string{"r"},
	Short:   "Generates a new actions/resource file",
	RunE: func(cmd *cobra.Command, args []string) error {
		if len(args) == 0 {
			return errors.New("you must specify a resource name")
		}

		name := args[0]
		data := makr.Data{
			"name":          name,
			"singular":      inflect.Singularize(name),
			"plural":        inflect.Pluralize(name),
			"camel":         inflect.Camelize(name),
			"under":         inflect.Underscore(name),
			"downFirstCap":  inflect.CamelizeDownFirst(name),
			"actions":       []string{"List", "Show", "New", "Create", "Edit", "Update", "Destroy"},
			"args":          args,
			"skipMigration": SkipResourceMigration,
			"skipModel":     SkipResourceModel,
		}

		g, err := resource.New(data)
		if err != nil {
			return err
		}
		return g.Run(".", data)
	},
}
<commit_msg>[cleaning] changing docs examples<commit_after>package generate

import (
	"errors"

	"github.com/gobuffalo/buffalo/generators/resource"
	"github.com/gobuffalo/makr"
	"github.com/markbates/inflect"
	"github.com/spf13/cobra"
)

const resourceExamples = `$ buffalo g resource users
Generates:

- actions/users.go
- actions/users_test.go
- models/user.go
- models/user_test.go
- migrations/XXXXX_create_table_users.fizz
- migrations/XXXXX_drop_table_users.fizz

$ buffalo g resource users --skip-migration
Generates:

- actions/users.go
- actions/users_test.go
- models/user.go
- models/user_test.go

$ buffalo g resource users --skip-model
Generates:

- actions/users.go
- actions/users_test.go`

//SkipResourceMigration allows to generate a resource without the migration.
var SkipResourceMigration = false

//SkipResourceModel allows to generate a resource without the model and Migration.
var SkipResourceModel = false

// ResourceCmd generates a new actions/resource file and a stub test.
var ResourceCmd = &cobra.Command{
	Use:     "resource [name]",
	Example: resourceExamples,
	Aliases: []string{"r"},
	Short:   "Generates a new actions/resource file",
	RunE: func(cmd *cobra.Command, args []string) error {
		if len(args) == 0 {
			return errors.New("you must specify a resource name")
		}

		name := args[0]
		data := makr.Data{
			"name":          name,
			"singular":      inflect.Singularize(name),
			"plural":        inflect.Pluralize(name),
			"camel":         inflect.Camelize(name),
			"under":         inflect.Underscore(name),
			"downFirstCap":  inflect.CamelizeDownFirst(name),
			"actions":       []string{"List", "Show", "New", "Create", "Edit", "Update", "Destroy"},
			"args":          args,
			"skipMigration": SkipResourceMigration,
			"skipModel":     SkipResourceModel,
		}

		g, err := resource.New(data)
		if err != nil {
			return err
		}
		return g.Run(".", data)
	},
}
<|endoftext|>


<commit_before>package command

import (
	"github.com/codegangsta/cli"
	"log"

	. "github.com/foostan/fileconsul/fileconsul"
	"path/filepath"
)

var RegisterFlags = []cli.Flag{
	cli.StringFlag{
		Name:  "addr",
		Value: "localhost:8500",
		Usage: "consul HTTP API address with port",
	},
	cli.StringFlag{
		Name:  "dc",
		Value: "dc1",
		Usage: "consul datacenter, uses local if blank",
	},
	cli.StringFlag{
		Name:  "prefix",
		Value: "fileconsul",
		Usage: "reading file status from Consul's K/V store with the given prefix",
	},
	cli.StringFlag{
		Name:  "path",
		Usage: "registered file path, full file path is `prefix + path` in K/V store",
	},
	cli.StringFlag{
		Name:  "url",
		Usage: "registered file url",
	},
}

func RegisterCommand(c *cli.Context) {
	addr := c.String("addr")
	dc := c.String("dc")
	prefix := c.String("prefix")
	path := c.String("path")
	url := c.String("url")

	client, err := NewClient(&ClientConfig{
		ConsulAddr: addr,
		ConsulDC:   dc,
	})
	if err != nil {
		log.Fatal(err)
	}

	hash, err:= UrlToHash(url)
	if err != nil {
		log.Fatal(err)
	}

	mfValue := MFValue{Url: url, Hash: hash}

	err = client.PutKV(filepath.Join(prefix, path), mfValue.ToStr())
	if err != nil {
		log.Fatal(err)
	}
}
<commit_msg>Validate flags of register command<commit_after>package command

import (
	"github.com/codegangsta/cli"
	"log"

	. "github.com/foostan/fileconsul/fileconsul"
	"path/filepath"
)

var RegisterFlags = []cli.Flag{
	cli.StringFlag{
		Name:  "addr",
		Value: "localhost:8500",
		Usage: "consul HTTP API address with port",
	},
	cli.StringFlag{
		Name:  "dc",
		Value: "dc1",
		Usage: "consul datacenter, uses local if blank",
	},
	cli.StringFlag{
		Name:  "prefix",
		Value: "fileconsul",
		Usage: "reading file status from Consul's K/V store with the given prefix",
	},
	cli.StringFlag{
		Name:  "path",
		Usage: "registered file path, full file path is `prefix + path` in K/V store",
	},
	cli.StringFlag{
		Name:  "url",
		Usage: "registered file url",
	},
}

func RegisterCommand(c *cli.Context) {
	addr := c.String("addr")
	dc := c.String("dc")
	prefix := c.String("prefix")
	path := c.String("path")
	if path == "" {
		log.Fatalf("Error missing flag 'path'")
	}
	url := c.String("url")
	if url == "" {
		log.Fatalf("Error missing flag 'url'")
	}

	client, err := NewClient(&ClientConfig{
		ConsulAddr: addr,
		ConsulDC:   dc,
	})
	if err != nil {
		log.Fatal(err)
	}

	hash, err:= UrlToHash(url)
	if err != nil {
		log.Fatal(err)
	}

	mfValue := MFValue{Url: url, Hash: hash}

	err = client.PutKV(filepath.Join(prefix, path), mfValue.ToStr())
	if err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package turnpike

import (
	"math/rand"
	"time"
)

const (
	// --- Interactions ---

	// Peer provided an incorrect URI for any URI-based attribute of WAMP message,
	// such as realm, topic or procedure.
	WAMP_ERROR_INVALID_URI = URI("wamp.error.invalid_uri")

	// A Dealer could not perform a call, since no procedure is currently
	// registered under the given URI.
	WAMP_ERROR_NO_SUCH_PROCEDURE = URI("wamp.error.no_such_procedure")

	// A procedure could not be registered, since a procedure with the given URI is already registered.
	WAMP_ERROR_PROCEDURE_ALREADY_EXISTS = URI("wamp.error.procedure_already_exists")

	// A Dealer could not perform an unregister, since the given registration is not active.
	WAMP_ERROR_NO_SUCH_REGISTRATION = URI("wamp.error.no_such_registration")

	// A Broker could not perform an unsubscribe, since the given subscription is not active.
	WAMP_ERROR_NO_SUCH_SUBSCRIPTION = URI("wamp.error.no_such_subscription")

	// A call failed, since the given argument types or values are not acceptable to the called
	// procedure - in which case the Callee may throw this error. Or a Router performing payload
	// validation checked the payload (args / kwargs) of a call, call result, call error or publish,
	// and the payload did not conform - in which case the Router may throw this error.
	WAMP_ERROR_INVALID_ARGUMENT = URI("wamp.error.invalid_argument")

	// --- Session Close ---

	// The Peer is shutting down completely - used as a GOODBYE (or ABORT) reason.
	WAMP_ERROR_SYSTEM_SHUTDOWN = URI("wamp.error.system_shutdown")

	// The Peer wants to leave the realm - used as a GOODBYE reason.
	WAMP_ERROR_CLOSE_REALM = URI("wamp.error.close_realm")

	// A Peer acknowledges ending of a session - used as a GOOBYE reply reason.
	WAMP_ERROR_GOODBYE_AND_OUT = URI("wamp.error.goodbye_and_out")

	// --- Authorization ---

	// A join, call, register, publish or subscribe failed, since the Peer is not authorized to
	// perform the operation.
	WAMP_ERROR_NOT_AUTHORIZED = URI("wamp.error.not_authorized")

	// A Dealer or Broker could not determine if the Peer is authorized to perform a join, call,
	// register, publish or subscribe, since the authorization operation itself failed. E.g. a custom
	// authorizer ran into an error.
	WAMP_ERROR_AUTHORIZATION_FAILED = URI("wamp.error.authorization_failed")

	// Peer wanted to join a non-existing realm (and the Router did not allow to auto-create the realm)
	WAMP_ERROR_NO_SUCH_REALM = URI("wamp.error.no_such_realm")

	// A Peer was to be authenticated under a Role that does not (or no longer) exists on the Router.
	// For example, the Peer was successfully authenticated, but the Role configured does not exists -
	// hence there is some misconfiguration in the Router.
	WAMP_ERROR_NO_SUCH_ROLE = URI("wamp.error.no_such_role")
)

const (
	maxId = 1 << 53
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

// NewID generates a random WAMP ID.
func NewID() ID {
	return ID(rand.Intn(maxId))
}
<commit_msg>Knock size of maxId down to fit in ARM int<commit_after>package turnpike

import (
	"math/rand"
	"time"
)

const (
	// --- Interactions ---

	// Peer provided an incorrect URI for any URI-based attribute of WAMP message,
	// such as realm, topic or procedure.
	WAMP_ERROR_INVALID_URI = URI("wamp.error.invalid_uri")

	// A Dealer could not perform a call, since no procedure is currently
	// registered under the given URI.
	WAMP_ERROR_NO_SUCH_PROCEDURE = URI("wamp.error.no_such_procedure")

	// A procedure could not be registered, since a procedure with the given URI is already registered.
	WAMP_ERROR_PROCEDURE_ALREADY_EXISTS = URI("wamp.error.procedure_already_exists")

	// A Dealer could not perform an unregister, since the given registration is not active.
	WAMP_ERROR_NO_SUCH_REGISTRATION = URI("wamp.error.no_such_registration")

	// A Broker could not perform an unsubscribe, since the given subscription is not active.
	WAMP_ERROR_NO_SUCH_SUBSCRIPTION = URI("wamp.error.no_such_subscription")

	// A call failed, since the given argument types or values are not acceptable to the called
	// procedure - in which case the Callee may throw this error. Or a Router performing payload
	// validation checked the payload (args / kwargs) of a call, call result, call error or publish,
	// and the payload did not conform - in which case the Router may throw this error.
	WAMP_ERROR_INVALID_ARGUMENT = URI("wamp.error.invalid_argument")

	// --- Session Close ---

	// The Peer is shutting down completely - used as a GOODBYE (or ABORT) reason.
	WAMP_ERROR_SYSTEM_SHUTDOWN = URI("wamp.error.system_shutdown")

	// The Peer wants to leave the realm - used as a GOODBYE reason.
	WAMP_ERROR_CLOSE_REALM = URI("wamp.error.close_realm")

	// A Peer acknowledges ending of a session - used as a GOOBYE reply reason.
	WAMP_ERROR_GOODBYE_AND_OUT = URI("wamp.error.goodbye_and_out")

	// --- Authorization ---

	// A join, call, register, publish or subscribe failed, since the Peer is not authorized to
	// perform the operation.
	WAMP_ERROR_NOT_AUTHORIZED = URI("wamp.error.not_authorized")

	// A Dealer or Broker could not determine if the Peer is authorized to perform a join, call,
	// register, publish or subscribe, since the authorization operation itself failed. E.g. a custom
	// authorizer ran into an error.
	WAMP_ERROR_AUTHORIZATION_FAILED = URI("wamp.error.authorization_failed")

	// Peer wanted to join a non-existing realm (and the Router did not allow to auto-create the realm)
	WAMP_ERROR_NO_SUCH_REALM = URI("wamp.error.no_such_realm")

	// A Peer was to be authenticated under a Role that does not (or no longer) exists on the Router.
	// For example, the Peer was successfully authenticated, but the Role configured does not exists -
	// hence there is some misconfiguration in the Router.
	WAMP_ERROR_NO_SUCH_ROLE = URI("wamp.error.no_such_role")
)

const (
	maxId = 1 << 29
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

// NewID generates a random WAMP ID.
func NewID() ID {
	return ID(rand.Intn(maxId))
}
<|endoftext|>


<commit_before>package main

import (
    "strconv"
)

type ArticleSlice []*Article

func (as ArticleSlice) Len() int {
	return len(as)
}

func (as ArticleSlice) Less(i, j int) bool {
	return as[i].Time.Before(as[j].Time)
}

func (as ArticleSlice) Swap(i, j int) {
	as[i], as[j] = as[j], as[i]
}

func getPageNum(params map[string]string) (page int) {
    //the default page is the first one
    page = 1

    if p, ok := params["page"]; ok{
        pint64, err := strconv.ParseInt(p, 0, 0)
        if err != nil {
            return 1;
        }
        page = int(pint64)
    }
    return
}

func paginate(articles ArticleSlice, numPerPage, page int) (rArticles ArticleSlice, prev, next int) {
    start := (page-1)*numPerPage
    end := start + numPerPage
    prev, next = -1, page+1
    if len(articles) == 0 {
        rArticles = articles
        next = -1
        return
    }

    if start != 0 {
        prev = page - 1
    }

    if end >= len(articles){
        rArticles = articles[start:]
        next = -1
    } else {
        rArticles = articles[start:end]
    }
    return
}
<commit_msg>Adjusted pagination<commit_after>package main

import (
    "strconv"
)

type ArticleSlice []*Article

func (as ArticleSlice) Len() int {
	return len(as)
}

func (as ArticleSlice) Less(i, j int) bool {
	return as[i].Time.Before(as[j].Time)
}

func (as ArticleSlice) Swap(i, j int) {
	as[i], as[j] = as[j], as[i]
}

func getPageNum(params map[string]string) (page int) {
    //the default page is the first one
    page = 1

    if p, ok := params["page"]; ok{
        pint64, err := strconv.ParseInt(p, 0, 0)
        if err != nil {
            return 1;
        }
        page = int(pint64)
    }
    return
}

func paginate(articles ArticleSlice, numPerPage, page int) (rArticles ArticleSlice, prev, next int) {
    start := (page-1)*numPerPage
    end := start + numPerPage
    prev, next = -1, page+1
    if len(articles) == 0 {
        rArticles = articles
        next = -1
        return
    }

    if start != 0 {
        prev = page - 1
    }

    if end >= len(articles){
        rArticles = articles[start:]
        next = -1
    } else if start > len(articles) {
        rArticles = make(ArticleSlice, 0)
        next = -1
    } else {
        rArticles = articles[start:end]
    }
    return
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/mgutz/logxi/v1"
)

func sendExternal(obj map[string]interface{}) {
	// normally you would send this to an external service like InfluxDB
	// or some logging framework. Let's filter out some data.
	fmt.Printf("Time: %s Level: %s Message: %s\n",
		obj[log.TimeKey],
		obj[log.LevelKey],
		obj[log.MessageKey],
	)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	dec := json.NewDecoder(r)
	for {
		var obj map[string]interface{}
		if err := dec.Decode(&obj); err == io.EOF {
			break
		} else if err != nil {
			log.InternalLog.Fatal("Could not decode", "err", err)
		}
		sendExternal(obj)
	}
}
<commit_msg>Change filter example to use KeyMap<commit_after>package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/mgutz/logxi/v1"
)

func sendExternal(obj map[string]interface{}) {
	// normally you would send this to an external service like InfluxDB
	// or some logging framework. Let's filter out some data.
	fmt.Printf("Time: %s Level: %s Message: %s\n",
		obj[log.KeyMap.Time],
		obj[log.KeyMap.Level],
		obj[log.KeyMap.Message],
	)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	dec := json.NewDecoder(r)
	for {
		var obj map[string]interface{}
		if err := dec.Decode(&obj); err == io.EOF {
			break
		} else if err != nil {
			log.InternalLog.Fatal("Could not decode", "err", err)
		}
		sendExternal(obj)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/nsf/termbox-go"
	"strings"
)

const (
	background = `
    WWWWWWWWWWWW WWWWWW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WWWWWW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WWWWWWWWWWWW
	`
	currentMinoXOffset, currentMinoYOffset = 5, 2
	nextMinoXOffset, nextMinoYOffset       = 18, 1
)

var (
	colorMapping = map[rune]termbox.Attribute{
		'k': termbox.ColorBlack,
		'K': termbox.ColorBlack | termbox.AttrBold,
		'r': termbox.ColorRed,
		'R': termbox.ColorRed | termbox.AttrBold,
		'g': termbox.ColorGreen,
		'G': termbox.ColorGreen | termbox.AttrBold,
		'y': termbox.ColorYellow,
		'Y': termbox.ColorYellow | termbox.AttrBold,
		'b': termbox.ColorBlue,
		'B': termbox.ColorBlue | termbox.AttrBold,
		'm': termbox.ColorMagenta,
		'M': termbox.ColorMagenta | termbox.AttrBold,
		'c': termbox.ColorCyan,
		'C': termbox.ColorCyan | termbox.AttrBold,
		'w': termbox.ColorWhite,
		'W': termbox.ColorWhite | termbox.AttrBold,
	}
)

func refreshScreen() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)

	drawCells(background, 0, 0)
	drawCurrentMino()
	drawNextMino()

	termbox.Flush()
}

func drawCurrentMino() {
	drawMino(currentMino, currentMinoXOffset, currentMinoYOffset)
}

func drawNextMino() {
	drawMino(nextMino, nextMinoXOffset-nextMino.x, nextMinoYOffset-nextMino.y)
}

func drawMino(mino *Mino, xOffset, yOffset int) {
	lines := strings.Split(mino.block, "\n")

	for y, line := range lines {
		for x, char := range line {
			color := colorByChar(char)

			if color != termbox.ColorDefault {
				termbox.SetCell(2*(x+mino.x+xOffset)-1, y+mino.y+yOffset, '▓', color, color^termbox.AttrBold)
				termbox.SetCell(2*(x+mino.x+xOffset), y+mino.y+yOffset, ' ', color, color^termbox.AttrBold)
			}
		}
	}
}

func drawCells(text string, left, top int) {
	lines := strings.Split(text, "\n")

	for y, line := range lines {
		for x, char := range line {
			drawCell(left+x, top+y, colorByChar(char))
		}
	}
}

func drawCell(x, y int, color termbox.Attribute) {
	termbox.SetCell(2*x-1, y, ' ', termbox.ColorDefault, color)
	termbox.SetCell(2*x, y, ' ', termbox.ColorDefault, color)
}

func colorByChar(ch rune) termbox.Attribute {
	return colorMapping[ch]
}
<commit_msg>Fix next mino place<commit_after>package main

import (
	"github.com/nsf/termbox-go"
	"strings"
)

const (
	background = `
    WWWWWWWWWWWW WWWWWW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WkkkkW
    WkkkkkkkkkkW WWWWWW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WkkkkkkkkkkW
    WWWWWWWWWWWW
	`
	currentMinoXOffset, currentMinoYOffset = 5, 2
	nextMinoXOffset, nextMinoYOffset       = 18, 2
)

var (
	colorMapping = map[rune]termbox.Attribute{
		'k': termbox.ColorBlack,
		'K': termbox.ColorBlack | termbox.AttrBold,
		'r': termbox.ColorRed,
		'R': termbox.ColorRed | termbox.AttrBold,
		'g': termbox.ColorGreen,
		'G': termbox.ColorGreen | termbox.AttrBold,
		'y': termbox.ColorYellow,
		'Y': termbox.ColorYellow | termbox.AttrBold,
		'b': termbox.ColorBlue,
		'B': termbox.ColorBlue | termbox.AttrBold,
		'm': termbox.ColorMagenta,
		'M': termbox.ColorMagenta | termbox.AttrBold,
		'c': termbox.ColorCyan,
		'C': termbox.ColorCyan | termbox.AttrBold,
		'w': termbox.ColorWhite,
		'W': termbox.ColorWhite | termbox.AttrBold,
	}
)

func refreshScreen() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)

	drawCells(background, 0, 0)
	drawCurrentMino()
	drawNextMino()

	termbox.Flush()
}

func drawCurrentMino() {
	drawMino(currentMino, currentMinoXOffset, currentMinoYOffset)
}

func drawNextMino() {
	drawMino(nextMino, nextMinoXOffset-nextMino.x, nextMinoYOffset-nextMino.y)
}

func drawMino(mino *Mino, xOffset, yOffset int) {
	lines := strings.Split(mino.block, "\n")

	for y, line := range lines {
		for x, char := range line {
			color := colorByChar(char)

			if color != termbox.ColorDefault {
				termbox.SetCell(2*(x+mino.x+xOffset)-1, y+mino.y+yOffset, '▓', color, color^termbox.AttrBold)
				termbox.SetCell(2*(x+mino.x+xOffset), y+mino.y+yOffset, ' ', color, color^termbox.AttrBold)
			}
		}
	}
}

func drawCells(text string, left, top int) {
	lines := strings.Split(text, "\n")

	for y, line := range lines {
		for x, char := range line {
			drawCell(left+x, top+y, colorByChar(char))
		}
	}
}

func drawCell(x, y int, color termbox.Attribute) {
	termbox.SetCell(2*x-1, y, ' ', termbox.ColorDefault, color)
	termbox.SetCell(2*x, y, ' ', termbox.ColorDefault, color)
}

func colorByChar(ch rune) termbox.Attribute {
	return colorMapping[ch]
}
<|endoftext|>