<commit_before>package build

import (
	"errors"
	"fmt"
	"go/build"
	"koding/tools/deps"
	"koding/tools/util"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

type Deb struct {
	// App informations
	AppName string
	Version string
	Desc    string
	Arch    string

	// Build fields
	Output          string
	ImportPath      string
	InstallPrefix   string
	BuildFolder     string
	Files           string
	UpstartScript   string
	DebianTemplates map[string]string
	Debug           bool
}

// Deb is building a new .deb package with the provided tarFile It returns the
// created filename of the .deb file.
func (d *Deb) Build() (string, error) {
	defer d.cleanDebianBuild()

	d.BuildFolder = deps.DepsGoPath
	d.Arch = debArch()
	d.Desc = d.AppName + " Kite"
	d.DebianTemplates = d.debianTemplates()
	d.Output = fmt.Sprintf("%s_%s_%s.deb", d.AppName, d.Version, d.Arch)

	fmt.Println("preparing build folders")
	if err := d.createDebianDir(); err != nil {
		return "", err
	}

	fmt.Println("preparing install folders")
	if err := d.createInstallDir(); err != nil {
		return "", err
	}

	// finally build with debuild to create .deb file
	cmd := exec.Command("debuild", "-us", "-uc")
	cmd.Dir = d.BuildFolder

	if d.Debug {
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
	}

	fmt.Println("starting build process ")
	err := cmd.Start()
	if err != nil {
		return "", err
	}

	done := make(chan bool)
	go func() {
		err := cmd.Wait()
		if err != nil {
			log.Fatalln(err) // exit if something goes wrong
		}
		done <- true
	}()

	// check the result every two seconds
	ticker := time.NewTicker(2 * time.Second).C

	for {
		select {
		case <-ticker:
			fmt.Printf(".  ")
		case <-done:
			fmt.Printf("\n\n")
			return d.Output, nil
		}
	}
}

func (d *Deb) cleanDebianBuild() {
	os.RemoveAll(d.BuildFolder)

	exts := []string{"build", "changes"}
	output := fmt.Sprintf("%s_%s_%s", d.AppName, d.Version, d.Arch)
	for _, ext := range exts {
		os.Remove(output + "." + ext)
	}

	exts = []string{"dsc", "tar.gz"}
	output = fmt.Sprintf("%s_%s", d.AppName, d.Version)
	for _, ext := range exts {
		os.Remove(output + "." + ext)
	}
}

func (d *Deb) createInstallDir() error {
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		return errors.New("GOPATH is not set")
	}

	dp, err := deps.LoadDeps(deps.NewPkg(d.ImportPath, d.AppName))
	if err != nil {
		return err
	}

	err = dp.InstallDeps()
	if err != nil {
		return err
	}

	appFolder := filepath.Join(dp.BuildGoPath, d.AppName)
	if d.Files != "" {
		files := strings.Split(d.Files, ",")
		for _, path := range files {
			err := util.Copy(path, appFolder)
			if err != nil {
				log.Println("copy assets", err)
			}
		}
	}

	if d.UpstartScript != "" {
		upstartPath := filepath.Join(d.BuildFolder, "debian/")
		upstartFile := filepath.Base(d.UpstartScript)

		err := util.Copy(d.UpstartScript, upstartPath)
		if err != nil {
			log.Println("copy assets", err)
		}

		oldFile := filepath.Join(upstartPath, upstartFile)
		newFile := filepath.Join(upstartPath, d.AppName+".upstart")

		err = os.Rename(oldFile, newFile)
		if err != nil {
			return err
		}
	}

	// move files to installprefix
	os.MkdirAll(filepath.Join(d.BuildFolder, d.InstallPrefix), 0755)
	installFolder := filepath.Join(d.BuildFolder, d.InstallPrefix, d.AppName)
	if err := os.Rename(appFolder, installFolder); err != nil {
		return err
	}

	return nil
}

func (d *Deb) createDebianDir() error {
	debianFolder := filepath.Join(d.BuildFolder, "debian")
	os.MkdirAll(debianFolder, 0755)

	if err := d.createDebianFile("control"); err != nil {
		return err
	}

	if err := d.createDebianFile("rules"); err != nil {
		return err
	}

	// make debian/rules executable
	os.Chmod(filepath.Join(debianFolder, "rules"), 0755)

	if err := d.createDebianFile("compat"); err != nil {
		return err
	}

	if err := d.createDebianFile("install"); err != nil {
		return err
	}

	if err := d.createDebianFile("changelog"); err != nil {
		return err
	}

	return nil
}

func (d *Deb) createDebianFile(name string) error {
	debianFile := filepath.Join(d.BuildFolder, "debian", name)
	file, err := os.Create(debianFile)
	if err != nil {
		return err
	}
	defer file.Close()

	return template.
		Must(template.New("controlFile").
		Parse(d.DebianTemplates[name])).
		Execute(file, d)
}

func (d *Deb) debianTemplates() map[string]string {
	t := make(map[string]string)
	t["control"] = `Source: {{.AppName}}
Section: devel
Priority: extra
Standards-Version: {{.Version}}
Maintainer: Koding Developers <hello@koding.com>
Homepage: https://koding.com

Package: {{.AppName}}
Architecture: {{.Arch}}
Description: {{.Desc}}
`

	t["rules"] = `#!/usr/bin/make -f
%:
	dh $@
`

	t["changelog"] = `{{.AppName}} ({{.Version}}) raring; urgency=low

  * Initial release.

 -- Koding Developers <hello@koding.com>  Tue, 28 Jan 2014 22:17:54 -0800
`

	t["compat"] = "9"

	t["install"] = fmt.Sprintf("%s/ /", filepath.Dir(d.InstallPrefix))

	return t
}

func debArch() string {
	arch := build.Default.GOARCH
	if arch == "386" {
		return "i386"
	}
	return arch
}
<commit_msg>go/build: add symbol name support for embedding version into binary<commit_after>package build

import (
	"errors"
	"fmt"
	"go/build"
	"koding/tools/deps"
	"koding/tools/util"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

type Deb struct {
	// App informations
	AppName     string
	Version     string
	Desc        string
	Arch        string
	SymbolName  string
	SymbolValue string

	// Build fields
	Output          string
	ImportPath      string
	InstallPrefix   string
	BuildFolder     string
	Files           string
	UpstartScript   string
	DebianTemplates map[string]string
	Debug           bool
}

// Deb is building a new .deb package with the provided tarFile It returns the
// created filename of the .deb file.
func (d *Deb) Build() (string, error) {
	defer d.cleanDebianBuild()

	d.BuildFolder = deps.DepsGoPath
	d.Arch = debArch()
	d.Desc = d.AppName + " Kite"
	d.DebianTemplates = d.debianTemplates()
	d.Output = fmt.Sprintf("%s_%s_%s.deb", d.AppName, d.Version, d.Arch)

	fmt.Println("preparing build folders")
	if err := d.createDebianDir(); err != nil {
		return "", err
	}

	fmt.Println("preparing install folders")
	if err := d.createInstallDir(); err != nil {
		return "", err
	}

	// finally build with debuild to create .deb file
	cmd := exec.Command("debuild", "-us", "-uc")
	cmd.Dir = d.BuildFolder

	if d.Debug {
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
	}

	fmt.Println("starting build process ")
	err := cmd.Start()
	if err != nil {
		return "", err
	}

	done := make(chan bool)
	go func() {
		err := cmd.Wait()
		if err != nil {
			log.Fatalln(err) // exit if something goes wrong
		}
		done <- true
	}()

	// check the result every two seconds
	ticker := time.NewTicker(2 * time.Second).C

	for {
		select {
		case <-ticker:
			fmt.Printf(".  ")
		case <-done:
			fmt.Printf("\n\n")
			return d.Output, nil
		}
	}
}

func (d *Deb) cleanDebianBuild() {
	os.RemoveAll(d.BuildFolder)

	exts := []string{"build", "changes"}
	output := fmt.Sprintf("%s_%s_%s", d.AppName, d.Version, d.Arch)
	for _, ext := range exts {
		os.Remove(output + "." + ext)
	}

	exts = []string{"dsc", "tar.gz"}
	output = fmt.Sprintf("%s_%s", d.AppName, d.Version)
	for _, ext := range exts {
		os.Remove(output + "." + ext)
	}
}

func (d *Deb) createInstallDir() error {
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		return errors.New("GOPATH is not set")
	}

	dp, err := deps.LoadDeps(deps.NewPkg(d.ImportPath, d.AppName))
	if err != nil {
		return err
	}

	if d.SymbolName != "" && d.SymbolValue != "" {
		dp.BuildSymbol = &deps.Symbol{
			SymbolName:  d.SymbolName,
			SymbolValue: d.SymbolValue,
		}
	}

	err = dp.InstallDeps()
	if err != nil {
		return err
	}

	appFolder := filepath.Join(dp.BuildGoPath, d.AppName)
	if d.Files != "" {
		files := strings.Split(d.Files, ",")
		for _, path := range files {
			err := util.Copy(path, appFolder)
			if err != nil {
				log.Println("copy assets", err)
			}
		}
	}

	if d.UpstartScript != "" {
		upstartPath := filepath.Join(d.BuildFolder, "debian/")
		upstartFile := filepath.Base(d.UpstartScript)

		err := util.Copy(d.UpstartScript, upstartPath)
		if err != nil {
			log.Println("copy assets", err)
		}

		oldFile := filepath.Join(upstartPath, upstartFile)
		newFile := filepath.Join(upstartPath, d.AppName+".upstart")

		err = os.Rename(oldFile, newFile)
		if err != nil {
			return err
		}
	}

	// move files to installprefix
	os.MkdirAll(filepath.Join(d.BuildFolder, d.InstallPrefix), 0755)
	installFolder := filepath.Join(d.BuildFolder, d.InstallPrefix, d.AppName)
	if err := os.Rename(appFolder, installFolder); err != nil {
		return err
	}

	return nil
}

func (d *Deb) createDebianDir() error {
	debianFolder := filepath.Join(d.BuildFolder, "debian")
	os.MkdirAll(debianFolder, 0755)

	if err := d.createDebianFile("control"); err != nil {
		return err
	}

	if err := d.createDebianFile("rules"); err != nil {
		return err
	}

	// make debian/rules executable
	os.Chmod(filepath.Join(debianFolder, "rules"), 0755)

	if err := d.createDebianFile("compat"); err != nil {
		return err
	}

	if err := d.createDebianFile("install"); err != nil {
		return err
	}

	if err := d.createDebianFile("changelog"); err != nil {
		return err
	}

	return nil
}

func (d *Deb) createDebianFile(name string) error {
	debianFile := filepath.Join(d.BuildFolder, "debian", name)
	file, err := os.Create(debianFile)
	if err != nil {
		return err
	}
	defer file.Close()

	return template.
		Must(template.New("controlFile").
		Parse(d.DebianTemplates[name])).
		Execute(file, d)
}

func (d *Deb) debianTemplates() map[string]string {
	t := make(map[string]string)
	t["control"] = `Source: {{.AppName}}
Section: devel
Priority: extra
Standards-Version: {{.Version}}
Maintainer: Koding Developers <hello@koding.com>
Homepage: https://koding.com

Package: {{.AppName}}
Architecture: {{.Arch}}
Description: {{.Desc}}
`

	t["rules"] = `#!/usr/bin/make -f
%:
	dh $@
`

	t["changelog"] = `{{.AppName}} ({{.Version}}) raring; urgency=low

  * Initial release.

 -- Koding Developers <hello@koding.com>  Tue, 28 Jan 2014 22:17:54 -0800
`

	t["compat"] = "9"

	t["install"] = fmt.Sprintf("%s/ /", filepath.Dir(d.InstallPrefix))

	return t
}

func debArch() string {
	arch := build.Default.GOARCH
	if arch == "386" {
		return "i386"
	}
	return arch
}
<|endoftext|>


<commit_before>// Copyright 2014 Brady Catherman
//
// 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.

// This module was written with the sole intention of making writing unit tests
// in Go use far less boiler plate checks. As such most of the boiler plate
// functionality is reduced into helpful functions that require little to no
// additional checking or setup.
//
// Use Case 1: Full Stack Traces
//
// Sometimes it is helpful to write a wrapper function to do a bunch of the
// boiler plate testing for you, however this causes the testing library
// to output a useless line number when reporting an error. As such this
// library implements a Fatal/Fatalf that will output the full stack
// trace where the error was encountered.
//
// Use Case 2: Easier Error Checking
//
// Often error checking around initialization or setup functionality can become
// extensive which means that often error returns will get ignored since
// developers don't want to keep typing up boiler plate error checking. Since
// the errors rarely ever happen the pain isn't really uncovered until later.
// This library makes testing for expected errors or success super trivial.
// See the Examples section for simple examples explaining how to do this.
//
// Use Case 3: Temporary Files are Not
//
// When writing temporary files people often assume that something will
// clean them up for them but in Go this is far from the truth. Often an
// external process cal clean them after some period but it is not rare to find
// /tmp completely full of random temporary cruft that explodes when running
// a large suite of unit tests.
//
// This library implements functionality to ensure that the temporary files
// that get created will be removed. It does this via a child process launched
// that will wait for the parent to die before removing all temporary files
// created. Using a new processes helps ensure that a panic or hard crash
// won't prevent files from being cleaned.
//
// Use Case 4: Simple Equality
//
// It can be quite tedious to validate that two objects are equal. Especially
// if they are maps of complex data types. Often this leads to dozens of
// helper functions or code explosion. The Equal() and NotEqual() functions
// are designed to eliminate this completely. Using reflection they walk
// through objects verifying that they are in fact equal, regardless of types.
// Unlike most other implementations this will also follow pointers to ensure
// that referenced data is also equal.
//
// Examples
//
// Note that the traditional Go Examples functionality is hindered since
// calls to T assume that you are starting in a unit test (and therefor
// have access to a *testing.T object). What follows are some simple pasted
// examples showing how the code can look.
//
// This example shows how easy it would be to test the ioutil.ReadFile
// function using testlib. The temporary file will be automatically cleaned at
// the end of the test. TestSuccess will automatically Fatalf if ReadFile
// returned an error, and Equal() will Fatalf if the read value does not match
// what we write.
//  func TestIoReadAll(t *testing.T) {
//      T := testlib.NewT(t)
//      defer T.Finish()
//      tempFile := T.WriteTempFile("contents")
//      contents, err := ioutil.ReadFile(tempFile)
//      T.ExpectSuccess(err)
//      T.Equal(contents, []byte("contents"))
//  }
package testlib
<commit_msg>Fix the section titles in doc.go<commit_after>// Copyright 2014 Brady Catherman
//
// 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.

// This module was written with the sole intention of making writing unit tests
// in Go use far less boiler plate checks. As such most of the boiler plate
// functionality is reduced into helpful functions that require little to no
// additional checking or setup.
//
// Full Stack Traces
//
// Sometimes it is helpful to write a wrapper function to do a bunch of the
// boiler plate testing for you, however this causes the testing library
// to output a useless line number when reporting an error. As such this
// library implements a Fatal/Fatalf that will output the full stack
// trace where the error was encountered.
//
// Easier Error Checking
//
// Often error checking around initialization or setup functionality can become
// extensive which means that often error returns will get ignored since
// developers don't want to keep typing up boiler plate error checking. Since
// the errors rarely ever happen the pain isn't really uncovered until later.
// This library makes testing for expected errors or success super trivial.
// See the Examples section for simple examples explaining how to do this.
//
// Temporary Files are Not
//
// When writing temporary files people often assume that something will
// clean them up for them but in Go this is far from the truth. Often an
// external process cal clean them after some period but it is not rare to find
// /tmp completely full of random temporary cruft that explodes when running
// a large suite of unit tests.
//
// This library implements functionality to ensure that the temporary files
// that get created will be removed. It does this via a child process launched
// that will wait for the parent to die before removing all temporary files
// created. Using a new processes helps ensure that a panic or hard crash
// won't prevent files from being cleaned.
//
// Simple Equality
//
// It can be quite tedious to validate that two objects are equal. Especially
// if they are maps of complex data types. Often this leads to dozens of
// helper functions or code explosion. The Equal() and NotEqual() functions
// are designed to eliminate this completely. Using reflection they walk
// through objects verifying that they are in fact equal, regardless of types.
// Unlike most other implementations this will also follow pointers to ensure
// that referenced data is also equal.
//
// Examples
//
// Note that the traditional Go Examples functionality is hindered since
// calls to T assume that you are starting in a unit test (and therefor
// have access to a *testing.T object). What follows are some simple pasted
// examples showing how the code can look.
//
// This example shows how easy it would be to test the ioutil.ReadFile
// function using testlib. The temporary file will be automatically cleaned at
// the end of the test. TestSuccess will automatically Fatalf if ReadFile
// returned an error, and Equal() will Fatalf if the read value does not match
// what we write.
//  func TestIoReadAll(t *testing.T) {
//      T := testlib.NewT(t)
//      defer T.Finish()
//      tempFile := T.WriteTempFile("contents")
//      contents, err := ioutil.ReadFile(tempFile)
//      T.ExpectSuccess(err)
//      T.Equal(contents, []byte("contents"))
//  }
package testlib
<|endoftext|>


<commit_before>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// Package yarpc provides the YARPC service framework.
package yarpc

// TODO: Add more package-level docs
<commit_msg>Write top godoc (#672)<commit_after>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// Package yarpc provides the YARPC service framework.
//
// With hundreds to thousands of services communicating with RPC, transport
// protocols (like HTTP and TChannel), encoding protocols (like JSON or
// Thrift), and peer choosers are the concepts that vary year over year.
// Separating these concerns allows services to change transports and wire
// protocols without changing call sites or request handlers, build proxies and
// wire protocol bridges, or experiment with load balancing strategies.
// YARPC is a toolkit for services and proxies.
//
// YARPC breaks RPC into interchangeable encodings, transports, and peer
// choosers.
// YARPC for Go provides reference implementations for HTTP/1.1 and TChannel
// transports, and also raw, JSON, and Thrift encodings.
// YARPC for Go provides experimental implementations for a Redis transport and a
// round robin peer chooser.
// YARPC for Go plans to provide a Protobuf 3 encoding, a gRPC transport, and a
// load balancer that uses a least-pending-requests strategy.
// Peer choosers can implement any strategy, including load balancing or sharding,
// in turn backed by a pluggable peer provider.
//
// Regardless of transport, every RPC has some common properties: caller name,
// service name, procedure name, encoding name, deadline or TTL, headers,
// baggage (multi-hop headers), and tracing.
// Each RPC can also have an optional shard key, routing key, or routing
// delegate for advanced routing.
// YARPC transports use a shared API for capturing RPC metadata, so middleware
// can apply to requests over any transport.
//
// Each YARPC transport protocol can implement inbound handlers and outbound
// callers. Each of these can support different RPC types, like unary (request and
// response) or oneway (request and receipt) RPC. A future release of YARPC will
// add support for other RPC types including variations on streaming and pubsub.
package yarpc
<|endoftext|>


<commit_before>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * doc.go                                                 *
 *                                                        *
 * hprose doc for Go.                                     *
 *                                                        *
 * LastModified: Aug 24, 2016                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*
Package hprose is a High Performance Remote Object Service Engine.

It is a modern, lightweight, cross-language, cross-platform, object-oriented, high performance, remote dynamic communication middleware. It is not only easy to use, but powerful. You just need a little time to learn, then you can use it to easily construct cross language cross platform distributed application system.

Hprose supports many programming languages, for example:

        * AAuto Quicker
        * ActionScript
        * ASP
        * C++
        * Dart
        * Delphi/Free Pascal
        * dotNET(C#, Visual Basic...)
        * Golang
        * Java
        * JavaScript
        * Node.js
        * Objective-C
        * Perl
        * PHP
        * Python
        * Ruby
        * ...

Through Hprose, You can conveniently and efficiently intercommunicate between those programming languages.

This project is the implementation of Hprose for Golang.
*/
package hprose
<commit_msg>Update doc.go<commit_after>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/
/**********************************************************\
 *                                                        *
 * doc.go                                                 *
 *                                                        *
 * hprose doc for Go.                                     *
 *                                                        *
 * LastModified: Aug 24, 2016                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*
Package hprose is a High Performance Remote Object Service Engine.

It is a modern, lightweight, cross-language, cross-platform, object-oriented, high performance, remote dynamic communication middleware. It is not only easy to use, but powerful. You just need a little time to learn, then you can use it to easily construct cross language cross platform distributed application system.

Hprose supports many programming languages, for example:

        * AAuto Quicker
        * ActionScript
        * ASP
        * C++
        * Dart
        * Delphi/Free Pascal
        * dotNET(C#, Visual Basic...)
        * Golang
        * Java
        * JavaScript
        * Node.js
        * Objective-C
        * Perl
        * PHP
        * Python
        * Ruby
        * ...

Through Hprose, You can conveniently and efficiently intercommunicate between those programming languages.

This project is the implementation of Hprose for Golang.
*/
package hprose
<|endoftext|>


<commit_before>// sshutil contains helpers for ssh

package sshutil
<commit_msg>Reformat package comment<commit_after>// Package sshutil contains helpers for ssh.
package sshutil
<|endoftext|>


<commit_before>// Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

/*
Package btcwire implements the bitcoin wire protocol.

For the complete details of the bitcoin protocol, see the official wiki entry
at https://en.bitcoin.it/wiki/Protocol_specification.  The following only serves
as a quick overview to provide information on how to use the package.

At a high level, this package provides support for marshalling and unmarshalling
supported bitcoin messages to and from the wire.  This package does not deal
with the specifics of message handling such as what to do when a message is
received.  This provides the caller with a high level of flexibility.

Bitcoin Message Overview

The bitcoin protocol consists of exchanging messages between peers.  Each
message is preceded by a header which identifies information about it such as
which bitcoin network it is a part of, its type, how big it is, and a checksum
to verify validity.  All encoding and decoding of message headers is handled by
this package.

To accomplish this, there is a generic interface for bitcoin messages named
Message which allows messages of any type to be read, written, or passed around
through channels, functions, etc.  In addition, concrete implementations of most
of the currently supported bitcoin messages are provided.  For these supported
messages, all of the details of marshalling and unmarshalling to and from the
wire using bitcoin encoding are handled so the caller doesn't have to concern
themselves with the specifics.

Message Interaction

The following provides a quick summary of how the bitcoin messages are intended
to interact with one another.  As stated above, these interactions are not
directly handled by this package.  For more in-depth details about the
appropriate interactions, see the official bitcoin protocol wiki entry at
https://en.bitcoin.it/wiki/Protocol_specification.

The initial handshake consists of two peers sending each other a version message
(MsgVersion) followed by responding with a verack message (MsgVerAck).  Both
peers use the information in the version message (MsgVersion) to negotiate
things such as protocol version and supported services with each other.  Once
the initial handshake is complete, the following chart indicates message
interactions in no particular order.

	Peer A Sends                          Peer B Responds
	----------------------------------------------------------------------------
	getaddr message (MsgGetAddr)          addr message (MsgAddr)
	getblocks message (MsgGetBlocks)      inv message (MsgInv)
	inv message (MsgInv)                  getdata message (MsgGetData)
	getdata message (MsgGetData)          block message (MsgBlock) -or-
	                                      tx message (MsgTx) -or-
	                                      notfound message (MsgNotFound)
	getheaders message (MsgGetHeaders)    headers message (MsgHeaders)
	ping message (MsgPing)                pong message (MsgHeaders)* -or-
	                                      (none -- Ability to send message is enough)

	NOTES:
	* The pong message was not added until later protocol versions as defined
	  in BIP0031.  The BIP0031Version constant can be used to detect a recent
	  enough protocol version for this purpose (version > BIP0031Version).

Common Parameters

There are several common parameters that arise when using this package to read
and write bitcoin messages.  The following sections provide a quick overview of
these parameters so the next sections can build on them.

Protocol Version

The protocol version should be negotiated with the remote peer at a higher
level than this package via the version (MsgVersion) message exchange, however,
this package provides the btcwire.ProtocolVersion constant which indicates the
latest protocol version this package supports and is typically the value to use
for all outbound connections before a potentially lower protocol version is
negotiated.

Bitcoin Network

The bitcoin network is a magic number which is used to identify the start of a
message and which bitcoin network the message applies to.  This package provides
the following constants:

	btcwire.MainNet
	btcwire.TestNet  (Regression test network)
	btcwire.TestNet3 (Test network version 3)

Determining Message Type

As discussed in the bitcoin message overview section, this package reads
and writes bitcoin messages using a generic interface named Message.  In
order to determine the actual concrete type of the message, use a type
switch or type assertion.  An example of a type switch follows:

	// Assumes msg is already a valid concrete message such as one created
	// via NewMsgVersion or read via ReadMessage.
	switch msg.(type) {
	case *btcwire.MsgVersion:
		// The message is a pointer to a MsgVersion struct.
		fmt.Printf("Protocol version: %v", msg.ProtocolVersion)
	case *btcwire.MsgBlock:
		// The message is a pointer to a MsgBlock struct.
		fmt.Printf("Number of tx in block: %v", msg.Header.TxnCount)
	}

Reading Messages

In order to unmarshall bitcoin messages from the wire, use the ReadMessage
function.  It accepts any io.Reader, but typically this will be a net.Conn to
a remote node running a bitcoin peer.  Example syntax is:

	// Reads and validates the next bitcoin message from conn using the
	// protocol version pver and the bitcoin network btcnet.  The returns
	// are a btcwire.Message, a []byte which contains the unmarshalled
	// raw payload, and a possible error.
	msg, rawPayload, err := btcwire.ReadMessage(conn, pver, btcnet)
	if err != nil {
		// Log and handle the error
	}

Writing Messages

In order to marshall bitcoin messages to the wire, use the WriteMessage
function.  It accepts any io.Writer, but typically this will be a net.Conn to
a remote node running a bitcoin peer.  Example syntax to request addresses
from a remote peer is:

	// Create a new getaddr bitcoin message.
	msg := btcwire.NewMsgGetAddr()

	// Writes a bitcoin message msg to conn using the protocol version
	// pver, and the bitcoin network btcnet.  The return is a possible
	// error.
	err := btcwire.WriteMessage(conn, msg, pver, btcnet)
	if err != nil {
		// Log and handle the error
	}

Errors

Errors returned by this package are either the raw errors provided by underlying
calls to read/write from streams such as io.EOF, io.ErrUnexpectedEOF, and
io.ErrShortWrite, or of type btcwire.MessageError.  This allows the caller to
differentiate between general IO errors and malformed messages through type
assertions.

Bitcoin Improvement Proposals

This package includes spec changes outlined by the following BIPs:

		BIP0031 (https://en.bitcoin.it/wiki/BIP_0031)
		BIP0035 (https://en.bitcoin.it/wiki/BIP_0035)

Other important information

The package does not yet implement BIP0037 (https://en.bitcoin.it/wiki/BIP_0037)
and therefore does not recognize filterload, filteradd, filterclear, or
merkleblock messages.
*/
package btcwire
<commit_msg>Fix doc example typo<commit_after>// Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

/*
Package btcwire implements the bitcoin wire protocol.

For the complete details of the bitcoin protocol, see the official wiki entry
at https://en.bitcoin.it/wiki/Protocol_specification.  The following only serves
as a quick overview to provide information on how to use the package.

At a high level, this package provides support for marshalling and unmarshalling
supported bitcoin messages to and from the wire.  This package does not deal
with the specifics of message handling such as what to do when a message is
received.  This provides the caller with a high level of flexibility.

Bitcoin Message Overview

The bitcoin protocol consists of exchanging messages between peers.  Each
message is preceded by a header which identifies information about it such as
which bitcoin network it is a part of, its type, how big it is, and a checksum
to verify validity.  All encoding and decoding of message headers is handled by
this package.

To accomplish this, there is a generic interface for bitcoin messages named
Message which allows messages of any type to be read, written, or passed around
through channels, functions, etc.  In addition, concrete implementations of most
of the currently supported bitcoin messages are provided.  For these supported
messages, all of the details of marshalling and unmarshalling to and from the
wire using bitcoin encoding are handled so the caller doesn't have to concern
themselves with the specifics.

Message Interaction

The following provides a quick summary of how the bitcoin messages are intended
to interact with one another.  As stated above, these interactions are not
directly handled by this package.  For more in-depth details about the
appropriate interactions, see the official bitcoin protocol wiki entry at
https://en.bitcoin.it/wiki/Protocol_specification.

The initial handshake consists of two peers sending each other a version message
(MsgVersion) followed by responding with a verack message (MsgVerAck).  Both
peers use the information in the version message (MsgVersion) to negotiate
things such as protocol version and supported services with each other.  Once
the initial handshake is complete, the following chart indicates message
interactions in no particular order.

	Peer A Sends                          Peer B Responds
	----------------------------------------------------------------------------
	getaddr message (MsgGetAddr)          addr message (MsgAddr)
	getblocks message (MsgGetBlocks)      inv message (MsgInv)
	inv message (MsgInv)                  getdata message (MsgGetData)
	getdata message (MsgGetData)          block message (MsgBlock) -or-
	                                      tx message (MsgTx) -or-
	                                      notfound message (MsgNotFound)
	getheaders message (MsgGetHeaders)    headers message (MsgHeaders)
	ping message (MsgPing)                pong message (MsgHeaders)* -or-
	                                      (none -- Ability to send message is enough)

	NOTES:
	* The pong message was not added until later protocol versions as defined
	  in BIP0031.  The BIP0031Version constant can be used to detect a recent
	  enough protocol version for this purpose (version > BIP0031Version).

Common Parameters

There are several common parameters that arise when using this package to read
and write bitcoin messages.  The following sections provide a quick overview of
these parameters so the next sections can build on them.

Protocol Version

The protocol version should be negotiated with the remote peer at a higher
level than this package via the version (MsgVersion) message exchange, however,
this package provides the btcwire.ProtocolVersion constant which indicates the
latest protocol version this package supports and is typically the value to use
for all outbound connections before a potentially lower protocol version is
negotiated.

Bitcoin Network

The bitcoin network is a magic number which is used to identify the start of a
message and which bitcoin network the message applies to.  This package provides
the following constants:

	btcwire.MainNet
	btcwire.TestNet  (Regression test network)
	btcwire.TestNet3 (Test network version 3)

Determining Message Type

As discussed in the bitcoin message overview section, this package reads
and writes bitcoin messages using a generic interface named Message.  In
order to determine the actual concrete type of the message, use a type
switch or type assertion.  An example of a type switch follows:

	// Assumes msg is already a valid concrete message such as one created
	// via NewMsgVersion or read via ReadMessage.
	switch msg := msg.(type) {
	case *btcwire.MsgVersion:
		// The message is a pointer to a MsgVersion struct.
		fmt.Printf("Protocol version: %v", msg.ProtocolVersion)
	case *btcwire.MsgBlock:
		// The message is a pointer to a MsgBlock struct.
		fmt.Printf("Number of tx in block: %v", msg.Header.TxnCount)
	}

Reading Messages

In order to unmarshall bitcoin messages from the wire, use the ReadMessage
function.  It accepts any io.Reader, but typically this will be a net.Conn to
a remote node running a bitcoin peer.  Example syntax is:

	// Reads and validates the next bitcoin message from conn using the
	// protocol version pver and the bitcoin network btcnet.  The returns
	// are a btcwire.Message, a []byte which contains the unmarshalled
	// raw payload, and a possible error.
	msg, rawPayload, err := btcwire.ReadMessage(conn, pver, btcnet)
	if err != nil {
		// Log and handle the error
	}

Writing Messages

In order to marshall bitcoin messages to the wire, use the WriteMessage
function.  It accepts any io.Writer, but typically this will be a net.Conn to
a remote node running a bitcoin peer.  Example syntax to request addresses
from a remote peer is:

	// Create a new getaddr bitcoin message.
	msg := btcwire.NewMsgGetAddr()

	// Writes a bitcoin message msg to conn using the protocol version
	// pver, and the bitcoin network btcnet.  The return is a possible
	// error.
	err := btcwire.WriteMessage(conn, msg, pver, btcnet)
	if err != nil {
		// Log and handle the error
	}

Errors

Errors returned by this package are either the raw errors provided by underlying
calls to read/write from streams such as io.EOF, io.ErrUnexpectedEOF, and
io.ErrShortWrite, or of type btcwire.MessageError.  This allows the caller to
differentiate between general IO errors and malformed messages through type
assertions.

Bitcoin Improvement Proposals

This package includes spec changes outlined by the following BIPs:

		BIP0031 (https://en.bitcoin.it/wiki/BIP_0031)
		BIP0035 (https://en.bitcoin.it/wiki/BIP_0035)

Other important information

The package does not yet implement BIP0037 (https://en.bitcoin.it/wiki/BIP_0037)
and therefore does not recognize filterload, filteradd, filterclear, or
merkleblock messages.
*/
package btcwire
<|endoftext|>


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

/*
Package cloud is the root of the packages used to access Google Cloud
Services. See https://godoc.org/cloud.google.com/go for a full list
of sub-packages.

Client Options

All clients in sub-packages are configurable via client options. These options are
described here: https://godoc.org/google.golang.org/api/option.

Authentication and Authorization

All the clients in sub-packages support authentication via Google Application Default
Credentials (see https://cloud.google.com/docs/authentication/production), or
by providing a JSON key file for a Service Account. See the authentication examples
in this package for details.

Timeouts and Cancellation

By default, non-streaming methods, like Create or Get, will have a default deadline applied to the
context provided at call time, unless a context deadline is already set. Streaming
methods have no default deadline and will run indefinitely. To set timeouts or
arrange for cancellation, use contexts. See the examples for details. Transient
errors will be retried when correctness allows.

To opt out of default deadlines, set the temporary environment variable
GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE to "true" prior to client
creation. This affects all Google Cloud Go client libraries. This opt-out
mechanism will be removed in a future release. File an issue at
https://github.com/googleapis/google-cloud-go if the default deadlines
cannot work for you.

Do not attempt to control the initial connection (dialing) of a service by setting a
timeout on the context passed to NewClient. Dialing is non-blocking, so timeouts
would be ineffective and would only interfere with credential refreshing, which uses
the same context.

Connection Pooling

Connection pooling differs in clients based on their transport. Cloud
clients either rely on HTTP or gRPC transports to communicate
with Google Cloud.

Cloud clients that use HTTP (bigquery, compute, storage, and translate) rely on the
underlying HTTP transport to cache connections for later re-use. These are cached to
the default http.MaxIdleConns and http.MaxIdleConnsPerHost settings in
http.DefaultTransport.

For gRPC clients (all others in this repo), connection pooling is configurable. Users
of cloud client libraries may specify option.WithGRPCConnectionPool(n) as a client
option to NewClient calls. This configures the underlying gRPC connections to be
pooled and addressed in a round robin fashion.

Using the Libraries with Docker

Minimal docker images like Alpine lack CA certificates. This causes RPCs to appear to
hang, because gRPC retries indefinitely. See https://github.com/googleapis/google-cloud-go/issues/928
for more information.

Debugging

To see gRPC logs, set the environment variable GRPC_GO_LOG_SEVERITY_LEVEL. See
https://godoc.org/google.golang.org/grpc/grpclog for more information.

For HTTP logging, set the GODEBUG environment variable to "http2debug=1" or "http2debug=2".

Client Stability

Clients in this repository are considered alpha or beta unless otherwise
marked as stable in the README.md. Semver is not used to communicate stability
of clients.

Alpha and beta clients may change or go away without notice.

Clients marked stable will maintain compatibility with future versions for as
long as we can reasonably sustain. Incompatible changes might be made in some
situations, including:

- Security bugs may prompt backwards-incompatible changes.

- Situations in which components are no longer feasible to maintain without
making breaking changes, including removal.

- Parts of the client surface may be outright unstable and subject to change.
These parts of the surface will be labeled with the note, "It is EXPERIMENTAL
and subject to change or removal without notice."
*/
package cloud // import "cloud.google.com/go"
<commit_msg>docs(all): add details on how to cast errors to grpc.Status (#3703)<commit_after>// Copyright 2014 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
Package cloud is the root of the packages used to access Google Cloud
Services. See https://godoc.org/cloud.google.com/go for a full list
of sub-packages.

Client Options

All clients in sub-packages are configurable via client options. These options are
described here: https://godoc.org/google.golang.org/api/option.

Authentication and Authorization

All the clients in sub-packages support authentication via Google Application Default
Credentials (see https://cloud.google.com/docs/authentication/production), or
by providing a JSON key file for a Service Account. See the authentication examples
in this package for details.

Timeouts and Cancellation

By default, non-streaming methods, like Create or Get, will have a default deadline applied to the
context provided at call time, unless a context deadline is already set. Streaming
methods have no default deadline and will run indefinitely. To set timeouts or
arrange for cancellation, use contexts. See the examples for details. Transient
errors will be retried when correctness allows.

To opt out of default deadlines, set the temporary environment variable
GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE to "true" prior to client
creation. This affects all Google Cloud Go client libraries. This opt-out
mechanism will be removed in a future release. File an issue at
https://github.com/googleapis/google-cloud-go if the default deadlines
cannot work for you.

Do not attempt to control the initial connection (dialing) of a service by setting a
timeout on the context passed to NewClient. Dialing is non-blocking, so timeouts
would be ineffective and would only interfere with credential refreshing, which uses
the same context.

Connection Pooling

Connection pooling differs in clients based on their transport. Cloud
clients either rely on HTTP or gRPC transports to communicate
with Google Cloud.

Cloud clients that use HTTP (bigquery, compute, storage, and translate) rely on the
underlying HTTP transport to cache connections for later re-use. These are cached to
the default http.MaxIdleConns and http.MaxIdleConnsPerHost settings in
http.DefaultTransport.

For gRPC clients (all others in this repo), connection pooling is configurable. Users
of cloud client libraries may specify option.WithGRPCConnectionPool(n) as a client
option to NewClient calls. This configures the underlying gRPC connections to be
pooled and addressed in a round robin fashion.

Using the Libraries with Docker

Minimal docker images like Alpine lack CA certificates. This causes RPCs to appear to
hang, because gRPC retries indefinitely. See https://github.com/googleapis/google-cloud-go/issues/928
for more information.

Debugging

To see gRPC logs, set the environment variable GRPC_GO_LOG_SEVERITY_LEVEL. See
https://godoc.org/google.golang.org/grpc/grpclog for more information.

For HTTP logging, set the GODEBUG environment variable to "http2debug=1" or "http2debug=2".

Inspecting errors

Most of the errors returned by the generated clients can be converted into a
`grpc.Status`. Converting your errors to this type can be a useful to get
more information about what went wrong while debugging.
 if err != {
    if s, ok := status.FromError(err); ok {
	   log.Println(s.Message())
	   for _, d := range s.Proto().Details {
	      log.Println(d)
	   }
	}
 }

Client Stability

Clients in this repository are considered alpha or beta unless otherwise
marked as stable in the README.md. Semver is not used to communicate stability
of clients.

Alpha and beta clients may change or go away without notice.

Clients marked stable will maintain compatibility with future versions for as
long as we can reasonably sustain. Incompatible changes might be made in some
situations, including:

- Security bugs may prompt backwards-incompatible changes.

- Situations in which components are no longer feasible to maintain without
making breaking changes, including removal.

- Parts of the client surface may be outright unstable and subject to change.
These parts of the surface will be labeled with the note, "It is EXPERIMENTAL
and subject to change or removal without notice."
*/
package cloud // import "cloud.google.com/go"
<|endoftext|>


<commit_before>// Copyright (c) 2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

// Package btcrpcclient implements a websocket-enabled Bitcoin JSON-RPC client.
//
// TODO(davec): Doco
package btcrpcclient
<commit_msg>Initial package overview documentation.<commit_after>// Copyright (c) 2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

/*
Package btcrpcclient implements a websocket-enabled Bitcoin JSON-RPC client.

Overview

This client is intended to provide a robust and easy to use client for
interfacing with a Bitcoin RPC server that uses a btcd/bitcoin core compatible
Bitcoin JSON-RPC API.  This client has been tested with
btcd (https://github.com/conformal/btcd),
btcwallet (https://github.com/conformal/btcwallet), and
bitcoin core (https://github.com/bitcoin).

In addition to the compatible standard HTTP POST JSON-RPC API, btcd and
btcwallet provide a websocket interface that is more efficient than the standard
HTTP POST method of accessing RPC.  The section below discusses the differences
between HTTP POST and websockets.

By default, this client assumes the RPC server supports websockets and has
TLS enabled.  In practice, this currently means it assumes you are talking to
btcd or btcwallet by default.  However, configuration options are provided to
fall back to HTTP POST and disable TLS to support talking with inferior bitcoin
core style RPC servers.

Websockets vs HTTP POST

In HTTP POST-based JSON-RPC, every request creates a new HTTP connection,
issues the call, waits for the response, and closes the connection.  This adds
quite a bit of overhead to every call and lacks flexibility for features such as
notifications.

In contrast, the websocket-based JSON-RPC interface provided by btcd and
btcwallet only uses a single connection that remains open and allows
asynchronous bi-directional communication.

The websocket interface supports all of the same commands as HTTP POST, but they
can be invoked without having to go through a connect/disconnect cycle for every
call.  In addition, the websocket interface provides other nice features such as
the ability to register for asynchronous notifications of various events.

Synchronous vs Asynchronous API

The client provides both a synchronous (blocking) and asynchronous API.

The synchronous (blocking) API is typically sufficient for most use cases.  It
works by issuing the RPC and blocking until the response is received.  This
allows  straightforward code where you have the response as soon as the function
returns.

The asynchronous API works on the concept of futures.  When you invoke the async
version of a command, it will quickly return an instance of a type that promises
to provide the result of the RPC at some future time.  In the background, the
RPC call is issued and the result is stored in the returned instance.  Invoking
the Receive method on the returned instance will either return the result
immediately if it has already arrived, or block until it has.  This is useful
since it provides the caller with greater control over concurrency.

Notifications

The first important part of notifications is to realize that they will only
work when connected via websockets.  This should intuitively make sense
because HTTP POST mode does not keep a connection open!

All notifications provided by btcd require registration to opt-in.  For example,
if you want to be notified when funds are received by a set of addresses, you
register the addresses via the NotifyReceived (or NotifyReceivedAsync) function.

Notification Handlers

Notifications are exposed by the client through the use of callback handlers
which are setup via a NotificationHandlers instance that is specified by the
caller when creating the client.

It is important that these notification handlers complete quickly since they
are intentionally in the main read loop and will block further reads until
they complete.  This provides the caller with the flexibility to decide what to
do when notifications are coming in faster than they are being handled.

In particular this means issuing a blocking RPC call from a callback handler
will cause a deadlock as more server responses won't be read until the callback
returns, but the callback would be waiting for a response.   Thus, any
additional RPCs must be issued an a completely decoupled manner.

Automatic Reconnection

By default, when running in websockets mode, this client will automatically
keep trying to reconnect to the RPC server should the connection be lost.  There
is a back-off in between each connection attempt until it reaches one try per
minute.  Once a connection is re-established, all previously registered
notifications are automatically re-registered and any in-flight commands are
re-issued.  This means from the caller's perspective, the request simply takes
longer to complete.

The caller may invoke the Shutdown method on the client to force the client
to cease reconnect attempts and return ErrClientShutdown for all outstanding
commands.

The automatic reconnection can be disabled by setting the DisableAutoReconnect
flag to true in the connection config when creating the client.

Minor RPC Server Differences and Chain/Wallet Separation

Some of the commands are extensions specific to a particular RPC server.  For
example, the DebugLevel call is an extension only provided by btcd (and
btcwallet passthrough).  Therefore if you call one of these commands against
an RPC server that doesn't provide them, you will get an unimplemented error
from the server.  An effort has been made to call out which commmands are
extensions in their documentation.

Also, it is important to realize that btcd intentionally separates the wallet
functionality into a separate process named btcwallet.  This means if you are
connected to the btcd RPC server directly, only the RPCs which are related to
chain services will be available.  Depending on your application, you might only
need chain-related RPCs.  In contrast, btcwallet provides pass through treatment
for chain-related RPCs, so it supports them in addition to wallet-related RPCs.

Errors

There are 3 categories of errors that will be returned throughout this package:

  - Errors related to the client connection such as authentication, endpoint,
    disconnect, and shutdown
  - Errors that occur before communicating with the remote RPC server such as
    command creation and marshaling errors or issues talking to the remote
    server
  - Errors returned from the remote RPC server like unimplemented commands,
    nonexistent requested blocks and transactions, malformed data, and incorrect
    networks

The first category of errors are typically one of ErrInvalidAuth,
ErrInvalidEndpoint, ErrClientDisconnect, or ErrClientShutdown.

NOTE: The ErrClientDisconnect will not be returned unless the
DisableAutoReconnect flag is set since the client automatically handles
reconnect by default as previously described.

The second category of errors typically indicates a programmer error and as such
the type can vary, but usually will be best handled by simply showing/logging
it.

The third category of errors, that is errors returned by the server, can be
detected by type asserting the error is a *btcjson.Error.  For example, to
detect if a command is unimplemented by the remote RPC server:

  amount, err := client.GetBalance("")
  if err != nil {
  	if jerr, ok := err.(*btcjson.Error); ok {
  		switch jerr.Code {
		case btcjson.ErrUnimplemented.Code:
  			// Handle not implemented error

  		// Handle other specific errors you care about
		}
  	}

  	// Log or otherwise handle the error knowing it was not one returned
  	// from the remote RPC server.
  }

Example Usage

The following full-blown client examples are in the examples directory:

 - bitcoincorehttp
   Connects to a bitcoin core RPC server using HTTP POST mode with TLS disabled
   and gets the current block count
 - btcdwebsockets
   Connects to a btcd RPC server using TLS-secured websockets, registers for
   block connected and block disconnected notifications, and gets the current
   block count
*/
package btcrpcclient
<|endoftext|>


<commit_before>// Package store4 provides a fast in-memory string-based quad store
// (graphs of triples).
//
// Simple
//
// Package store4 does not feature any specific support
// for RDF — its API is purely string-based, bare-boned and minimal.
//
//  // Add some quads to a store.
//  s := store4.NewQuadStore()
//  s.Add("s", "p", "o", "g")
//  s.Add("Alice", "knows", "Bob", "")
//  s.Add("Alice", "knows", "Charlie", "")
//  s.Add("Charlie", "knows", "Bob", "")
//  s.Add("Bob", "isa", "Cat", "")
//  s.Add("play", "with", "strings!", "₍˄·͈༝·͈˄₎◞ ̑̑ෆ⃛")
//  s.Add("_:bn", "<urn:foo:bar>", `"baz"`, "<qux>")
//
//  // Find everyone that Alice knows, in any graph.
//  list := s.FindObjects("Alice", "knows", "*")
//  fmt.Println(list)
//  // Output (exact order may vary):
//  // [Bob Charlie]
//
//  // Find everyone who knows Charlie, in the 'unnamed' graph.
//  x := s.FindSubjects("knows", "Charlie", "")
//  fmt.Println(x)
//  // Output:
//  // [Alice]
//
//  // Remove all statements about Charlie, from all graphs.
//  s.Remove("Charlie", "*", "Charlie", "*")
//
// Callbacks make it easy to work with and query the contents of the
// store without allocating lists for results.
//
//  // Iterate over all quads.
//  s.ForEach(func(s, p, o, g string) {
//      // ...
//  })
//
//  // Iterate over quads matching given pattern.
//  s.ForEachWith("*", "*", "Bob", "*", func(s, p, o, g string) {
//      fmt.Println(s, p, o, g)
//  })
//  // Output (exact order may vary):
//  // Alice knows Bob
//  // Charlie knows Bob
//
// For cancellable iterators see Some and Every, and
// their filtering counterparts SomeWith and EveryWith.
//
// Internals
//
// Each graph is indexed by SPO, POS and OSP.
// Each index is composed of three layers of native Go maps.
//
// Additionally, the store only holds a single reference to each
// string term it has seen.
//
// Concurrency
//
// Package store4 is not concurrency safe (while being modified).
//
// Dependencies
//
// No external dependencies.
//
// License
//
// Package store4 is free software / open source software, released
// under the MIT License.
//
// Additional credits
//
// The internals of store4 draw heavily from the implementation
// of N3Store, a component of N3.js. The N3.js library is
// copyrighted by Ruben Verborgh and released under the MIT License.
// https://github.com/RubenVerborgh/N3.js
package store4
<commit_msg>Minor doc cleanup<commit_after>// Package store4 provides a fast in-memory string-based quad store
// (graphs of triples).
//
// Simple
//
// Package store4 does not feature any specific support
// for RDF — its API is purely string-based, bare-boned and minimal.
//
//  // Add some quads to a store.
//  s := store4.NewQuadStore()
//  s.Add("s", "p", "o", "g")
//  s.Add("Alice", "knows", "Bob", "")
//  s.Add("Alice", "knows", "Charlie", "")
//  s.Add("Charlie", "knows", "Bob", "")
//  s.Add("Bob", "isa", "Cat", "")
//  s.Add("play", "with", "strings!", "₍˄·͈༝·͈˄₎◞ ̑̑ෆ⃛")
//  s.Add("_:bn", "<urn:foo:bar>", `"baz"`, "<qux>")
//
//  // Find everyone that Alice knows, in any graph.
//  list := s.FindObjects("Alice", "knows", "*")
//  fmt.Println(list)
//  // Output (exact order may vary):
//  // [Bob Charlie]
//
//  // Find everyone who knows Charlie, in the 'unnamed' graph.
//  x := s.FindSubjects("knows", "Charlie", "")
//  fmt.Println(x)
//  // Output:
//  // [Alice]
//
//  // Remove all statements about Charlie, from all graphs.
//  s.Remove("Charlie", "*", "Charlie", "*")
//
// Callbacks make it easy to work with and query the contents of the
// store without allocating lists for results.
//
//  // Iterate over all quads.
//  s.ForEach(func(s, p, o, g string) {
//      // ...
//  })
//
//  // Iterate over quads matching given pattern.
//  s.ForEachWith("*", "*", "Bob", "*", func(s, p, o, g string) {
//      fmt.Println(s, p, o, g)
//  })
//  // Output (exact order may vary):
//  // Alice knows Bob
//  // Charlie knows Bob
//
// For cancellable iterators see Some and Every, and
// their filtering counterparts SomeWith and EveryWith.
//
// Internals
//
// Each graph is indexed by SPO, POS and OSP.
// Each index is composed of three layers of native Go maps.
//
// Additionally, the store only holds a single reference to each
// string term it has seen.
//
// Concurrency
//
// Package store4 is not concurrency safe while being modified.
//
// Dependencies
//
// Standard library.
//
// Ginkgo and Gomega to run tests.
//
// License
//
// Package store4 is free software / open source software, released
// under the MIT License.
//
// Additional credits
//
// The internals of QuadStore draw heavily from the implementation
// of N3Store, a component of N3.js.
//
// The N3.js library is
// copyrighted by Ruben Verborgh and released under the MIT License.
// https://github.com/RubenVerborgh/N3.js
package store4
<|endoftext|>


<commit_before>// CheeseGull is a webserver that functions as a cache middleman between the
// official osu! mirrors and requesters of beatmaps, as well as also a cache
// middleman for beatmaps metadata retrieved from the official osu! API.
package main

// Version is the version of cheesegull.
const Version = "v2.0.4"
<commit_msg>⬆ v2.1.0 ⬆<commit_after>// CheeseGull is a webserver that functions as a cache middleman between the
// official osu! mirrors and requesters of beatmaps, as well as also a cache
// middleman for beatmaps metadata retrieved from the official osu! API.
package main

// Version is the version of cheesegull.
const Version = "v2.1.0"
<|endoftext|>


<commit_before>package main

import (
	"go/parser"
	"go/token"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

var cmdFix = &Command{
	UsageLine: "fix",
	Short:     "fix the beego application to compatibel with beego 1.6",
	Long: `
As from beego1.6, there's some incompatible code with the old version.

bee fix help to upgrade the application to beego 1.6
`,
}

func init() {
	cmdFix.Run = runFix
}

func runFix(cmd *Command, args []string) int {
	dir, err := os.Getwd()
	if err != nil {
		ColorLog("GetCurrent Path:%s\n", err)
	}
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			if strings.HasPrefix(info.Name(), ".") {
				return filepath.SkipDir
			}
			return nil
		}
		if err != nil {
			return err
		}
		if strings.HasSuffix(info.Name(), ".exe") {
			return nil
		}
		ColorLog("%s\n", path)
		err = fixFile(path)
		if err != nil {
			ColorLog("fixFile:%s\n", err)
		}
		return err
	})
	return 0
}

var rules = []string{
	"beego.AppName", "beego.BConfig.AppName",
	"beego.RunMode", "beego.BConfig.RunMode",
	"beego.RecoverPanic", "beego.BConfig.RecoverPanic",
	"beego.RouterCaseSensitive", "beego.BConfig.RouterCaseSensitive",
	"beego.BeegoServerName", "beego.BConfig.ServerName",
	"beego.EnableGzip", "beego.BConfig.EnableGzip",
	"beego.ErrorsShow", "beego.BConfig.EnableErrorsShow",
	"beego.CopyRequestBody", "beego.BConfig.CopyRequestBody",
	"beego.MaxMemory", "beego.BConfig.MaxMemory",
	"beego.Graceful", "beego.BConfig.Listen.Graceful",
	"beego.HttpAddr", "beego.BConfig.Listen.HTTPAddr",
	"beego.HttpPort", "beego.BConfig.Listen.HTTPPort",
	"beego.ListenTCP4", "beego.BConfig.Listen.ListenTCP4",
	"beego.EnableHttpListen", "beego.BConfig.Listen.HTTPEnable",
	"beego.EnableHttpTLS", "beego.BConfig.Listen.HTTPSEnable",
	"beego.HttpsAddr", "beego.BConfig.Listen.HTTPSAddr",
	"beego.HttpsPort", "beego.BConfig.Listen.HTTPSPort",
	"beego.HttpCertFile", "beego.BConfig.Listen.HTTPSCertFile",
	"beego.HttpKeyFile", "beego.BConfig.Listen.HTTPSKeyFile",
	"beego.EnableAdmin", "beego.BConfig.Listen.AdminEnable",
	"beego.AdminHttpAddr", "beego.BConfig.Listen.AdminAddr",
	"beego.AdminHttpPort", "beego.BConfig.Listen.AdminPort",
	"beego.UseFcgi", "beego.BConfig.Listen.EnableFcgi",
	"beego.HttpServerTimeOut", "beego.BConfig.Listen.ServerTimeOut",
	"beego.AutoRender", "beego.BConfig.WebConfig.AutoRender",
	"beego.ViewsPath", "beego.BConfig.WebConfig.ViewsPath",
	"beego.StaticDir", "beego.BConfig.WebConfig.StaticDir",
	"beego.StaticExtensionsToGzip", "beego.BConfig.WebConfig.StaticExtensionsToGzip",
	"beego.DirectoryIndex", "beego.BConfig.WebConfig.DirectoryIndex",
	"beego.FlashName", "beego.BConfig.WebConfig.FlashName",
	"beego.FlashSeperator", "beego.BConfig.WebConfig.FlashSeparator",
	"beego.EnableDocs", "beego.BConfig.WebConfig.EnableDocs",
	"beego.XSRFKEY", "beego.BConfig.WebConfig.XSRFKey",
	"beego.EnableXSRF", "beego.BConfig.WebConfig.EnableXSRF",
	"beego.XSRFExpire", "beego.BConfig.WebConfig.XSRFExpire",
	"beego.TemplateLeft", "beego.BConfig.WebConfig.TemplateLeft",
	"beego.TemplateRight", "beego.BConfig.WebConfig.TemplateRight",
	"beego.SessionOn", "beego.BConfig.WebConfig.Session.SessionOn",
	"beego.SessionProvider", "beego.BConfig.WebConfig.Session.SessionProvider",
	"beego.SessionName", "beego.BConfig.WebConfig.Session.SessionName",
	"beego.SessionGCMaxLifetime", "beego.BConfig.WebConfig.Session.SessionGCMaxLifetime",
	"beego.SessionSavePath", "beego.BConfig.WebConfig.Session.SessionProviderConfig",
	"beego.SessionCookieLifeTime", "beego.BConfig.WebConfig.Session.SessionCookieLifeTime",
	"beego.SessionAutoSetCookie", "beego.BConfig.WebConfig.Session.SessionAutoSetCookie",
	"beego.SessionDomain", "beego.BConfig.WebConfig.Session.SessionDomain",
	"Ctx.Input.CopyBody(", "Ctx.Input.CopyBody(beego.BConfig.MaxMemory",
	".UrlFor(", ".URLFor(",
	".ServeJson(", ".ServeJSON(",
	".ServeXml(", ".ServeXML(",
	".XsrfToken(", ".XSRFToken(",
	".CheckXsrfCookie(", ".CheckXSRFCookie(",
	".XsrfFormHtml(", ".XSRFFormHTML(",
	"beego.UrlFor(", "beego.URLFor(",
	"beego.GlobalDocApi", "beego.GlobalDocAPI",
	"beego.Errorhandler", "beego.ErrorHandler",
	"Output.Jsonp(", "Output.JSONP(",
	"Output.Json(", "Output.JSON(",
	"Output.Xml(", "Output.XML(",
	"Input.Uri()", "Input.URI()",
	"Input.Url()", "Input.URL()",
	"Input.AcceptsHtml()", "Input.AcceptsHTML()",
	"Input.AcceptsXml()", "Input.AcceptsXML()",
	"Input.AcceptsJson()", "Input.AcceptsJSON()",
	"Ctx.XsrfToken()", "Ctx.XSRFToken()",
	"Ctx.CheckXsrfCookie()", "Ctx.CheckXSRFCookie()",
	"session.SessionStore", "session.Store",
	".TplNames", ".TplName",
	"swagger.ApiRef", "swagger.APIRef",
	"swagger.ApiDeclaration", "swagger.APIDeclaration",
	"swagger.Api", "swagger.API",
	"swagger.ApiRef", "swagger.APIRef",
	"swagger.Infomation", "swagger.Information",
	"toolbox.UrlMap", "toolbox.URLMap",
	"logs.LoggerInterface", "logs.Logger",
	"Input.Request", "Input.Context.Request",
	"Input.Params)", "Input.Params())",
	"httplib.BeegoHttpSettings", "httplib.BeegoHTTPSettings",
	"httplib.BeegoHttpRequest", "httplib.BeegoHTTPRequest",
	".TlsClientConfig", ".TLSClientConfig",
	".JsonBody", ".JSONBody",
	".ToJson", ".ToJSON",
	".ToXml", ".ToXML",
	"beego.Html2str", "beego.HTML2str",
	"beego.AssetsCss", "beego.AssetsCSS",
	"orm.DR_Sqlite", "orm.DRSqlite",
	"orm.DR_Postgres", "orm.DRPostgres",
	"orm.DR_MySQL", "orm.DRMySQL",
	"orm.DR_Oracle", "orm.DROracle",
	"orm.Col_Add", "orm.ColAdd",
	"orm.Col_Minus", "orm.ColMinus",
	"orm.Col_Multiply", "orm.ColMultiply",
	"orm.Col_Except", "orm.ColExcept",
	"GenerateOperatorSql", "GenerateOperatorSQL",
	"OperatorSql", "OperatorSQL",
	"orm.Debug_Queries", "orm.DebugQueries",
	"orm.COMMA_SPACE", "orm.CommaSpace",
	".SendOut()", ".DoRequest()",
}

func fixFile(file string) error {
	rp := strings.NewReplacer(rules...)
	content, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}
	fixed := rp.Replace(string(content))

	// forword the RequestBody from the replace
	// "Input.Request", "Input.Context.Request",
	fixed = strings.Replace(fixed, "Input.Context.RequestBody", "Input.RequestBody", -1)

	// regexp replace
	pareg := regexp.MustCompile(`(Input.Params\[")(.*)("])`)
	fixed = pareg.ReplaceAllString(fixed, "Input.Param(\"$2\")")
	pareg = regexp.MustCompile(`(Input.Data\[\")(.*)(\"\])(\s)(=)(\s)(.*)`)
	fixed = pareg.ReplaceAllString(fixed, "Input.SetData(\"$2\", $7)")
	pareg = regexp.MustCompile(`(Input.Data\[\")(.*)(\"\])`)
	fixed = pareg.ReplaceAllString(fixed, "Input.Data(\"$2\")")
	// fix the cache object Put method
	pareg = regexp.MustCompile(`(\.Put\(\")(.*)(\",)(\s)(.*)(,\s*)([^\*.]*)(\))`)
	if pareg.MatchString(fixed) && strings.HasSuffix(file, ".go") {
		fixed = pareg.ReplaceAllString(fixed, ".Put(\"$2\", $5, $7*time.Second)")
		fset := token.NewFileSet() // positions are relative to fset
		f, err := parser.ParseFile(fset, file, nil, parser.ImportsOnly)
		if err != nil {
			panic(err)
		}
		// Print the imports from the file's AST.
		hasTimepkg := false
		for _, s := range f.Imports {
			if s.Path.Value == `"time"` {
				hasTimepkg = true
				break
			}
		}
		if !hasTimepkg {
			fixed = strings.Replace(fixed, "import (", "import (\n\t\"time\"", 1)
		}
	}
	// replace the v.Apis in docs.go
	if strings.Contains(file, "docs.go") {
		fixed = strings.Replace(fixed, "v.Apis", "v.APIs", -1)
	}
	// replace the config file
	if strings.HasSuffix(file, ".conf") {
		fixed = strings.Replace(fixed, "HttpCertFile", "HTTPSCertFile", -1)
		fixed = strings.Replace(fixed, "HttpKeyFile", "HTTPSKeyFile", -1)
		fixed = strings.Replace(fixed, "EnableHttpListen", "HTTPEnable", -1)
		fixed = strings.Replace(fixed, "EnableHttpTLS", "EnableHTTPS", -1)
		fixed = strings.Replace(fixed, "EnableHttpTLS", "EnableHTTPS", -1)
		fixed = strings.Replace(fixed, "BeegoServerName", "ServerName", -1)
		fixed = strings.Replace(fixed, "AdminHttpAddr", "AdminAddr", -1)
		fixed = strings.Replace(fixed, "AdminHttpPort", "AdminPort", -1)
		fixed = strings.Replace(fixed, "HttpServerTimeOut", "ServerTimeOut", -1)
	}
	err = os.Truncate(file, 0)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(file, []byte(fixed), 0666)
}
<commit_msg>fix #164 #165<commit_after>package main

import (
	"go/parser"
	"go/token"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

var cmdFix = &Command{
	UsageLine: "fix",
	Short:     "fix the beego application to compatibel with beego 1.6",
	Long: `
As from beego1.6, there's some incompatible code with the old version.

bee fix help to upgrade the application to beego 1.6
`,
}

func init() {
	cmdFix.Run = runFix
}

func runFix(cmd *Command, args []string) int {
	dir, err := os.Getwd()
	if err != nil {
		ColorLog("GetCurrent Path:%s\n", err)
	}
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			if strings.HasPrefix(info.Name(), ".") {
				return filepath.SkipDir
			}
			return nil
		}
		if err != nil {
			return err
		}
		if strings.HasSuffix(info.Name(), ".exe") {
			return nil
		}
		ColorLog("%s\n", path)
		err = fixFile(path)
		if err != nil {
			ColorLog("fixFile:%s\n", err)
		}
		return err
	})
	return 0
}

var rules = []string{
	"beego.AppName", "beego.BConfig.AppName",
	"beego.RunMode", "beego.BConfig.RunMode",
	"beego.RecoverPanic", "beego.BConfig.RecoverPanic",
	"beego.RouterCaseSensitive", "beego.BConfig.RouterCaseSensitive",
	"beego.BeegoServerName", "beego.BConfig.ServerName",
	"beego.EnableGzip", "beego.BConfig.EnableGzip",
	"beego.ErrorsShow", "beego.BConfig.EnableErrorsShow",
	"beego.CopyRequestBody", "beego.BConfig.CopyRequestBody",
	"beego.MaxMemory", "beego.BConfig.MaxMemory",
	"beego.Graceful", "beego.BConfig.Listen.Graceful",
	"beego.HttpAddr", "beego.BConfig.Listen.HTTPAddr",
	"beego.HttpPort", "beego.BConfig.Listen.HTTPPort",
	"beego.ListenTCP4", "beego.BConfig.Listen.ListenTCP4",
	"beego.EnableHttpListen", "beego.BConfig.Listen.HTTPEnable",
	"beego.EnableHttpTLS", "beego.BConfig.Listen.HTTPSEnable",
	"beego.HttpsAddr", "beego.BConfig.Listen.HTTPSAddr",
	"beego.HttpsPort", "beego.BConfig.Listen.HTTPSPort",
	"beego.HttpCertFile", "beego.BConfig.Listen.HTTPSCertFile",
	"beego.HttpKeyFile", "beego.BConfig.Listen.HTTPSKeyFile",
	"beego.EnableAdmin", "beego.BConfig.Listen.AdminEnable",
	"beego.AdminHttpAddr", "beego.BConfig.Listen.AdminAddr",
	"beego.AdminHttpPort", "beego.BConfig.Listen.AdminPort",
	"beego.UseFcgi", "beego.BConfig.Listen.EnableFcgi",
	"beego.HttpServerTimeOut", "beego.BConfig.Listen.ServerTimeOut",
	"beego.AutoRender", "beego.BConfig.WebConfig.AutoRender",
	"beego.ViewsPath", "beego.BConfig.WebConfig.ViewsPath",
	"beego.StaticDir", "beego.BConfig.WebConfig.StaticDir",
	"beego.StaticExtensionsToGzip", "beego.BConfig.WebConfig.StaticExtensionsToGzip",
	"beego.DirectoryIndex", "beego.BConfig.WebConfig.DirectoryIndex",
	"beego.FlashName", "beego.BConfig.WebConfig.FlashName",
	"beego.FlashSeperator", "beego.BConfig.WebConfig.FlashSeparator",
	"beego.EnableDocs", "beego.BConfig.WebConfig.EnableDocs",
	"beego.XSRFKEY", "beego.BConfig.WebConfig.XSRFKey",
	"beego.EnableXSRF", "beego.BConfig.WebConfig.EnableXSRF",
	"beego.XSRFExpire", "beego.BConfig.WebConfig.XSRFExpire",
	"beego.TemplateLeft", "beego.BConfig.WebConfig.TemplateLeft",
	"beego.TemplateRight", "beego.BConfig.WebConfig.TemplateRight",
	"beego.SessionOn", "beego.BConfig.WebConfig.Session.SessionOn",
	"beego.SessionProvider", "beego.BConfig.WebConfig.Session.SessionProvider",
	"beego.SessionName", "beego.BConfig.WebConfig.Session.SessionName",
	"beego.SessionGCMaxLifetime", "beego.BConfig.WebConfig.Session.SessionGCMaxLifetime",
	"beego.SessionSavePath", "beego.BConfig.WebConfig.Session.SessionProviderConfig",
	"beego.SessionCookieLifeTime", "beego.BConfig.WebConfig.Session.SessionCookieLifeTime",
	"beego.SessionAutoSetCookie", "beego.BConfig.WebConfig.Session.SessionAutoSetCookie",
	"beego.SessionDomain", "beego.BConfig.WebConfig.Session.SessionDomain",
	"Ctx.Input.CopyBody(", "Ctx.Input.CopyBody(beego.BConfig.MaxMemory",
	".UrlFor(", ".URLFor(",
	".ServeJson(", ".ServeJSON(",
	".ServeXml(", ".ServeXML(",
	".ServeJsonp(", ".ServeJSONP(",
	".XsrfToken(", ".XSRFToken(",
	".CheckXsrfCookie(", ".CheckXSRFCookie(",
	".XsrfFormHtml(", ".XSRFFormHTML(",
	"beego.UrlFor(", "beego.URLFor(",
	"beego.GlobalDocApi", "beego.GlobalDocAPI",
	"beego.Errorhandler", "beego.ErrorHandler",
	"Output.Jsonp(", "Output.JSONP(",
	"Output.Json(", "Output.JSON(",
	"Output.Xml(", "Output.XML(",
	"Input.Uri()", "Input.URI()",
	"Input.Url()", "Input.URL()",
	"Input.AcceptsHtml()", "Input.AcceptsHTML()",
	"Input.AcceptsXml()", "Input.AcceptsXML()",
	"Input.AcceptsJson()", "Input.AcceptsJSON()",
	"Ctx.XsrfToken()", "Ctx.XSRFToken()",
	"Ctx.CheckXsrfCookie()", "Ctx.CheckXSRFCookie()",
	"session.SessionStore", "session.Store",
	".TplNames", ".TplName",
	"swagger.ApiRef", "swagger.APIRef",
	"swagger.ApiDeclaration", "swagger.APIDeclaration",
	"swagger.Api", "swagger.API",
	"swagger.ApiRef", "swagger.APIRef",
	"swagger.Infomation", "swagger.Information",
	"toolbox.UrlMap", "toolbox.URLMap",
	"logs.LoggerInterface", "logs.Logger",
	"Input.Request", "Input.Context.Request",
	"Input.Params)", "Input.Params())",
	"httplib.BeegoHttpSettings", "httplib.BeegoHTTPSettings",
	"httplib.BeegoHttpRequest", "httplib.BeegoHTTPRequest",
	".TlsClientConfig", ".TLSClientConfig",
	".JsonBody", ".JSONBody",
	".ToJson", ".ToJSON",
	".ToXml", ".ToXML",
	"beego.Html2str", "beego.HTML2str",
	"beego.AssetsCss", "beego.AssetsCSS",
	"orm.DR_Sqlite", "orm.DRSqlite",
	"orm.DR_Postgres", "orm.DRPostgres",
	"orm.DR_MySQL", "orm.DRMySQL",
	"orm.DR_Oracle", "orm.DROracle",
	"orm.Col_Add", "orm.ColAdd",
	"orm.Col_Minus", "orm.ColMinus",
	"orm.Col_Multiply", "orm.ColMultiply",
	"orm.Col_Except", "orm.ColExcept",
	"GenerateOperatorSql", "GenerateOperatorSQL",
	"OperatorSql", "OperatorSQL",
	"orm.Debug_Queries", "orm.DebugQueries",
	"orm.COMMA_SPACE", "orm.CommaSpace",
	".SendOut()", ".DoRequest()",
	"validation.ValidationError", "validation.Error",
}

func fixFile(file string) error {
	rp := strings.NewReplacer(rules...)
	content, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}
	fixed := rp.Replace(string(content))

	// forword the RequestBody from the replace
	// "Input.Request", "Input.Context.Request",
	fixed = strings.Replace(fixed, "Input.Context.RequestBody", "Input.RequestBody", -1)

	// regexp replace
	pareg := regexp.MustCompile(`(Input.Params\[")(.*)("])`)
	fixed = pareg.ReplaceAllString(fixed, "Input.Param(\"$2\")")
	pareg = regexp.MustCompile(`(Input.Data\[\")(.*)(\"\])(\s)(=)(\s)(.*)`)
	fixed = pareg.ReplaceAllString(fixed, "Input.SetData(\"$2\", $7)")
	pareg = regexp.MustCompile(`(Input.Data\[\")(.*)(\"\])`)
	fixed = pareg.ReplaceAllString(fixed, "Input.Data(\"$2\")")
	// fix the cache object Put method
	pareg = regexp.MustCompile(`(\.Put\(\")(.*)(\",)(\s)(.*)(,\s*)([^\*.]*)(\))`)
	if pareg.MatchString(fixed) && strings.HasSuffix(file, ".go") {
		fixed = pareg.ReplaceAllString(fixed, ".Put(\"$2\", $5, $7*time.Second)")
		fset := token.NewFileSet() // positions are relative to fset
		f, err := parser.ParseFile(fset, file, nil, parser.ImportsOnly)
		if err != nil {
			panic(err)
		}
		// Print the imports from the file's AST.
		hasTimepkg := false
		for _, s := range f.Imports {
			if s.Path.Value == `"time"` {
				hasTimepkg = true
				break
			}
		}
		if !hasTimepkg {
			fixed = strings.Replace(fixed, "import (", "import (\n\t\"time\"", 1)
		}
	}
	// replace the v.Apis in docs.go
	if strings.Contains(file, "docs.go") {
		fixed = strings.Replace(fixed, "v.Apis", "v.APIs", -1)
	}
	// replace the config file
	if strings.HasSuffix(file, ".conf") {
		fixed = strings.Replace(fixed, "HttpCertFile", "HTTPSCertFile", -1)
		fixed = strings.Replace(fixed, "HttpKeyFile", "HTTPSKeyFile", -1)
		fixed = strings.Replace(fixed, "EnableHttpListen", "HTTPEnable", -1)
		fixed = strings.Replace(fixed, "EnableHttpTLS", "EnableHTTPS", -1)
		fixed = strings.Replace(fixed, "EnableHttpTLS", "EnableHTTPS", -1)
		fixed = strings.Replace(fixed, "BeegoServerName", "ServerName", -1)
		fixed = strings.Replace(fixed, "AdminHttpAddr", "AdminAddr", -1)
		fixed = strings.Replace(fixed, "AdminHttpPort", "AdminPort", -1)
		fixed = strings.Replace(fixed, "HttpServerTimeOut", "ServerTimeOut", -1)
	}
	err = os.Truncate(file, 0)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(file, []byte(fixed), 0666)
}
<|endoftext|>


<commit_before>package main

import (
	"net/url"
	"os"
	"strings"

	"github.com/libgit2/git2go"
)

// the git segment provides useful information about a git repository such as the domain of the "origin" remote (with an icon), the current branch, and whether the HEAD is dirty
func gitSegment(segment *segment) {
	dir, err := os.Getwd()
	check(err)
	repo, err := git.OpenRepositoryExtended(dir, 0, "/")
	if err != nil {
		return
	}

	var domain string
	remote, err := repo.Remotes.Lookup("origin")
	if err == nil {
		uri, err := url.Parse(remote.Url())
		check(err)
		domain = uri.Hostname()
		remote.Free()
	}

	var stashes int
	repo.Stashes.Foreach(func(int, string, *git.Oid) error {
		stashes++
		return nil
	})

	var commitsAhead int
	var branch string

	var dirty, modified, staged bool
	status, err := repo.StatusList(&git.StatusOptions{
		Flags: git.StatusOptIncludeUntracked,
	})
	check(err)
	count, err := status.EntryCount()
	check(err)
	if count != 0 {
		dirty = true
	}
	for i := 0; i < count; i++ {
		entry, err := status.ByIndex(i)
		check(err)
		if entry.Status&git.StatusWtNew != 0 || entry.Status&git.StatusWtModified != 0 || entry.Status&git.StatusWtDeleted != 0 || entry.Status&git.StatusWtTypeChange != 0 || entry.Status&git.StatusWtRenamed != 0 {
			modified = true
		}
		if entry.Status&git.StatusIndexNew != 0 || entry.Status&git.StatusIndexModified != 0 || entry.Status&git.StatusIndexDeleted != 0 || entry.Status&git.StatusIndexRenamed != 0 || entry.Status&git.StatusIndexTypeChange != 0 {
			staged = true
		}
	}
	status.Free()

	var segments []string
	switch domain {
	case "github.com":
		segments = append(segments, iconGithub)
	case "gitlab.com":
		segments = append(segments, iconGitlab)
	case "bitbucket.com":
		segments = append(segments, iconBitbucket)
	default:
		segments = append(segments, iconGit)
	}
	if stashes != 0 || commitsAhead != 0 {
		segments = append(segments, strings.Repeat(iconStash, stashes)+strings.Repeat(iconAhead, commitsAhead))
	}
	if branch != "" {
		segments = append(segments, branch)
	}
	if dirty {
		segment.background = "yellow"

		var icons string
		if modified {
			icons += iconCircle
		}
		if staged {
			icons += iconPlus
		}
		if icons != "" {
			segments = append(segments, icons)
		}
	}
	segment.visible = true
	segment.value = strings.Join(segments, " ")
}
<commit_msg>get branch<commit_after>package main

import (
	"net/url"
	"os"
	"strings"

	"github.com/libgit2/git2go"
)

// the git segment provides useful information about a git repository such as the domain of the "origin" remote (with an icon), the current branch, and whether the HEAD is dirty
func gitSegment(segment *segment) {
	dir, err := os.Getwd()
	check(err)
	repo, err := git.OpenRepositoryExtended(dir, 0, "/")
	if err != nil {
		return
	}

	var domain string
	remote, err := repo.Remotes.Lookup("origin")
	if err == nil {
		uri, err := url.Parse(remote.Url())
		check(err)
		domain = uri.Hostname()
		remote.Free()
	}

	var stashes int
	repo.Stashes.Foreach(func(int, string, *git.Oid) error {
		stashes++
		return nil
	})

	var commitsAhead int

	var branch string
	head, err := repo.Head()
	check(err)
	branch, err = head.Branch().Name()
	check(err)
	head.Free()

	var dirty, modified, staged bool
	status, err := repo.StatusList(&git.StatusOptions{
		Flags: git.StatusOptIncludeUntracked,
	})
	check(err)
	count, err := status.EntryCount()
	check(err)
	if count != 0 {
		dirty = true
	}
	for i := 0; i < count; i++ {
		entry, err := status.ByIndex(i)
		check(err)
		if entry.Status&git.StatusWtNew != 0 || entry.Status&git.StatusWtModified != 0 || entry.Status&git.StatusWtDeleted != 0 || entry.Status&git.StatusWtTypeChange != 0 || entry.Status&git.StatusWtRenamed != 0 {
			modified = true
		}
		if entry.Status&git.StatusIndexNew != 0 || entry.Status&git.StatusIndexModified != 0 || entry.Status&git.StatusIndexDeleted != 0 || entry.Status&git.StatusIndexRenamed != 0 || entry.Status&git.StatusIndexTypeChange != 0 {
			staged = true
		}
	}
	status.Free()

	var segments []string
	switch domain {
	case "github.com":
		segments = append(segments, iconGithub)
	case "gitlab.com":
		segments = append(segments, iconGitlab)
	case "bitbucket.com":
		segments = append(segments, iconBitbucket)
	default:
		segments = append(segments, iconGit)
	}
	if stashes != 0 || commitsAhead != 0 {
		segments = append(segments, strings.Repeat(iconStash, stashes)+strings.Repeat(iconAhead, commitsAhead))
	}
	if branch != "" {
		segments = append(segments, branch)
	}
	if dirty {
		segment.background = "yellow"

		var icons string
		if modified {
			icons += iconCircle
		}
		if staged {
			icons += iconPlus
		}
		if icons != "" {
			segments = append(segments, icons)
		}
	}
	segment.visible = true
	segment.value = strings.Join(segments, " ")
}
<|endoftext|>


<commit_before>package main

import (
	"os"
	"strings"

	"github.com/libgit2/git2go"
)

// the git segment provides useful information about a git repository such as the domain of the "origin" remote (with an icon), the current branch, and whether the HEAD is dirty
func gitSegment(segment *segment) {
	dir, err := os.Getwd()
	check(err)
	repo, err := git.OpenRepositoryExtended(dir, 0, "/")
	if err != nil {
		return
	}

	var domain string
	var stashes int
	var commitsAhead int
	var branch string
	var dirty, modified, staged bool

	var segments []string
	switch domain {
	case "github.com":
		segments = append(segments, iconGithub)
	case "gitlab.com":
		segments = append(segments, iconGitlab)
	case "bitbucket.com":
		segments = append(segments, iconBitbucket)
	default:
		segments = append(segments, iconGit)
	}
	if stashes != 0 || commitsAhead != 0 {
		segments = append(segments, strings.Repeat(iconStash, stashes)+strings.Repeat(iconAhead, commitsAhead))
	}
	if branch != "" {
		segments = append(segments, branch)
	}
	if dirty {
		segment.background = "yellow"

		var icons string
		if modified {
			icons += iconCircle
		}
		if staged {
			icons += iconPlus
		}
		if icons != "" {
			segments = append(segments, icons)
		}
	}
	segment.visible = true
	segment.value = strings.Join(segments, " ")
}
<commit_msg>get domain<commit_after>package main

import (
	"net/url"
	"os"
	"strings"

	"github.com/libgit2/git2go"
)

// the git segment provides useful information about a git repository such as the domain of the "origin" remote (with an icon), the current branch, and whether the HEAD is dirty
func gitSegment(segment *segment) {
	dir, err := os.Getwd()
	check(err)
	repo, err := git.OpenRepositoryExtended(dir, 0, "/")
	if err != nil {
		return
	}

	var domain string
	remote, err := repo.Remotes.Lookup("origin")
	if err == nil {
		uri, err := url.Parse(remote.Url())
		check(err)
		domain = uri.Hostname()
	}

	var stashes int
	var commitsAhead int
	var branch string
	var dirty, modified, staged bool

	var segments []string
	switch domain {
	case "github.com":
		segments = append(segments, iconGithub)
	case "gitlab.com":
		segments = append(segments, iconGitlab)
	case "bitbucket.com":
		segments = append(segments, iconBitbucket)
	default:
		segments = append(segments, iconGit)
	}
	if stashes != 0 || commitsAhead != 0 {
		segments = append(segments, strings.Repeat(iconStash, stashes)+strings.Repeat(iconAhead, commitsAhead))
	}
	if branch != "" {
		segments = append(segments, branch)
	}
	if dirty {
		segment.background = "yellow"

		var icons string
		if modified {
			icons += iconCircle
		}
		if staged {
			icons += iconPlus
		}
		if icons != "" {
			segments = append(segments, icons)
		}
	}
	segment.visible = true
	segment.value = strings.Join(segments, " ")
}
<|endoftext|>