<commit_before>package repo

import (
	"fmt"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/git"
)

// SetEditorconfigIfExists set editor config as render variable
func SetEditorconfigIfExists(ctx *context.Context) {
	ec, err := ctx.Repo.GetEditorconfig()

	if err != nil && !git.IsErrNotExist(err) {
		description := fmt.Sprintf("Error while getting .editorconfig file: %v", err)
		if err := models.CreateRepositoryNotice(description); err != nil {
			ctx.ServerError("ErrCreatingReporitoryNotice", err)
		}
		return
	}

	ctx.Data["Editorconfig"] = ec
}

// SetDiffViewStyle set diff style as render variable
func SetDiffViewStyle(ctx *context.Context) {
	queryStyle := ctx.Query("style")

	if !ctx.IsSigned {
		ctx.Data["IsSplitStyle"] = queryStyle == "split"
		return
	}

	var (
		userStyle = ctx.User.DiffViewStyle
		style     string
	)

	if queryStyle == "unified" || queryStyle == "split" {
		style = queryStyle
	} else if userStyle == "unified" || userStyle == "split" {
		style = userStyle
	} else {
		style = "unified"
	}

	ctx.Data["IsSplitStyle"] = style == "split"
	if err := ctx.User.UpdateDiffViewStyle(style); err != nil {
		ctx.ServerError("ErrUpdateDiffViewStyle", err)
	}
}

// SetWhitespaceBehavior set whitespace behavior as render variable
func SetWhitespaceBehavior(ctx *context.Context) {
	whitespaceBehavior := ctx.Query("whitespace")
	switch whitespaceBehavior {
	case "ignore-all", "ignore-eol", "ignore-change":
		ctx.Data["WhitespaceBehavior"] = whitespaceBehavior
	default:
		ctx.Data["WhitespaceBehavior"] = ""
	}
}
<commit_msg>fix wrong system notice when repository is empty (#9010)<commit_after>package repo

import (
	"fmt"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/git"
)

// SetEditorconfigIfExists set editor config as render variable
func SetEditorconfigIfExists(ctx *context.Context) {
	if ctx.Repo.Repository.IsEmpty {
		ctx.Data["Editorconfig"] = nil
		return
	}

	ec, err := ctx.Repo.GetEditorconfig()

	if err != nil && !git.IsErrNotExist(err) {
		description := fmt.Sprintf("Error while getting .editorconfig file: %v", err)
		if err := models.CreateRepositoryNotice(description); err != nil {
			ctx.ServerError("ErrCreatingReporitoryNotice", err)
		}
		return
	}

	ctx.Data["Editorconfig"] = ec
}

// SetDiffViewStyle set diff style as render variable
func SetDiffViewStyle(ctx *context.Context) {
	queryStyle := ctx.Query("style")

	if !ctx.IsSigned {
		ctx.Data["IsSplitStyle"] = queryStyle == "split"
		return
	}

	var (
		userStyle = ctx.User.DiffViewStyle
		style     string
	)

	if queryStyle == "unified" || queryStyle == "split" {
		style = queryStyle
	} else if userStyle == "unified" || userStyle == "split" {
		style = userStyle
	} else {
		style = "unified"
	}

	ctx.Data["IsSplitStyle"] = style == "split"
	if err := ctx.User.UpdateDiffViewStyle(style); err != nil {
		ctx.ServerError("ErrUpdateDiffViewStyle", err)
	}
}

// SetWhitespaceBehavior set whitespace behavior as render variable
func SetWhitespaceBehavior(ctx *context.Context) {
	whitespaceBehavior := ctx.Query("whitespace")
	switch whitespaceBehavior {
	case "ignore-all", "ignore-eol", "ignore-change":
		ctx.Data["WhitespaceBehavior"] = whitespaceBehavior
	default:
		ctx.Data["WhitespaceBehavior"] = ""
	}
}
<|endoftext|>


<commit_before>package app

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

	"github.com/gorilla/mux"
)

//Index useless println
func Index(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	fmt.Fprintln(w, "Welcome!")
}

//CatsIndex send a json back with all the cats database
func CatsIndex(w http.ResponseWriter, r *http.Request) {
	cat, err := searchImage("")
	if err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(cat); err != nil {
			panic(err)
		}
		fmt.Fprintln(w, cat)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(cat); err != nil {
		panic(err)
	}
	fmt.Fprintln(w, cat)
}

//CatShow show a specific required beautiful cat
func CatShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	catID := vars["catId"]
	cat, err := searchImage(catID)
	if err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(cat); err != nil {
			panic(err)
		}
		fmt.Fprintln(w, cat)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(cat); err != nil {
		panic(err)
	}
	fmt.Fprintln(w, cat)
}
<commit_msg>handler funcs now return pure json<commit_after>package app

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

	"github.com/gorilla/mux"
)

//Index useless println
func Index(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	fmt.Fprintln(w, "Welcome!")
}

//CatsIndex send a json back with all the cats database
func CatsIndex(w http.ResponseWriter, r *http.Request) {
	cat, err := searchImage("")
	if err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(cat); err != nil {
			panic(err)
		}
		fmt.Fprintln(w)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(cat); err != nil {
		panic(err)
	}
	fmt.Fprintln(w)
}

//CatShow show a specific required beautiful cat
func CatShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	catID := vars["catId"]
	cat, err := searchImage(catID)
	if err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(cat); err != nil {
			panic(err)
		}
		fmt.Fprintln(w)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(cat); err != nil {
		panic(err)
	}
	fmt.Fprintln(w)
}
<|endoftext|>


<commit_before>/*

*/

package zd

import "fmt"

// Ticket struct
type Ticket struct {
	ID         *float64 `json:"id,omitempty"`
	URL        *string  `json:"url,omitempty"`
	ExternalID *string  `json:"external_id,omitempty"`
	Type       *string  `json:"type,omitempty"`
	Subject    *string  `json:"subject,omitempty"`
	// No description for now it's pointless and clutters the db.
	// Description         *string             `json:"description,omitempty"`
	Priority            *string             `json:"priority,omitempty"`
	Status              *string             `json:"status,omitempty"`
	Recipient           *string             `json:"recipient,omitempty"`
	RequesterID         *float64            `json:"requester_id,omitempty"`
	SubmitterID         *float64            `json:"submitter_id,omitempty"`
	AssigneeID          *float64            `json:"assignee_id,omitempty"`
	OrganizationID      *float64            `json:"organization_id,omitempty"`
	GroupID             *float64            `json:"group_id,omitempty"`
	CollaboratorIDs     *[]float64          `json:"collaborator_ids,omitempty"`
	ForumTopicID        *float64            `json:"forum_topic_id,omitempty"`
	ProblemID           *float64            `json:"problem_id,omitempty"`
	HasIncidents        *bool               `json:"has_incidents,omitempty"`
	DueAt               *string             `json:"due_at,omitempty"`
	Tags                *[]string           `json:"tags,omitempty"`
	Via                 *Via                `json:"via,omitempty"`
	CustomFields        *[]CustomField      `json:"custom_fields,omitempty"`
	SatisfactionRating  *SatisfactionRating `json:"satisfaction_rating,omitempty"`
	SharingAgreementIds *[]float64          `json:"sharing_agreement_ids,omitempty"`
	FollowupIds         *[]float64          `json:"followup_ids,omitempty"`
	TicketFormID        *float64            `json:"ticket_form_id,omitempty"`
	BrandID             *float64            `json:"brand_id,omitempty"`
	CreatedAt           *string             `json:"created_at,omitempty"`
	UpdatedAt           *string             `json:"updated_at,omitempty"`
}

// Via struct
type Via struct {
	Channel *string      `json:"channel,omitempty"`
	Source  *interface{} `json:"source,omitempty"`
}

// CustomField struct
type CustomField struct {
	ID    *float64     `json:"id,omitempty"`
	Value *interface{} `json:"value"`
}

// SatisfactionRating struct
type SatisfactionRating struct {
	ID      *float64 `json:"id,omitempty"`
	Score   *string  `json:"score"`
	Comment *string  `json:"comment"`
}

// TicketResponse struct
type TicketResponse struct {
	Results  *[]Ticket `json:"tickets"`
	Next     *string   `json:"next_page,omitempty"`
	Previous *string   `json:"previous_page,omitempty"`
	Count    *int      `json:"count,omitempty"`
}

// TicketService struct
type TicketService struct {
	client *Client
}

// List returns a slice of all products
func (s *TicketService) List() ([]Ticket, error) {

	var resource []Ticket

	rp, _, _, err := s.getPage("")

	if err != nil {
		return nil, err
	}

	resource = append(resource, *rp...)

	// for next != nil {
	// 	rp, nx, _, err := s.getPage(*next)
	// 	if err != nil {
	// 		return nil, err
	// 	}
	// 	next = nx
	// 	resource = append(resource, *rp...)
	// }

	return resource, err
}

// GetAllProblems func
func (s *TicketService) GetAllProblems() ([]Ticket, error) {

	var resource []Ticket

	// Gets all tickets for this view
	rp, next, _, err := s.getPage("views/31672620/tickets.json") // Hardcoded "Problem tickets" view
	if err != nil {
		return nil, err
	}

	resource = append(resource, *rp...)

	for next != nil {
		rp, nx, _, err := s.getPage(*next)
		if err != nil {
			return nil, err
		}
		next = nx
		resource = append(resource, *rp...)
	}

	return resource, err
}

// GetProblemIncidents gets all problem tickets
func (s *TicketService) GetProblemIncidents(id string) ([]Ticket, error) {
	var resource []Ticket

	url := fmt.Sprintf("tickets/%s/incidents.json", id)

	rp, next, _, err := s.getPage(url)
	if err != nil {
		return nil, err
	}

	resource = append(resource, *rp...)

	for next != nil {
		rp, nx, _, err := s.getPage(*next)
		if err != nil {
			return nil, err
		}
		next = nx
		resource = append(resource, *rp...)
	}

	return resource, err
}

// GetProblemIncidentsCount gets only the first page of tickets which includes the count field
func (s *TicketService) GetProblemIncidentsCount(id string) (int, error) {

	url := fmt.Sprintf("tickets/%s/incidents.json", id)

	req, err := s.client.NewRequest("GET", url, nil)
	if err != nil {
		return 0, err
	}

	response := new(TicketResponse)
	_, err = s.client.Do(req, response)
	if err != nil {
		return 0, err
	}

	resource := response.Count
	return *resource, err
}

func (s *TicketService) getPage(url string) (*[]Ticket, *string, *Response, error) {

	if url == "" {
		url = "tickets.json"
	}

	req, err := s.client.NewRequest("GET", url, nil)
	if err != nil {
		return nil, nil, nil, err
	}

	response := new(TicketResponse)
	resp, err := s.client.Do(req, response)
	if err != nil {
		return nil, nil, resp, err
	}

	next := response.Next
	resource := response.Results
	return resource, next, resp, err
}

// GetOne method
func (s *TicketService) GetOne(id string) (*Ticket, *Response, error) {
	url := fmt.Sprintf("tickets/%s.json", id)

	req, err := s.client.NewRequest("GET", url, nil)
	if err != nil {
		return nil, nil, err
	}

	ticket := new(Ticket)
	resp, err := s.client.Do(req, &ticket)
	if err != nil {
		return nil, resp, err
	}

	return ticket, resp, err
}
<commit_msg>less retarded, more generic<commit_after>/*

*/

package zd

import "fmt"

// Ticket struct
type Ticket struct {
	ID         *float64 `json:"id,omitempty"`
	URL        *string  `json:"url,omitempty"`
	ExternalID *string  `json:"external_id,omitempty"`
	Type       *string  `json:"type,omitempty"`
	Subject    *string  `json:"subject,omitempty"`
	// No description for now it's pointless and clutters the db.
	// Description         *string             `json:"description,omitempty"`
	Priority            *string             `json:"priority,omitempty"`
	Status              *string             `json:"status,omitempty"`
	Recipient           *string             `json:"recipient,omitempty"`
	RequesterID         *float64            `json:"requester_id,omitempty"`
	SubmitterID         *float64            `json:"submitter_id,omitempty"`
	AssigneeID          *float64            `json:"assignee_id,omitempty"`
	OrganizationID      *float64            `json:"organization_id,omitempty"`
	GroupID             *float64            `json:"group_id,omitempty"`
	CollaboratorIDs     *[]float64          `json:"collaborator_ids,omitempty"`
	ForumTopicID        *float64            `json:"forum_topic_id,omitempty"`
	ProblemID           *float64            `json:"problem_id,omitempty"`
	HasIncidents        *bool               `json:"has_incidents,omitempty"`
	DueAt               *string             `json:"due_at,omitempty"`
	Tags                *[]string           `json:"tags,omitempty"`
	Via                 *Via                `json:"via,omitempty"`
	CustomFields        *[]CustomField      `json:"custom_fields,omitempty"`
	SatisfactionRating  *SatisfactionRating `json:"satisfaction_rating,omitempty"`
	SharingAgreementIds *[]float64          `json:"sharing_agreement_ids,omitempty"`
	FollowupIds         *[]float64          `json:"followup_ids,omitempty"`
	TicketFormID        *float64            `json:"ticket_form_id,omitempty"`
	BrandID             *float64            `json:"brand_id,omitempty"`
	CreatedAt           *string             `json:"created_at,omitempty"`
	UpdatedAt           *string             `json:"updated_at,omitempty"`
}

// Via struct
type Via struct {
	Channel *string      `json:"channel,omitempty"`
	Source  *interface{} `json:"source,omitempty"`
}

// CustomField struct
type CustomField struct {
	ID    *float64     `json:"id,omitempty"`
	Value *interface{} `json:"value"`
}

// SatisfactionRating struct
type SatisfactionRating struct {
	ID      *float64 `json:"id,omitempty"`
	Score   *string  `json:"score"`
	Comment *string  `json:"comment"`
}

// TicketResponse struct
type TicketResponse struct {
	Results  *[]Ticket `json:"tickets"`
	Next     *string   `json:"next_page,omitempty"`
	Previous *string   `json:"previous_page,omitempty"`
	Count    *int      `json:"count,omitempty"`
}

// TicketService struct
type TicketService struct {
	client *Client
}

// List returns a slice of all products
func (s *TicketService) List() ([]Ticket, error) {

	var resource []Ticket

	rp, _, _, err := s.getPage("")

	if err != nil {
		return nil, err
	}

	resource = append(resource, *rp...)

	// for next != nil {
	// 	rp, nx, _, err := s.getPage(*next)
	// 	if err != nil {
	// 		return nil, err
	// 	}
	// 	next = nx
	// 	resource = append(resource, *rp...)
	// }

	return resource, err
}

// ListByView function
func (s *TicketService) ListByView(id string) ([]Ticket, error) {

	var resource []Ticket

	url := fmt.Sprintf("views/%s/tickets.json", id)
	rp, next, _, err := s.getPage(url) // Hardcoded "Problem tickets" view
	if err != nil {
		return nil, err
	}

	resource = append(resource, *rp...)

	for next != nil {
		rp, nx, _, err := s.getPage(*next)
		if err != nil {
			return nil, err
		}
		next = nx
		resource = append(resource, *rp...)
	}

	return resource, err
}

// GetProblemIncidents gets all problem tickets
func (s *TicketService) GetProblemIncidents(id string) ([]Ticket, error) {
	var resource []Ticket

	url := fmt.Sprintf("tickets/%s/incidents.json", id)

	rp, next, _, err := s.getPage(url)
	if err != nil {
		return nil, err
	}

	resource = append(resource, *rp...)

	for next != nil {
		rp, nx, _, err := s.getPage(*next)
		if err != nil {
			return nil, err
		}
		next = nx
		resource = append(resource, *rp...)
	}

	return resource, err
}

// GetProblemIncidentsCount gets only the first page of tickets which includes the count field
func (s *TicketService) GetProblemIncidentsCount(id string) (int, error) {

	url := fmt.Sprintf("tickets/%s/incidents.json", id)

	req, err := s.client.NewRequest("GET", url, nil)
	if err != nil {
		return 0, err
	}

	response := new(TicketResponse)
	_, err = s.client.Do(req, response)
	if err != nil {
		return 0, err
	}

	resource := response.Count
	return *resource, err
}

func (s *TicketService) getPage(url string) (*[]Ticket, *string, *Response, error) {

	if url == "" {
		url = "tickets.json"
	}

	req, err := s.client.NewRequest("GET", url, nil)
	if err != nil {
		return nil, nil, nil, err
	}

	response := new(TicketResponse)
	resp, err := s.client.Do(req, response)
	if err != nil {
		return nil, nil, resp, err
	}

	next := response.Next
	resource := response.Results
	return resource, next, resp, err
}

// GetOne method
func (s *TicketService) GetOne(id string) (*Ticket, *Response, error) {
	url := fmt.Sprintf("tickets/%s.json", id)

	req, err := s.client.NewRequest("GET", url, nil)
	if err != nil {
		return nil, nil, err
	}

	ticket := new(Ticket)
	resp, err := s.client.Do(req, &ticket)
	if err != nil {
		return nil, resp, err
	}

	return ticket, resp, err
}
<|endoftext|>


<commit_before>package terraform

import (
	"strings"
	"testing"
)

func TestDiffTransformer_nilDiff(t *testing.T) {
	g := Graph{Path: RootModulePath}
	tf := &DiffTransformer{}
	if err := tf.Transform(&g); err != nil {
		t.Fatalf("err: %s", err)
	}

	if len(g.Vertices()) > 0 {
		t.Fatal("graph should be empty")
	}
}

func TestDiffTransformer(t *testing.T) {
	g := Graph{Path: RootModulePath}
	tf := &DiffTransformer{
		Module: testModule(t, "transform-diff-basic"),
		Diff: &Diff{
			Modules: []*ModuleDiff{
				&ModuleDiff{
					Path: []string{"root"},
					Resources: map[string]*InstanceDiff{
						"aws_instance.foo": &InstanceDiff{
							Attributes: map[string]*ResourceAttrDiff{
								"name": &ResourceAttrDiff{
									Old: "",
									New: "foo",
								},
							},
						},
					},
				},
			},
		},
	}
	if err := tf.Transform(&g); err != nil {
		t.Fatalf("err: %s", err)
	}

	actual := strings.TrimSpace(g.String())
	expected := strings.TrimSpace(testTransformDiffBasicStr)
	if actual != expected {
		t.Fatalf("bad:\n\n%s", actual)
	}

	v := g.Vertices()[0].(*NodeApplyableResource)
	if v.Config == nil {
		t.Fatal("no config")
	}
}

const testTransformDiffBasicStr = `
aws_instance.foo
`
<commit_msg>terraform: remove diff transformer test that no longer happens<commit_after>package terraform

import (
	"strings"
	"testing"
)

func TestDiffTransformer_nilDiff(t *testing.T) {
	g := Graph{Path: RootModulePath}
	tf := &DiffTransformer{}
	if err := tf.Transform(&g); err != nil {
		t.Fatalf("err: %s", err)
	}

	if len(g.Vertices()) > 0 {
		t.Fatal("graph should be empty")
	}
}

func TestDiffTransformer(t *testing.T) {
	g := Graph{Path: RootModulePath}
	tf := &DiffTransformer{
		Module: testModule(t, "transform-diff-basic"),
		Diff: &Diff{
			Modules: []*ModuleDiff{
				&ModuleDiff{
					Path: []string{"root"},
					Resources: map[string]*InstanceDiff{
						"aws_instance.foo": &InstanceDiff{
							Attributes: map[string]*ResourceAttrDiff{
								"name": &ResourceAttrDiff{
									Old: "",
									New: "foo",
								},
							},
						},
					},
				},
			},
		},
	}
	if err := tf.Transform(&g); err != nil {
		t.Fatalf("err: %s", err)
	}

	actual := strings.TrimSpace(g.String())
	expected := strings.TrimSpace(testTransformDiffBasicStr)
	if actual != expected {
		t.Fatalf("bad:\n\n%s", actual)
	}
}

const testTransformDiffBasicStr = `
aws_instance.foo
`
<|endoftext|>


<commit_before>package config

type (
	// Config holds all the configuration variables of socialapi
	Config struct {
		// Postres holds connection credentials for postgresql
		Postgres Postgres

		// Mq holds connction credentials for rabbitmq
		Mq Mq

		// Redis holds connection string for redis
		Redis Redis

		// Mongo holds full connection string
		Mongo string `env:"key=KONFIG_SOCIALAPI_MONGO                                 required"`

		// Environment holds the environment of the the running application
		Environment string `env:"key=KONFIG_SOCIALAPI_ENVIRONMENT                     required"`

		// Region holds the region of the the running application
		Region string `env:"key=KONFIG_SOCIALAPI_REGION                               required"`

		// Hostname is the web end point the app
		Hostname string `env:"key=KONFIG_SOCIALAPI_HOSTNAME                           required"`

		// Protocol holds used protocol information
		Protocol string `env:"key=KONFIG_SOCIALAPI_PROTOCOL                           required"`

		// Email holds the required configuration data for email related workers
		Email Email

		// Sitemap holds configuration for Sitemap workers
		Sitemap Sitemap

		// Algolia holds configuration parameters for Aloglia search engine
		Algolia Algolia

		// Mixpanel holds configuration parameters for mixpanel
		Mixpanel Mixpanel

		// Limits holds limits for various cases
		Limits Limits

		Stripe Stripe

		Paypal Paypal

		// Holds access information for realtime message authenticator
		GateKeeper GateKeeper

		// random access configs
		EventExchangeName string `env:"key=KONFIG_SOCIALAPI_EVENTEXCHANGENAME               required  default=BrokerMessageBus"`
		DisableCaching    bool   `env:"key=KONFIG_SOCIALAPI_DISABLECACHING                  required  default=false"`
		Debug             bool   `env:"key=KONFIG_SOCIALAPI_DEBUG 					       		      default=false"`

		// just a temp hack
		Host string
		Port string

		CustomDomain CustomDomain
	}

	// Postgres holds Postgresql database related configuration
	Postgres struct {
		Host     string `env:"key=KONFIG_SOCIALAPI_POSTGRES_HOST                            required"`
		Port     int    `env:"key=KONFIG_SOCIALAPI_POSTGRES_PORT                            required  default=5432"`
		Username string `env:"key=KONFIG_SOCIALAPI_POSTGRES_USERNAME                        required  default=socialapplication"`
		Password string `env:"key=KONFIG_SOCIALAPI_POSTGRES_PASSWORD                        required  default=socialapplication"`
		DBName   string `env:"key=KONFIG_SOCIALAPI_POSTGRES_DBNAME                          required  default=social"`
	}

	// Mq holds Rabbitmq related configuration
	Mq struct {
		Host     string `env:"key=KONFIG_SOCIALAPI_MQ_HOST                                  required"`
		Port     int    `env:"key=KONFIG_SOCIALAPI_MQ_PORT                                  required"`
		Login    string `env:"key=KONFIG_SOCIALAPI_MQ_LOGIN                                 required"`
		Password string `env:"key=KONFIG_SOCIALAPI_MQ_PASSWORD                              required"`
		Vhost    string `env:"key=KONFIG_SOCIALAPI_MQ_VHOST                                 required"`
	}

	// Redis holds Redis related config
	Redis struct {
		URL string `env:"key=KONFIG_SOCIALAPI_REDIS_URL                                    required"`
		DB  int    `env:"key=KONFIG_SOCIALAPI_REDIS_DB                                                  default=0"`
	}

	// Email holds Email Workers' config
	Email struct {
		Host            string `env:"key=KONFIG_SOCIALAPI_EMAIL_HOST                     required"`
		Protocol        string `env:"key=KONFIG_SOCIALAPI_EMAIL_PROTOCOL                 required"`
		DefaultFromMail string `env:"key=KONFIG_SOCIALAPI_EMAIL_DEFAULTFROMMAIL          required"`
		DefaultFromName string `env:"key=KONFIG_SOCIALAPI_EMAIL_DEFAULTFROMNAME          required"`
		ForcedRecipient string `env:"key=KONFIG_SOCIALAPI_EMAIL_FORCEDRECIPIENT"`
		Username        string `env:"key=KONFIG_SOCIALAPI_EMAIL_USERNAME                 required"`
		Password        string `env:"key=KONFIG_SOCIALAPI_EMAIL_PASSWORD                 required"`
		TemplateRoot    string `env:"key=KONFIG_SOCIALAPI_EMAIL_TEMPLATEROOT 	        default=workers/sitemap/files/"`
	}

	// Sitemap holds Sitemap Workers' config
	Sitemap struct {
		RedisDB int `env:"key=KONFIG_SOCIALAPI_SITEMAP_REDISDB"`
	}

	// Algolia holds Algolia service credentials
	Algolia struct {
		AppId        string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_APPID                        required"`
		ApiKey       string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_APIKEY                       required"`
		ApiSecretKey string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_APISECRETKEY                 required"`
		IndexSuffix  string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX                  required"`
	}

	// Mixpanel holds mixpanel credentials
	Mixpanel struct {
		Token   string `env:"key=KONFIG_SOCIALAPI_MIXPANEL_TOKEN                            required"`
		Enabled bool   `env:"key=KONFIG_SOCIALAPI_MIXPANEL_ENABLED"`
	}

	// Limits holds application's various limits
	Limits struct {
		MessageBodyMinLen    int    `env:"key=KONFIG_SOCIALAPI_LIMITS_MESSAGEBODYMINLEN     required default=1"`
		PostThrottleDuration string `env:"key=KONFIG_SOCIALAPI_LIMITS_POSTTHROTTLEDURATION  required default=5s"`
		PostThrottleCount    int    `env:"key=KONFIG_SOCIALAPI_LIMITS_POSTTHROTTLECOUNT     required default=20"`
	}

	Stripe struct {
		SecretToken string `env:"key=KONFIG_SOCIALAPI_STRIPE_SECRETTOKEN"`
	}

	Paypal struct {
		Username  string `env:"key=KONFIG_SOCIALAPI_PAYPAL_USERNAME"`
		Password  string `env:"key=KONFIG_SOCIALAPI_PAYPAL_PASSWORD"`
		Signature string `env:"key=KONFIG_SOCIALAPI_PAYPAL_SIGNATURE"`
		ReturnUrl string `env:"key=KONFIG_SOCIALAPI_PAYPAL_RETURNURL"`
		CancelUrl string `env:"key=KONFIG_SOCIALAPI_PAYPAL_CANCELURL"`
		IsSandbox bool   `env:"key=KONFIG_SOCIALAPI_PAYPAL_ISANDBOX"`
	}

	GateKeeper struct {
		Host   string `env:"key=KONFIG_GATEKEEPER_HOST"`
		Port   int    `env:"key=KONFIG_GATEKEEPER_PORT"`
		Pubnub Pubnub
	}

	Pubnub struct {
		PublishKey   string `env:"key=KONFIG_GATEKEEPER_PUBNUB_PUBLISHKEY"`
		SubscribeKey string `env:"key=KONFIG_GATEKEEPER_PUBNUB_SUBSCRIBEKEY"`
		SecretKey    string `env:"key=KONFIG_GATEKEEPER_PUBNUB_SECRETKEY"`
		Enabled      bool   `env:"key=KONFIG_GATEKEEPER_PUBNUB_ENABLED"`
	}

	CustomDomain struct {
		Public string `env:"key=KONFIG_CUSTOMDOMAIN_PUBLIC"`
	}
)
<commit_msg>config: add ProxyUrl to config types<commit_after>package config

type (
	// Config holds all the configuration variables of socialapi
	Config struct {
		// Postres holds connection credentials for postgresql
		Postgres Postgres

		// Mq holds connction credentials for rabbitmq
		Mq Mq

		// Redis holds connection string for redis
		Redis Redis

		// Mongo holds full connection string
		Mongo string `env:"key=KONFIG_SOCIALAPI_MONGO                                 required"`

		// Environment holds the environment of the the running application
		Environment string `env:"key=KONFIG_SOCIALAPI_ENVIRONMENT                     required"`

		// Region holds the region of the the running application
		Region string `env:"key=KONFIG_SOCIALAPI_REGION                               required"`

		// Hostname is the web end point the app
		Hostname string `env:"key=KONFIG_SOCIALAPI_HOSTNAME                           required"`

		// Protocol holds used protocol information
		Protocol string `env:"key=KONFIG_SOCIALAPI_PROTOCOL                           required"`

		// Email holds the required configuration data for email related workers
		Email Email

		// Sitemap holds configuration for Sitemap workers
		Sitemap Sitemap

		// Algolia holds configuration parameters for Aloglia search engine
		Algolia Algolia

		// Mixpanel holds configuration parameters for mixpanel
		Mixpanel Mixpanel

		// Limits holds limits for various cases
		Limits Limits

		Stripe Stripe

		Paypal Paypal

		// Holds access information for realtime message authenticator
		GateKeeper GateKeeper

		// random access configs
		EventExchangeName string `env:"key=KONFIG_SOCIALAPI_EVENTEXCHANGENAME               required  default=BrokerMessageBus"`
		DisableCaching    bool   `env:"key=KONFIG_SOCIALAPI_DISABLECACHING                  required  default=false"`
		Debug             bool   `env:"key=KONFIG_SOCIALAPI_DEBUG 					       		      default=false"`

		// just a temp hack
		Host     string
		Port     string
		ProxyURL string

		CustomDomain CustomDomain
	}

	// Postgres holds Postgresql database related configuration
	Postgres struct {
		Host     string `env:"key=KONFIG_SOCIALAPI_POSTGRES_HOST                            required"`
		Port     int    `env:"key=KONFIG_SOCIALAPI_POSTGRES_PORT                            required  default=5432"`
		Username string `env:"key=KONFIG_SOCIALAPI_POSTGRES_USERNAME                        required  default=socialapplication"`
		Password string `env:"key=KONFIG_SOCIALAPI_POSTGRES_PASSWORD                        required  default=socialapplication"`
		DBName   string `env:"key=KONFIG_SOCIALAPI_POSTGRES_DBNAME                          required  default=social"`
	}

	// Mq holds Rabbitmq related configuration
	Mq struct {
		Host     string `env:"key=KONFIG_SOCIALAPI_MQ_HOST                                  required"`
		Port     int    `env:"key=KONFIG_SOCIALAPI_MQ_PORT                                  required"`
		Login    string `env:"key=KONFIG_SOCIALAPI_MQ_LOGIN                                 required"`
		Password string `env:"key=KONFIG_SOCIALAPI_MQ_PASSWORD                              required"`
		Vhost    string `env:"key=KONFIG_SOCIALAPI_MQ_VHOST                                 required"`
	}

	// Redis holds Redis related config
	Redis struct {
		URL string `env:"key=KONFIG_SOCIALAPI_REDIS_URL                                    required"`
		DB  int    `env:"key=KONFIG_SOCIALAPI_REDIS_DB                                                  default=0"`
	}

	// Email holds Email Workers' config
	Email struct {
		Host            string `env:"key=KONFIG_SOCIALAPI_EMAIL_HOST                     required"`
		Protocol        string `env:"key=KONFIG_SOCIALAPI_EMAIL_PROTOCOL                 required"`
		DefaultFromMail string `env:"key=KONFIG_SOCIALAPI_EMAIL_DEFAULTFROMMAIL          required"`
		DefaultFromName string `env:"key=KONFIG_SOCIALAPI_EMAIL_DEFAULTFROMNAME          required"`
		ForcedRecipient string `env:"key=KONFIG_SOCIALAPI_EMAIL_FORCEDRECIPIENT"`
		Username        string `env:"key=KONFIG_SOCIALAPI_EMAIL_USERNAME                 required"`
		Password        string `env:"key=KONFIG_SOCIALAPI_EMAIL_PASSWORD                 required"`
		TemplateRoot    string `env:"key=KONFIG_SOCIALAPI_EMAIL_TEMPLATEROOT 	        default=workers/sitemap/files/"`
	}

	// Sitemap holds Sitemap Workers' config
	Sitemap struct {
		RedisDB int `env:"key=KONFIG_SOCIALAPI_SITEMAP_REDISDB"`
	}

	// Algolia holds Algolia service credentials
	Algolia struct {
		AppId        string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_APPID                        required"`
		ApiKey       string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_APIKEY                       required"`
		ApiSecretKey string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_APISECRETKEY                 required"`
		IndexSuffix  string `env:"key=KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX                  required"`
	}

	// Mixpanel holds mixpanel credentials
	Mixpanel struct {
		Token   string `env:"key=KONFIG_SOCIALAPI_MIXPANEL_TOKEN                            required"`
		Enabled bool   `env:"key=KONFIG_SOCIALAPI_MIXPANEL_ENABLED"`
	}

	// Limits holds application's various limits
	Limits struct {
		MessageBodyMinLen    int    `env:"key=KONFIG_SOCIALAPI_LIMITS_MESSAGEBODYMINLEN     required default=1"`
		PostThrottleDuration string `env:"key=KONFIG_SOCIALAPI_LIMITS_POSTTHROTTLEDURATION  required default=5s"`
		PostThrottleCount    int    `env:"key=KONFIG_SOCIALAPI_LIMITS_POSTTHROTTLECOUNT     required default=20"`
	}

	Stripe struct {
		SecretToken string `env:"key=KONFIG_SOCIALAPI_STRIPE_SECRETTOKEN"`
	}

	Paypal struct {
		Username  string `env:"key=KONFIG_SOCIALAPI_PAYPAL_USERNAME"`
		Password  string `env:"key=KONFIG_SOCIALAPI_PAYPAL_PASSWORD"`
		Signature string `env:"key=KONFIG_SOCIALAPI_PAYPAL_SIGNATURE"`
		ReturnUrl string `env:"key=KONFIG_SOCIALAPI_PAYPAL_RETURNURL"`
		CancelUrl string `env:"key=KONFIG_SOCIALAPI_PAYPAL_CANCELURL"`
		IsSandbox bool   `env:"key=KONFIG_SOCIALAPI_PAYPAL_ISANDBOX"`
	}

	GateKeeper struct {
		Host   string `env:"key=KONFIG_GATEKEEPER_HOST"`
		Port   int    `env:"key=KONFIG_GATEKEEPER_PORT"`
		Pubnub Pubnub
	}

	Pubnub struct {
		PublishKey   string `env:"key=KONFIG_GATEKEEPER_PUBNUB_PUBLISHKEY"`
		SubscribeKey string `env:"key=KONFIG_GATEKEEPER_PUBNUB_SUBSCRIBEKEY"`
		SecretKey    string `env:"key=KONFIG_GATEKEEPER_PUBNUB_SECRETKEY"`
		Enabled      bool   `env:"key=KONFIG_GATEKEEPER_PUBNUB_ENABLED"`
	}

	CustomDomain struct {
		Public string `env:"key=KONFIG_CUSTOMDOMAIN_PUBLIC"`
	}
)
<|endoftext|>


<commit_before>package config

type (
	Config struct {
		Postgres          Postgres
		Mq                Mq
		Limits            Limits
		EventExchangeName string
		Redis             Redis
		Mongo             string
		Environment       string
		Uri               string
		Notification      Notification
		SendGrid          SendGrid
		EmailNotification EmailNotification
		Sitemap           Sitemap
	}

	Redis struct {
		URL   string
		DB    int
		Slave string
	}

	Postgres struct {
		Host     string
		Port     int
		Username string
		Password string
		DBName   string
	}
	Mq struct {
		Host     string
		Port     int
		Username string
		Password string
		Vhost    string
	}
	Limits struct {
		MessageBodyMinLen int
	}
	Notification struct {
		CacheEnabled bool
	}
	SendGrid struct {
		Username        string
		Password        string
		FromName        string
		FromMail        string
		ForcedRecipient string
	}
	EmailNotification struct {
		TemplateRoot string
	}
	Sitemap struct {
		RedisDB int
	}
)
<commit_msg>Social: add new config variables<commit_after>package config

type (
	Config struct {
		Postgres          Postgres
		Mq                Mq
		Limits            Limits
		EventExchangeName string
		Redis             Redis
		Mongo             string
		Environment       string
		Uri               string
		Notification      Notification
		SendGrid          SendGrid
		EmailNotification EmailNotification
		Sitemap           Sitemap
	}

	Redis struct {
		URL   string
		DB    int
		Slave string
	}

	Postgres struct {
		Host     string
		Port     int
		Username string
		Password string
		DBName   string
	}
	Mq struct {
		Host     string
		Port     int
		Username string
		Password string
		Vhost    string
	}
	Limits struct {
		MessageBodyMinLen    int
		PostThrottleDuration string
		PostThrottleCount    int
	}
	Notification struct {
		CacheEnabled bool
	}
	SendGrid struct {
		Username        string
		Password        string
		FromName        string
		FromMail        string
		ForcedRecipient string
	}
	EmailNotification struct {
		TemplateRoot string
	}
	Sitemap struct {
		RedisDB int
	}
)
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, 2014 Conformal Systems LLC <info@conformal.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

// Package tx provides an implementation of a transaction store for a
// bitcoin wallet.  Its primary purpose is to save transactions with
// outputs spendable with wallet keys and transactions that are signed by
// wallet keys in memory, handle spend tracking for newly-inserted
// transactions, report the spendable balance from each unspent
// transaction output, and finally to provide a means to serialize the
// entire data structure to an io.Writer and deserialize from an io.Reader
// (both of which are usually an os.File).
//
// Transaction outputs which are spendable by wallet keys are called
// credits (because they credit to a wallet's total spendable balance)
// and are modeled using the Credit structure.  Transaction inputs which
// spend previously-inserted credits are called debits (because they debit
// from the wallet's spendable balance) and are modeled using the Debit
// structure.
//
// Besides just saving transactions, bidirectional spend tracking is also
// performed on each credit and debit.  Unlike packages such as btcdb,
// which only mark whether a transaction output is spent or unspent, this
// package always records which transaction is responsible for debiting
// (spending) any credit.  Each debit also points back to the transaction
// credit it spends.
//
// A significant amount of internal bookkeeping is used to improve the
// performance of inserting transactions and querying commonly-needed
// data.  Most notably, all unspent credits may be iterated over without
// including (and ignoring) spent credits.  Another trick is to record
// the total spendable amount delta as a result of all transactions within
// a block, which is the total value of all credits (both spent and
// unspent) minus the total value debited from previous transactions, for
// every transaction in that block.  This allows for the calculation of a
// wallet's balance for any arbitrary number of confirmations without
// needing to iterate over every unspent credit.
//
// Finally, this package records transaction insertion history (such as
// the date a transaction was first received0 and is able to create the
// JSON reply structure for RPC calls such as listtransactions for any
// saved transaction.
//
// To use the transaction store, a transaction must be first inserted
// with InsertTx.  After an insert, credits and debits may be attached to
// the returned transaction record using the AddCredit and AddDebits
// methods.
//
// Example use:
//
//	// Create a new transaction store to hold two transactions.
//	s := tx.NewStore()
//
//	// Insert a transaction belonging to some imaginary block at
//	// height 123.
//	b123 := &tx.Block{Height: 123, Time: time.Now()}
//	r1, err := s.InsertTx(txA, b123)
//	if err != nil {
//		// handle error
//	}
//
//	// Mark output 0 as being a non-change credit to this wallet.
//	c1o0, err := r1.AddCredit(0, false)
//	if err != nil {
//		// handle error
//	}
//
//	// c1o0 (credit 1 output 0) is inserted unspent.
//	fmt.Println(c1o0.Spent())      // Prints "false"
//	fmt.Println(s.Balance(1, 123)) // Prints amount of txA output 0.
//
//	// Insert a second transaction at some imaginary block height
//	// 321.
//	b321 := &tx.Block{Height: 321, Time: time.Now()}
//	r2, err := s.InsertTx(txB, b321)
//	if err != nil {
//		// handle error
//	}
//
//	// Mark r2 as debiting from record 1's 0th credit.
//	d2, err := r2.AddDebits([]*tx.Credit{c1o0})
//	if err != nil {
//		// handle error
//	}
//
//	// Spend tracking and the balances are updated accordingly.
//	fmt.Println(c1o0.Spent())      // Prints "true"
//	fmt.Println(s.Balance(1, 321)) // Prints "0 BTC"
//	fmt.Println(d2.InputAmount())  // Prints amount of txA output 0.
package tx
<commit_msg>Fix another typo.<commit_after>/*
 * Copyright (c) 2013, 2014 Conformal Systems LLC <info@conformal.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

// Package tx provides an implementation of a transaction store for a
// bitcoin wallet.  Its primary purpose is to save transactions with
// outputs spendable with wallet keys and transactions that are signed by
// wallet keys in memory, handle spend tracking for newly-inserted
// transactions, report the spendable balance from each unspent
// transaction output, and finally to provide a means to serialize the
// entire data structure to an io.Writer and deserialize from an io.Reader
// (both of which are usually an os.File).
//
// Transaction outputs which are spendable by wallet keys are called
// credits (because they credit to a wallet's total spendable balance)
// and are modeled using the Credit structure.  Transaction inputs which
// spend previously-inserted credits are called debits (because they debit
// from the wallet's spendable balance) and are modeled using the Debit
// structure.
//
// Besides just saving transactions, bidirectional spend tracking is also
// performed on each credit and debit.  Unlike packages such as btcdb,
// which only mark whether a transaction output is spent or unspent, this
// package always records which transaction is responsible for debiting
// (spending) any credit.  Each debit also points back to the transaction
// credit it spends.
//
// A significant amount of internal bookkeeping is used to improve the
// performance of inserting transactions and querying commonly-needed
// data.  Most notably, all unspent credits may be iterated over without
// including (and ignoring) spent credits.  Another trick is to record
// the total spendable amount delta as a result of all transactions within
// a block, which is the total value of all credits (both spent and
// unspent) minus the total value debited from previous transactions, for
// every transaction in that block.  This allows for the calculation of a
// wallet's balance for any arbitrary number of confirmations without
// needing to iterate over every unspent credit.
//
// Finally, this package records transaction insertion history (such as
// the date a transaction was first received) and is able to create the
// JSON reply structure for RPC calls such as listtransactions for any
// saved transaction.
//
// To use the transaction store, a transaction must be first inserted
// with InsertTx.  After an insert, credits and debits may be attached to
// the returned transaction record using the AddCredit and AddDebits
// methods.
//
// Example use:
//
//	// Create a new transaction store to hold two transactions.
//	s := tx.NewStore()
//
//	// Insert a transaction belonging to some imaginary block at
//	// height 123.
//	b123 := &tx.Block{Height: 123, Time: time.Now()}
//	r1, err := s.InsertTx(txA, b123)
//	if err != nil {
//		// handle error
//	}
//
//	// Mark output 0 as being a non-change credit to this wallet.
//	c1o0, err := r1.AddCredit(0, false)
//	if err != nil {
//		// handle error
//	}
//
//	// c1o0 (credit 1 output 0) is inserted unspent.
//	fmt.Println(c1o0.Spent())      // Prints "false"
//	fmt.Println(s.Balance(1, 123)) // Prints amount of txA output 0.
//
//	// Insert a second transaction at some imaginary block height
//	// 321.
//	b321 := &tx.Block{Height: 321, Time: time.Now()}
//	r2, err := s.InsertTx(txB, b321)
//	if err != nil {
//		// handle error
//	}
//
//	// Mark r2 as debiting from record 1's 0th credit.
//	d2, err := r2.AddDebits([]*tx.Credit{c1o0})
//	if err != nil {
//		// handle error
//	}
//
//	// Spend tracking and the balances are updated accordingly.
//	fmt.Println(c1o0.Spent())      // Prints "true"
//	fmt.Println(s.Balance(1, 321)) // Prints "0 BTC"
//	fmt.Println(d2.InputAmount())  // Prints amount of txA output 0.
package tx
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
)

const execMode = 0755
const fileFmt = "ntwrk-%s-%s"
const updateUrl = "https://api.github.com/repos/waits/ntwrk/releases/latest"

type Release struct {
	Name   string  `json:"name"`
	Tag    string  `json:"tag_name"`
	Assets []Asset `json:"assets"`
}

type Asset struct {
	Name string `json:"name"`
	Url  string `json:"browser_download_url"`
}

func (rel *Release) assetForPlatform(os string, arch string) (a Asset, err error) {
	assetName := fmt.Sprintf(fileFmt, os, arch)
	for _, a = range rel.Assets {
		if a.Name == assetName {
			return
		}
	}
	err = fmt.Errorf("no release for %s/%s", os, arch)
	return
}

func update(host string) {
	rel, err := getLatestRelease()
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	if rel.Tag == "v"+version {
		fmt.Println("No update available.")
		return
	}

	asset, err := rel.assetForPlatform(runtime.GOOS, runtime.GOARCH)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	err = applyPatch(asset)
	if err != nil {
		fmt.Println("error:", err)
	}
}

func getLatestRelease() (rel Release, err error) {
	resp, err := http.Get(updateUrl)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	dat, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	json.Unmarshal(dat, &rel)
	return
}

func applyPatch(asset Asset) error {
	path := filepath.Join("/", "tmp", asset.Name)
	file, err := os.Create(path)
	if err != nil {
		return err
	}
	defer file.Close()
	defer os.Remove(path)

	err = file.Chmod(execMode)
	if err != nil {
		return err
	}

	fmt.Println("Downloading", asset.Url)
	resp, err := http.Get(asset.Url)
	if err != nil {
		return err
	}
	io.Copy(file, resp.Body)

	exec, err := os.Executable()
	if err != nil {
		return err
	}

	os.Rename(exec, exec+".old")
	os.Rename(path, exec)
	os.Remove(exec + ".old")

	return nil
}
<commit_msg>Fix version check in `update` command<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
)

const execMode = 0755
const fileFmt = "ntwrk-%s-%s"
const updateUrl = "https://api.github.com/repos/waits/ntwrk/releases/latest"

type Release struct {
	Name   string  `json:"name"`
	Tag    string  `json:"tag_name"`
	Assets []Asset `json:"assets"`
}

type Asset struct {
	Name string `json:"name"`
	Url  string `json:"browser_download_url"`
}

func (rel *Release) assetForPlatform(os string, arch string) (a Asset, err error) {
	assetName := fmt.Sprintf(fileFmt, os, arch)
	for _, a = range rel.Assets {
		if a.Name == assetName {
			return
		}
	}
	err = fmt.Errorf("no release for %s/%s", os, arch)
	return
}

func update(host string) {
	rel, err := getLatestRelease()
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	if rel.Tag == version {
		fmt.Println("No update available.")
		return
	}

	asset, err := rel.assetForPlatform(runtime.GOOS, runtime.GOARCH)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	err = applyPatch(asset)
	if err != nil {
		fmt.Println("error:", err)
	}
}

func getLatestRelease() (rel Release, err error) {
	resp, err := http.Get(updateUrl)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	dat, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	json.Unmarshal(dat, &rel)
	return
}

func applyPatch(asset Asset) error {
	path := filepath.Join("/", "tmp", asset.Name)
	file, err := os.Create(path)
	if err != nil {
		return err
	}
	defer file.Close()
	defer os.Remove(path)

	err = file.Chmod(execMode)
	if err != nil {
		return err
	}

	fmt.Println("Downloading", asset.Url)
	resp, err := http.Get(asset.Url)
	if err != nil {
		return err
	}
	io.Copy(file, resp.Body)

	exec, err := os.Executable()
	if err != nil {
		return err
	}

	os.Rename(exec, exec+".old")
	os.Rename(path, exec)
	os.Remove(exec + ".old")

	return nil
}
<|endoftext|>


<commit_before>package reviewdog

import (
	"fmt"
	"log"
	"os/exec"
	"sync"
	"time"

	"golang.org/x/sync/errgroup"

	"github.com/google/go-github/github"
)

var _ = github.ScopeAdminOrg

var _ CommentService = &GitHubPullRequest{}
var _ DiffService = &GitHubPullRequest{}

// `path` to `position`(Lnum for new file) to comment `body`s
type postedcomments map[string]map[int][]string

// IsPosted returns true if a given comment has been posted in GitHub already,
// otherwise returns false. It sees comments with same path, same position,
// and same body as same comments.
func (p postedcomments) IsPosted(c *Comment) bool {
	if _, ok := p[c.Path]; !ok {
		return false
	}
	bodys, ok := p[c.Path][c.LnumDiff]
	if !ok {
		return false
	}
	for _, body := range bodys {
		if body == commentBody(c) {
			return true
		}
	}
	return false
}

// GitHubPullRequest is a comment and diff service for GitHub PullRequest.
//
// API:
//	https://developer.github.com/v3/pulls/comments/#create-a-comment
// 	POST /repos/:owner/:repo/pulls/:number/comments
type GitHubPullRequest struct {
	postComments []*Comment

	cli   *github.Client
	owner string
	repo  string
	pr    int
	sha   string

	postedcs postedcomments

	muFlash sync.Mutex
}

// NewGitHubPullReqest returns a new GitHubPullRequest service.
func NewGitHubPullReqest(cli *github.Client, owner, repo string, pr int, sha string) *GitHubPullRequest {
	return &GitHubPullRequest{
		cli:   cli,
		owner: owner,
		repo:  repo,
		pr:    pr,
		sha:   sha,
	}
}

func F() {
	go func() {
		var tick = time.Tick(1 * time.Second)
		for t := range tick {
			fmt.Println(t)
		}
	}()
}

// Post accepts a comment and holds it. Flash method actually posts comments to
// GitHub in parallel.
func (g *GitHubPullRequest) Post(c *Comment) error {
	g.muFlash.Lock()
	defer g.muFlash.Unlock()
	g.postComments = append(g.postComments, c)
	return nil
}

const bodyPrefix = `<sub>reported by [reviewdog](https://github.com/haya14busa/reviewdog) :dog:</sub>`

func commentBody(c *Comment) string {
	tool := ""
	if c.ToolName != "" {
		tool = fmt.Sprintf("**[%s]** ", c.ToolName)
	}
	return tool + bodyPrefix + "\n" + c.Body
}

var githubAPIHost = "api.github.com"

// Flash posts comments which has not been posted yet.
func (g *GitHubPullRequest) Flash() error {
	g.muFlash.Lock()
	defer g.muFlash.Unlock()

	if err := g.setPostedComment(); err != nil {
		return err
	}
	// TODO(haya14busa,#58): remove host check when GitHub Enterprise supports
	// Pull Request API.
	if g.cli.BaseURL.Host == githubAPIHost {
		return g.postAsReviewComment()
	}
	return g.postCommentsForEach()
}

func (g *GitHubPullRequest) postAsReviewComment() error {
	comments := make([]*ReviewComment, 0, len(g.postComments))
	for _, c := range g.postComments {
		if g.postedcs.IsPosted(c) {
			continue
		}
		cbody := commentBody(c)
		comments = append(comments, &ReviewComment{
			Path:     &c.Path,
			Position: &c.LnumDiff,
			Body:     &cbody,
		})
	}

	if len(comments) == 0 {
		return nil
	}

	// TODO(haya14busa): it might be useful to report overview results by "body"
	// field.
	event := "COMMENT"
	review := &Review{Event: &event, Comments: comments}

	_, _, err := g.CreateReview(g.owner, g.repo, g.pr, review)
	return err
}

func (g *GitHubPullRequest) postCommentsForEach() error {
	var eg errgroup.Group
	for _, c := range g.postComments {
		comment := c
		if g.postedcs.IsPosted(comment) {
			continue
		}
		eg.Go(func() error {
			body := commentBody(comment)
			prcomment := &github.PullRequestComment{
				CommitID: &g.sha,
				Body:     &body,
				Path:     &comment.Path,
				Position: &comment.LnumDiff,
			}
			_, _, err := g.cli.PullRequests.CreateComment(g.owner, g.repo, g.pr, prcomment)
			return err
		})
	}
	return eg.Wait()
}

func (g *GitHubPullRequest) setPostedComment() error {
	g.postedcs = make(postedcomments)
	cs, err := g.comment()
	if err != nil {
		return err
	}
	for _, c := range cs {
		if c.Position == nil || c.Path == nil || c.Body == nil {
			// skip resolved comments. Or comments which do not have "path" nor
			// "body".
			continue
		}
		path := *c.Path
		pos := *c.Position
		body := *c.Body
		if _, ok := g.postedcs[path]; !ok {
			g.postedcs[path] = make(map[int][]string)
		}
		if _, ok := g.postedcs[path][pos]; !ok {
			g.postedcs[path][pos] = make([]string, 0)
		}
		g.postedcs[path][pos] = append(g.postedcs[path][pos], body)
	}
	return nil
}

// Diff returns a diff of PullRequest. It runs `git diff` locally instead of
// diff_url of GitHub Pull Request because diff of diff_url is not suited for
// comment API in a sense that diff of diff_url is equivalent to
// `git diff --no-renames`, we want diff which is equivalent to
// `git diff --find-renames`.
func (g *GitHubPullRequest) Diff() ([]byte, error) {
	pr, _, err := g.cli.PullRequests.Get(g.owner, g.repo, g.pr)
	if err != nil {
		return nil, err
	}
	return exec.Command("git", "diff", "--find-renames", *pr.Base.SHA, g.sha).Output()
}

// Strip returns 1 as a strip of git diff.
func (g *GitHubPullRequest) Strip() int {
	return 1
}

func (g *GitHubPullRequest) comment() ([]*github.PullRequestComment, error) {
	comments, _, err := g.cli.PullRequests.ListComments(g.owner, g.repo, g.pr, nil)
	if err != nil {
		return nil, err
	}
	return comments, nil
}

// ---
// GitHub PullRequest Review API Implementation
// ref: https://github.com/google/go-github/issues/495

const (
	mediaTypePullRequestReview = "application/vnd.github.black-cat-preview+json"
)

// Review represents a pull request review.
type Review struct {
	Body     *string          `json:"body,omitempty"`
	Event    *string          `json:"event,omitempty"`
	Comments []*ReviewComment `json:"comments,omitempty"`
}

// ReviewComment represents draft review comments.
type ReviewComment struct {
	Path     *string `json:"path,omitempty"`
	Position *int    `json:"position,omitempty"`
	Body     *string `json:"body,omitempty"`
}

// CreateReview creates a new review comment on the specified pull request.
//
// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#create-a-pull-request-review
func (g *GitHubPullRequest) CreateReview(owner, repo string, number int, review *Review) (*github.PullRequestReview, *github.Response, error) {
	u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number)

	req, err := g.cli.NewRequest("POST", u, review)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypePullRequestReview)

	r := new(github.PullRequestReview)
	resp, err := g.cli.Do(req, r)
	if err != nil {
		log.Printf("GitHub Review API error: %v", err)
		return nil, resp, err
	}
	return r, resp, err
}
<commit_msg>Revert "[revert later] add stupid code"<commit_after>package reviewdog

import (
	"fmt"
	"log"
	"os/exec"
	"sync"

	"golang.org/x/sync/errgroup"

	"github.com/google/go-github/github"
)

var _ = github.ScopeAdminOrg

var _ CommentService = &GitHubPullRequest{}
var _ DiffService = &GitHubPullRequest{}

// `path` to `position`(Lnum for new file) to comment `body`s
type postedcomments map[string]map[int][]string

// IsPosted returns true if a given comment has been posted in GitHub already,
// otherwise returns false. It sees comments with same path, same position,
// and same body as same comments.
func (p postedcomments) IsPosted(c *Comment) bool {
	if _, ok := p[c.Path]; !ok {
		return false
	}
	bodys, ok := p[c.Path][c.LnumDiff]
	if !ok {
		return false
	}
	for _, body := range bodys {
		if body == commentBody(c) {
			return true
		}
	}
	return false
}

// GitHubPullRequest is a comment and diff service for GitHub PullRequest.
//
// API:
//	https://developer.github.com/v3/pulls/comments/#create-a-comment
// 	POST /repos/:owner/:repo/pulls/:number/comments
type GitHubPullRequest struct {
	postComments []*Comment

	cli   *github.Client
	owner string
	repo  string
	pr    int
	sha   string

	postedcs postedcomments

	muFlash sync.Mutex
}

// NewGitHubPullReqest returns a new GitHubPullRequest service.
func NewGitHubPullReqest(cli *github.Client, owner, repo string, pr int, sha string) *GitHubPullRequest {
	return &GitHubPullRequest{
		cli:   cli,
		owner: owner,
		repo:  repo,
		pr:    pr,
		sha:   sha,
	}
}

// Post accepts a comment and holds it. Flash method actually posts comments to
// GitHub in parallel.
func (g *GitHubPullRequest) Post(c *Comment) error {
	g.muFlash.Lock()
	defer g.muFlash.Unlock()
	g.postComments = append(g.postComments, c)
	return nil
}

const bodyPrefix = `<sub>reported by [reviewdog](https://github.com/haya14busa/reviewdog) :dog:</sub>`

func commentBody(c *Comment) string {
	tool := ""
	if c.ToolName != "" {
		tool = fmt.Sprintf("**[%s]** ", c.ToolName)
	}
	return tool + bodyPrefix + "\n" + c.Body
}

var githubAPIHost = "api.github.com"

// Flash posts comments which has not been posted yet.
func (g *GitHubPullRequest) Flash() error {
	g.muFlash.Lock()
	defer g.muFlash.Unlock()

	if err := g.setPostedComment(); err != nil {
		return err
	}
	// TODO(haya14busa,#58): remove host check when GitHub Enterprise supports
	// Pull Request API.
	if g.cli.BaseURL.Host == githubAPIHost {
		return g.postAsReviewComment()
	}
	return g.postCommentsForEach()
}

func (g *GitHubPullRequest) postAsReviewComment() error {
	comments := make([]*ReviewComment, 0, len(g.postComments))
	for _, c := range g.postComments {
		if g.postedcs.IsPosted(c) {
			continue
		}
		cbody := commentBody(c)
		comments = append(comments, &ReviewComment{
			Path:     &c.Path,
			Position: &c.LnumDiff,
			Body:     &cbody,
		})
	}

	if len(comments) == 0 {
		return nil
	}

	// TODO(haya14busa): it might be useful to report overview results by "body"
	// field.
	event := "COMMENT"
	review := &Review{Event: &event, Comments: comments}

	_, _, err := g.CreateReview(g.owner, g.repo, g.pr, review)
	return err
}

func (g *GitHubPullRequest) postCommentsForEach() error {
	var eg errgroup.Group
	for _, c := range g.postComments {
		comment := c
		if g.postedcs.IsPosted(comment) {
			continue
		}
		eg.Go(func() error {
			body := commentBody(comment)
			prcomment := &github.PullRequestComment{
				CommitID: &g.sha,
				Body:     &body,
				Path:     &comment.Path,
				Position: &comment.LnumDiff,
			}
			_, _, err := g.cli.PullRequests.CreateComment(g.owner, g.repo, g.pr, prcomment)
			return err
		})
	}
	return eg.Wait()
}

func (g *GitHubPullRequest) setPostedComment() error {
	g.postedcs = make(postedcomments)
	cs, err := g.comment()
	if err != nil {
		return err
	}
	for _, c := range cs {
		if c.Position == nil || c.Path == nil || c.Body == nil {
			// skip resolved comments. Or comments which do not have "path" nor
			// "body".
			continue
		}
		path := *c.Path
		pos := *c.Position
		body := *c.Body
		if _, ok := g.postedcs[path]; !ok {
			g.postedcs[path] = make(map[int][]string)
		}
		if _, ok := g.postedcs[path][pos]; !ok {
			g.postedcs[path][pos] = make([]string, 0)
		}
		g.postedcs[path][pos] = append(g.postedcs[path][pos], body)
	}
	return nil
}

// Diff returns a diff of PullRequest. It runs `git diff` locally instead of
// diff_url of GitHub Pull Request because diff of diff_url is not suited for
// comment API in a sense that diff of diff_url is equivalent to
// `git diff --no-renames`, we want diff which is equivalent to
// `git diff --find-renames`.
func (g *GitHubPullRequest) Diff() ([]byte, error) {
	pr, _, err := g.cli.PullRequests.Get(g.owner, g.repo, g.pr)
	if err != nil {
		return nil, err
	}
	return exec.Command("git", "diff", "--find-renames", *pr.Base.SHA, g.sha).Output()
}

// Strip returns 1 as a strip of git diff.
func (g *GitHubPullRequest) Strip() int {
	return 1
}

func (g *GitHubPullRequest) comment() ([]*github.PullRequestComment, error) {
	comments, _, err := g.cli.PullRequests.ListComments(g.owner, g.repo, g.pr, nil)
	if err != nil {
		return nil, err
	}
	return comments, nil
}

// ---
// GitHub PullRequest Review API Implementation
// ref: https://github.com/google/go-github/issues/495

const (
	mediaTypePullRequestReview = "application/vnd.github.black-cat-preview+json"
)

// Review represents a pull request review.
type Review struct {
	Body     *string          `json:"body,omitempty"`
	Event    *string          `json:"event,omitempty"`
	Comments []*ReviewComment `json:"comments,omitempty"`
}

// ReviewComment represents draft review comments.
type ReviewComment struct {
	Path     *string `json:"path,omitempty"`
	Position *int    `json:"position,omitempty"`
	Body     *string `json:"body,omitempty"`
}

// CreateReview creates a new review comment on the specified pull request.
//
// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#create-a-pull-request-review
func (g *GitHubPullRequest) CreateReview(owner, repo string, number int, review *Review) (*github.PullRequestReview, *github.Response, error) {
	u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number)

	req, err := g.cli.NewRequest("POST", u, review)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypePullRequestReview)

	r := new(github.PullRequestReview)
	resp, err := g.cli.Do(req, r)
	if err != nil {
		log.Printf("GitHub Review API error: %v", err)
		return nil, resp, err
	}
	return r, resp, err
}
<|endoftext|>


<commit_before>package goddos

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/pilu/traffic"
)

var (
	uriFragments map[string]bool
)

func init() {
	uriFragments = make(map[string]bool)
	uriFragments["manager/html"] = true
	uriFragments["POST_ip_port.php"] = true
	uriFragments["tmUnblock.cgi"] = true
	uriFragments["HNAP1"] = true
	uriFragments["phpMyAdmin/scripts/setup.php"] = true
	uriFragments["pma/scripts/setup.php"] = true
	uriFragments["myadmin/scripts/setup.php"] = true
	uriFragments["MyAdmin/scripts/setup.php"] = true
	uriFragments["vyvy/vyv/vy.php"] = true
	uriFragments["cgi-sys/php5"] = true
	uriFragments["cgi-bin/test-cgi"] = true
	uriFragments["cgi-bin/printenv"] = true
	uriFragments["cgi-bin/test.cgi"] = true
	uriFragments["cgi-bin/test.pl"] = true
	uriFragments["cgi-bin/test.sh"] = true
	uriFragments["cgi-bin/teste.pl"] = true
	uriFragments["cgi-bin/teste.cgi"] = true
	uriFragments["cgi-bin/teste.sh"] = true
	uriFragments["cgi-bin/print-env"] = true
	uriFragments["cgi-bin/print.pl"] = true
	uriFragments["cgi-bin/print.cgi"] = true
	uriFragments["cgi-bin/printenv.sh"] = true
	uriFragments["dpdp/dpd/dp.php"] = true
	uriFragments["upup/upu/up.php"] = true
	uriFragments["admin/fckeditor/editor/filemanager/browser/default/connectors/test.html"] = true
	uriFragments["web-console/ServerInfo.jsp"] = true
	uriFragments["vtigercrm"] = true
	uriFragments["operator/basic.shtml"] = true
	uriFragments["secure/ltx_conf.htm"] = true
	uriFragments["syslog.htm"] = true
}

func main() {

}

func CheckForDdosString(w traffic.ResponseWriter, r *traffic.Request) {
	for k, _ := range uriFragments {
		if strings.Contains(r.RequestURI, k) {
			fmt.Printf("Found %s", k)
			w.WriteHeader(http.StatusGatewayTimeout)
			w.WriteText("connection timed out")
		}
	}
}
<commit_msg>added debugging<commit_after>package goddos

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/pilu/traffic"
)

var (
	uriFragments map[string]bool
)

func init() {
	uriFragments = make(map[string]bool)
	uriFragments["manager/html"] = true
	uriFragments["POST_ip_port.php"] = true
	uriFragments["tmUnblock.cgi"] = true
	uriFragments["HNAP1"] = true
	uriFragments["phpMyAdmin/scripts/setup.php"] = true
	uriFragments["pma/scripts/setup.php"] = true
	uriFragments["myadmin/scripts/setup.php"] = true
	uriFragments["MyAdmin/scripts/setup.php"] = true
	uriFragments["vyvy/vyv/vy.php"] = true
	uriFragments["cgi-sys/php5"] = true
	uriFragments["cgi-bin/test-cgi"] = true
	uriFragments["cgi-bin/printenv"] = true
	uriFragments["cgi-bin/test.cgi"] = true
	uriFragments["cgi-bin/test.pl"] = true
	uriFragments["cgi-bin/test.sh"] = true
	uriFragments["cgi-bin/teste.pl"] = true
	uriFragments["cgi-bin/teste.cgi"] = true
	uriFragments["cgi-bin/teste.sh"] = true
	uriFragments["cgi-bin/print-env"] = true
	uriFragments["cgi-bin/print.pl"] = true
	uriFragments["cgi-bin/print.cgi"] = true
	uriFragments["cgi-bin/printenv.sh"] = true
	uriFragments["dpdp/dpd/dp.php"] = true
	uriFragments["upup/upu/up.php"] = true
	uriFragments["admin/fckeditor/editor/filemanager/browser/default/connectors/test.html"] = true
	uriFragments["web-console/ServerInfo.jsp"] = true
	uriFragments["vtigercrm"] = true
	uriFragments["operator/basic.shtml"] = true
	uriFragments["secure/ltx_conf.htm"] = true
	uriFragments["syslog.htm"] = true
}

func main() {

}

func CheckForDdosString(w traffic.ResponseWriter, r *traffic.Request) {
	for k, _ := range uriFragments {
		fmt.Printf("Searching for %s in %s", k, r.RequestURI)
		if strings.Contains(r.RequestURI, k) {
			fmt.Printf("Found %s", k)
			w.WriteHeader(http.StatusGatewayTimeout)
			w.WriteText("connection timed out")
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"math/rand"
	"time"
)

type Card struct {
	suit  string
	value int
}

type Deck struct {
	cards [52]Card
}

var Suits   []string = []string{"♤", "♥", "♢", "♧"}
var Values  []string=  []string{
	"Ace", "Two", "Three", "Four","Five",
	"Six", "Seven", "Eight", "Nine", "Ten",
	"Jack", "Queen", "King"}

func New() Deck {
	d := Deck{}
	var i int = 0
	for k, _ := range d.cards {
		var c = (i * 13) - k + 1
		if k % 13 == 0 {
			i++
		}
		d.cards[k] = Card{Suits[i - 1], c}
	}
	return d
}

func (d *Deck) Shuffle() {
	rand.Seed(time.Now().UnixNano())
	for i := range d.cards {
		j := rand.Intn(i + 1)
		d.cards[i], d.cards[j] = d.cards[j], d.cards[i]
	}
}

func (d *Deck) Print() {
	for _, c := range d.cards {
		fmt.Printf("%s\n", c.Name())
	}
}

func (c *Card) Name() string {
	return fmt.Sprintf("%s (%d) %s", Values[c.value - 1], c.value,  c.suit)
}

func main() {
	d := New()
	d.Shuffle()
	d.Print()
}
<commit_msg>Go fmt ;)<commit_after>package main

import (
	"fmt"
	"math/rand"
	"time"
)

type Card struct {
	suit  string
	value int
}

type Deck struct {
	cards [52]Card
}

var Suits []string = []string{"♤", "♥", "♢", "♧"}
var Values []string = []string{
	"Ace", "Two", "Three", "Four", "Five",
	"Six", "Seven", "Eight", "Nine", "Ten",
	"Jack", "Queen", "King"}

func New() Deck {
	d := Deck{}
	var i int = 0
	for k, _ := range d.cards {
		var c = (i * 13) - k + 1
		if k%13 == 0 {
			i++
		}
		d.cards[k] = Card{Suits[i-1], c}
	}
	return d
}

func (d *Deck) Shuffle() {
	rand.Seed(time.Now().UnixNano())
	for i := range d.cards {
		j := rand.Intn(i + 1)
		d.cards[i], d.cards[j] = d.cards[j], d.cards[i]
	}
}

func (d *Deck) Print() {
	for _, c := range d.cards {
		fmt.Printf("%s\n", c.Name())
	}
}

func (c *Card) Name() string {
	return fmt.Sprintf("%s (%d) %s", Values[c.value-1], c.value, c.suit)
}

func main() {
	d := New()
	d.Shuffle()
	d.Print()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/gophergala/goffee/tor"

	"flag"

	"github.com/goffee/web"
)

var webMode bool

func init() {
	flag.BoolVar(&webMode, "webmode", false, "Run goffee in webmode")
	flag.Parse()
}

func main() {
	if webMode {
		web.StartServer()
	}
	fmt.Println("Hello, Gopher Gala!")
	body, _ := tor.TorGet("http://www.kiskolabs.com")
        fmt.Printf("Result was '%s'\n", string(body))
}
<commit_msg>Fix web path<commit_after>package main

import (
	"fmt"
	"github.com/gophergala/goffee/tor"

	"flag"

	"github.com/gophergala/goffee/web"
)

var webMode bool

func init() {
	flag.BoolVar(&webMode, "webmode", false, "Run goffee in webmode")
	flag.Parse()
}

func main() {
	if webMode {
		web.StartServer()
	}
	fmt.Println("Hello, Gopher Gala!")
	body, _ := tor.TorGet("http://www.kiskolabs.com")
        fmt.Printf("Result was '%s'\n", string(body))
}
<|endoftext|>


<commit_before>package golock

import (
	"os"
	"sync"
	"syscall"
	"time"
)

//Alarm will raise a SIGALRM if not stopped in time
type Alarm struct {
	t       time.Duration
	abort   chan struct{}
	p       *os.Process
	started *sync.WaitGroup
}

func NewAlarm(t time.Duration) (a Alarm, err error) {
	a.p, err = getMyProcess()
	if err != nil {
		return a, err
	}
	a.abort = make(chan struct{}, 1)
	a.started = &sync.WaitGroup{}
	return a, nil
}

//GetMyProcess through os.Getpid
func getMyProcess() (p *os.Process, err error) {
	p, err = os.FindProcess(os.Getpid())
	if err != nil {
		return nil, err
	}
	return p, nil
}

//AlarmAfter a duration or abort on a channel input
func (a Alarm) alarmAfter() {
	timer := time.NewTimer(a.t)
	defer timer.Stop()
	a.started.Done()
	for {
		select {
		case <-timer.C:
			a.p.Signal(syscall.SIGALRM)
		case <-a.abort:
			return
		}
	}
	return
}

func (a Alarm) Start() {
	a.started.Add(1)
	go a.alarmAfter()
	a.started.Wait()
}

func (a Alarm) Stop() {
	a.abort <- struct{}{}
}

func WriteLockWithTimeout(fd *os.File, t time.Duration) (err error) {
	a, err := NewAlarm(t)
	if err != nil {
		return err
	}
	flock := syscall.Flock_t{
		Type: syscall.F_WRLCK,
	}
	a.Start()
	err = syscall.FcntlFlock(fd.Fd(), syscall.F_SETLKW, &flock)
	a.Stop()
	return err

}
func WriteUnLockWithTimeout(fd *os.File, t time.Duration) (err error) {
	a, err := NewAlarm(t)
	if err != nil {
		return err
	}
	flock := syscall.Flock_t{
		Type: syscall.F_UNLCK,
	}
	a.Start()
	err = syscall.FcntlFlock(fd.Fd(), syscall.F_SETLKW, &flock)
	a.Stop()
	return err

}
<commit_msg>godocs<commit_after>package golock

import (
	"os"
	"sync"
	"syscall"
	"time"
)

//Alarm will raise a SIGALRM if not stopped in time
type Alarm struct {
	t       time.Duration
	abort   chan struct{}
	p       *os.Process
	started *sync.WaitGroup
}

//NewAlarm creates an alarm for the given duration
func NewAlarm(t time.Duration) (a Alarm, err error) {
	a.p, err = getMyProcess()
	if err != nil {
		return a, err
	}
	a.abort = make(chan struct{}, 1)
	a.started = &sync.WaitGroup{}
	return a, nil
}

//getMyProcess through os.Getpid
func getMyProcess() (p *os.Process, err error) {
	p, err = os.FindProcess(os.Getpid())
	if err != nil {
		return nil, err
	}
	return p, nil
}

//alarmAfter a duration or abort on a channel input
func (a Alarm) alarmAfter() {
	timer := time.NewTimer(a.t)
	defer timer.Stop()
	a.started.Done()
	for {
		select {
		case <-timer.C:
			a.p.Signal(syscall.SIGALRM)
		case <-a.abort:
			return
		}
	}
	return
}

//Start the countdown till an alarm is raised
func (a Alarm) Start() {
	a.started.Add(1)
	go a.alarmAfter()
	a.started.Wait()
}

//Stop the countdown for the alarm
func (a Alarm) Stop() {
	a.abort <- struct{}{}
}

//WriteLockWithTimeout write lock fd but give up after t
func WriteLockWithTimeout(fd *os.File, t time.Duration) (err error) {
	a, err := NewAlarm(t)
	if err != nil {
		return err
	}
	flock := syscall.Flock_t{
		Type: syscall.F_WRLCK,
	}
	a.Start()
	err = syscall.FcntlFlock(fd.Fd(), syscall.F_SETLKW, &flock)
	a.Stop()
	return err

}

//WriteUnLockWithTimeout un-lock fd but give up after t
func WriteUnLockWithTimeout(fd *os.File, t time.Duration) (err error) {
	a, err := NewAlarm(t)
	if err != nil {
		return err
	}
	flock := syscall.Flock_t{
		Type: syscall.F_UNLCK,
	}
	a.Start()
	err = syscall.FcntlFlock(fd.Fd(), syscall.F_SETLKW, &flock)
	a.Stop()
	return err

}
<|endoftext|>


<commit_before>package main

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

	"github.com/pkg/errors"

	"github.com/jBugman/fun-lang/func-parse/parser"
)

func main() {
	filename := os.Args[1]
	source := readFile(filename)

	result, e := parser.Parse(source)
	if e != nil {
		fmt.Fprintf(os.Stderr, "%s:%d:%d: %s\n", filename, e.Pos().Line, e.Pos().Col, e)
		os.Exit(1)
	}

	output, err := json.MarshalIndent(result, "", "  ")
	if err != nil {
		fmt.Fprintln(os.Stderr, errors.Wrap(err, "marshal json"))
		os.Exit(1)
	}
	os.Stdout.Write(output)
}

func readFile(filename string) []byte {
	source, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Fprintln(os.Stderr, errors.Wrap(err, "read file"))
		os.Exit(1)
	}
	return source
}
<commit_msg>Reading stdin<commit_after>package main

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

	"github.com/pkg/errors"

	"github.com/jBugman/fun-lang/func-parse/parser"
)

func main() {
	source, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		fmt.Fprintln(os.Stderr, errors.Wrap(err, "reading input"))
		os.Exit(1)
	}

	result, e := parser.Parse(source)
	if e != nil {
		const filename = "<standard input>"
		fmt.Fprintf(os.Stderr, "%s:%d:%d: %s\n", filename, e.Pos().Line, e.Pos().Col, e)
		os.Exit(1)
	}

	output, err := json.MarshalIndent(result, "", "  ")
	if err != nil {
		fmt.Fprintln(os.Stderr, errors.Wrap(err, "marshal json"))
		os.Exit(1)
	}
	os.Stdout.Write(output)
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 fuseops contains implementations of the fuse.Op interface that may
// be returned by fuse.Connection.ReadOp. See documentation in that package for
// more.
package fuseops

import (
	"github.com/jacobsa/bazilfuse"
	"golang.org/x/net/context"
)

// Convert the supplied bazilfuse request struct to an Op, returning nil if it
// is unknown.
//
// This function is an implementation detail of the fuse package, and must not
// be called by anyone else.
func Convert(r bazilfuse.Request) (o Op) {
	var co *commonOp

	switch r.(type) {
	case *bazilfuse.InitRequest:
		to := &InitOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.LookupRequest:
		to := &LookUpInodeOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.GetattrRequest:
		to := &GetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.SetattrRequest:
		to := &SetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.MkdirRequest:
		to := &MkDirOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.CreateRequest:
		to := &CreateFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.RemoveRequest:
		//TODO

	case *bazilfuse.OpenRequest:
		//TODO

	case *bazilfuse.ReadRequest:
		//TODO

	case *bazilfuse.ReleaseRequest:
		//TODO

	case *bazilfuse.WriteRequest:
		to := &WriteFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.FsyncRequest:
		to := &SyncFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.FlushRequest:
		to := &FlushFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	default:
		return
	}

	co.init(r)
	return
}

// A helper for embedding common behavior.
type commonOp struct {
	ctx context.Context
	r   bazilfuse.Request
}

func (o *commonOp) init(r bazilfuse.Request) {
	o.ctx = context.Background()
	o.r = r
}

func (o *commonOp) Header() OpHeader {
	bh := o.r.Hdr()
	return OpHeader{
		Uid: bh.Uid,
		Gid: bh.Gid,
	}
}

func (o *commonOp) Context() context.Context {
	return o.ctx
}

func (o *commonOp) respondErr(err error) {
	if err != nil {
		panic("Expect non-nil here.")
	}

	o.r.RespondError(err)
}
<commit_msg>Filled in LookUpInodeOp.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 fuseops contains implementations of the fuse.Op interface that may
// be returned by fuse.Connection.ReadOp. See documentation in that package for
// more.
package fuseops

import (
	"github.com/jacobsa/bazilfuse"
	"golang.org/x/net/context"
)

// Convert the supplied bazilfuse request struct to an Op, returning nil if it
// is unknown.
//
// This function is an implementation detail of the fuse package, and must not
// be called by anyone else.
func Convert(r bazilfuse.Request) (o Op) {
	var co *commonOp

	switch typed := r.(type) {
	case *bazilfuse.InitRequest:
		to := &InitOp{}
		o = to
		co = &to.commonOp

	case *bazilfuse.LookupRequest:
		to := &LookUpInodeOp{
			Parent: InodeID(typed.Header.Node),
			Name:   typed.Name,
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.GetattrRequest:
		to := &GetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.SetattrRequest:
		to := &SetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.MkdirRequest:
		to := &MkDirOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.CreateRequest:
		to := &CreateFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.RemoveRequest:
		//TODO

	case *bazilfuse.OpenRequest:
		//TODO

	case *bazilfuse.ReadRequest:
		//TODO

	case *bazilfuse.ReleaseRequest:
		//TODO

	case *bazilfuse.WriteRequest:
		to := &WriteFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.FsyncRequest:
		to := &SyncFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.FlushRequest:
		to := &FlushFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	default:
		return
	}

	co.init(r)
	return
}

// A helper for embedding common behavior.
type commonOp struct {
	ctx context.Context
	r   bazilfuse.Request
}

func (o *commonOp) init(r bazilfuse.Request) {
	o.ctx = context.Background()
	o.r = r
}

func (o *commonOp) Header() OpHeader {
	bh := o.r.Hdr()
	return OpHeader{
		Uid: bh.Uid,
		Gid: bh.Gid,
	}
}

func (o *commonOp) Context() context.Context {
	return o.ctx
}

func (o *commonOp) respondErr(err error) {
	if err != nil {
		panic("Expect non-nil here.")
	}

	o.r.RespondError(err)
}
<|endoftext|>


<commit_before>/*
 * Minio Client (C) 2015 Minio, Inc.
 *
 * 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 main

import (
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"

	"github.com/minio/mc/pkg/console"

	. "gopkg.in/check.v1"
)

func (s *TestSuite) TestCopyURLType(c *C) {
	sourceURLs := []string{server.URL + "/bucket/object1"}
	targetURL := server.URL + "/bucket/test"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeA)

	sourceURLs = []string{server.URL + "/bucket/object1"}
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeB)

	sourceURLs = []string{server.URL + "/bucket/..."}
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeC)

	sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
	targetURL = server.URL + "/bucket/test"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeD)

	sourceURLs = []string{}
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)

	sourceURLs = nil
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)

	sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
	targetURL = ""
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
}

func (s *TestSuite) TestMirror(c *C) {
	/// filesystem
	source, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(source)

	target, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(target)

	for i := 0; i < 10; i++ {
		objectPath := filepath.Join(source, "object"+strconv.Itoa(i))
		data := "hello"
		dataLen := len(data)
		err := putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
		c.Assert(err, IsNil)
	}

	// reset back
	console.IsExited = false

	err = app.Run([]string{os.Args[0], "mirror", source, target})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, false)

	// reset back
	console.IsExited = false
}

func (s *TestSuite) TestCopy(c *C) {
	/// filesystem
	source, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(source)

	for i := 0; i < 10; i++ {
		objectPath := filepath.Join(source, "object"+strconv.Itoa(i))
		data := "hello"
		dataLen := len(data)
		err := putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
		c.Assert(err, IsNil)
	}

	// reset back
	console.IsExited = false

	target := filepath.Join(source, "random")
	defer os.RemoveAll(target)

	err = app.Run([]string{os.Args[0], "cp", filepath.Join(source, "..."), target})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, false)

	// reset back
	console.IsExited = false

	err = app.Run([]string{os.Args[0], "cp", filepath.Join(source, ".."), target})
	c.Assert(err, IsNil)
	// in case of invalid arguments both are set
	c.Assert(console.IsError, Equals, true)
	c.Assert(console.IsExited, Equals, true)

	// reset back
	console.IsError = false
	console.IsExited = false
}
<commit_msg>remove negetive testcase for cp as we don't handle it<commit_after>/*
 * Minio Client (C) 2015 Minio, Inc.
 *
 * 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 main

import (
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"

	"github.com/minio/mc/pkg/console"

	. "gopkg.in/check.v1"
)

func (s *TestSuite) TestCopyURLType(c *C) {
	sourceURLs := []string{server.URL + "/bucket/object1"}
	targetURL := server.URL + "/bucket/test"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeA)

	sourceURLs = []string{server.URL + "/bucket/object1"}
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeB)

	sourceURLs = []string{server.URL + "/bucket/..."}
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeC)

	sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
	targetURL = server.URL + "/bucket/test"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeD)

	sourceURLs = []string{}
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)

	sourceURLs = nil
	targetURL = server.URL + "/bucket"
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)

	sourceURLs = []string{server.URL + "/bucket/...", server.URL + "/bucket/..."}
	targetURL = ""
	c.Assert(guessCopyURLType(sourceURLs, targetURL), Equals, copyURLsTypeInvalid)
}

func (s *TestSuite) TestMirror(c *C) {
	/// filesystem
	source, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(source)

	target, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(target)

	for i := 0; i < 10; i++ {
		objectPath := filepath.Join(source, "object"+strconv.Itoa(i))
		data := "hello"
		dataLen := len(data)
		err := putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
		c.Assert(err, IsNil)
	}

	// reset back
	console.IsExited = false

	err = app.Run([]string{os.Args[0], "mirror", source, target})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, false)

	// reset back
	console.IsExited = false
}

func (s *TestSuite) TestCopy(c *C) {
	/// filesystem
	source, err := ioutil.TempDir(os.TempDir(), "cmd-")
	c.Assert(err, IsNil)
	defer os.RemoveAll(source)

	for i := 0; i < 10; i++ {
		objectPath := filepath.Join(source, "object"+strconv.Itoa(i))
		data := "hello"
		dataLen := len(data)
		err := putTarget(objectPath, int64(dataLen), bytes.NewReader([]byte(data)))
		c.Assert(err, IsNil)
	}

	// reset back
	console.IsExited = false

	target := filepath.Join(source, "random")
	defer os.RemoveAll(target)

	err = app.Run([]string{os.Args[0], "cp", filepath.Join(source, "..."), target})
	c.Assert(err, IsNil)
	c.Assert(console.IsExited, Equals, false)

	// reset back
	console.IsError = false
	console.IsExited = false
}
<|endoftext|>


<commit_before>package cpanel

import (
	"encoding/json"

	"github.com/letsencrypt-cpanel/cpanelgo"
)

const (
	ParkedStatusNotRedirected = "not redirected"
)

type DomainsDataDomain struct {
	Domain       string `json:"domain"`
	Ip           string `json:"ip"`
	DocumentRoot string `json:"documentroot"`
	User         string `json:"user"`
	ServerAlias  string `json:"serveralias"`
	ServerName   string `json:"servername"`
}

type DomainsDataApiResponse struct {
	cpanelgo.BaseUAPIResponse
	Data struct {
		MainDomain    DomainsDataDomain   `json:"main_domain"`
		AddonDomains  []DomainsDataDomain `json:"addon_domains"`
		ParkedDomains []string            `json:"parked_domains"`
		Sub_Domains   []json.RawMessage   `json:"sub_domains"`
		Subdomains    []DomainsDataDomain `json:"-"`
	} `json:"data"`
}

func (dd DomainsDataApiResponse) DataList() []DomainsDataDomain {
	doms := append(dd.Data.AddonDomains, dd.Data.MainDomain)
	doms = append(doms, dd.Data.Subdomains...)
	return doms
}

func (r DomainsDataApiResponse) DomainList() []string {
	out := []string{}
	out = append(out, r.Data.MainDomain.Domain)
	out = append(out, r.Data.ParkedDomains...)
	for _, v := range r.Data.AddonDomains {
		out = append(out, v.Domain)
	}
	for _, v := range r.Data.Subdomains {
		out = append(out, v.Domain)
	}
	return out
}

func (c CpanelApi) DomainsData() (DomainsDataApiResponse, error) {
	var out DomainsDataApiResponse

	err := c.Gateway.UAPI("DomainInfo", "domains_data", cpanelgo.Args{
		"format": "hash",
	}, &out)
	if err == nil {
		err = out.Error()
	}
	if err == nil {
		out.Data.Subdomains = []DomainsDataDomain{}
		for _, v := range out.Data.Sub_Domains {
			dec := DomainsDataDomain{}
			if err := json.Unmarshal(v, &dec); err == nil {
				out.Data.Subdomains = append(out.Data.Subdomains, dec)
			}
		}

	}
	return out, err
}

type SingleDomainDataApiResponse struct {
	Status int `json:"status"`
	Data   struct {
		Domain       string `json:"domain"`
		DocumentRoot string `json:"documentroot"`
	} `json:"data"`
}

func (c CpanelApi) SingleDomainData(domain string) (SingleDomainDataApiResponse, error) {
	var out SingleDomainDataApiResponse

	err := c.Gateway.UAPI("DomainInfo", "single_domain_data", cpanelgo.Args{
		"domain": domain,
	}, &out)

	return out, err
}

type ParkedDomain struct {
	Domain string `json:"domain"`
	Status string `json:"status"`
	Dir    string `json:"dir"`
}

type ListParkedDomainsApiResponse struct {
	cpanelgo.BaseAPI2Response
	Data []ParkedDomain `json:"data"`
}

func (c CpanelApi) ListParkedDomains() (ListParkedDomainsApiResponse, error) {
	var out ListParkedDomainsApiResponse

	err := c.Gateway.API2("Park", "listparkeddomains", cpanelgo.Args{}, &out)

	if err == nil {
		err = out.Error()
	}

	return out, err
}
<commit_msg>Added API WebVhosts::list_domains<commit_after>package cpanel

import (
	"encoding/json"

	"github.com/letsencrypt-cpanel/cpanelgo"
)

const (
	ParkedStatusNotRedirected = "not redirected"
)

type DomainsDataDomain struct {
	Domain       string `json:"domain"`
	Ip           string `json:"ip"`
	DocumentRoot string `json:"documentroot"`
	User         string `json:"user"`
	ServerAlias  string `json:"serveralias"`
	ServerName   string `json:"servername"`
}

type DomainsDataApiResponse struct {
	cpanelgo.BaseUAPIResponse
	Data struct {
		MainDomain    DomainsDataDomain   `json:"main_domain"`
		AddonDomains  []DomainsDataDomain `json:"addon_domains"`
		ParkedDomains []string            `json:"parked_domains"`
		Sub_Domains   []json.RawMessage   `json:"sub_domains"`
		Subdomains    []DomainsDataDomain `json:"-"`
	} `json:"data"`
}

func (dd DomainsDataApiResponse) DataList() []DomainsDataDomain {
	doms := append(dd.Data.AddonDomains, dd.Data.MainDomain)
	doms = append(doms, dd.Data.Subdomains...)
	return doms
}

func (r DomainsDataApiResponse) DomainList() []string {
	out := []string{}
	out = append(out, r.Data.MainDomain.Domain)
	out = append(out, r.Data.ParkedDomains...)
	for _, v := range r.Data.AddonDomains {
		out = append(out, v.Domain)
	}
	for _, v := range r.Data.Subdomains {
		out = append(out, v.Domain)
	}
	return out
}

func (c CpanelApi) DomainsData() (DomainsDataApiResponse, error) {
	var out DomainsDataApiResponse

	err := c.Gateway.UAPI("DomainInfo", "domains_data", cpanelgo.Args{
		"format": "hash",
	}, &out)
	if err == nil {
		err = out.Error()
	}
	if err == nil {
		out.Data.Subdomains = []DomainsDataDomain{}
		for _, v := range out.Data.Sub_Domains {
			dec := DomainsDataDomain{}
			if err := json.Unmarshal(v, &dec); err == nil {
				out.Data.Subdomains = append(out.Data.Subdomains, dec)
			}
		}

	}
	return out, err
}

type SingleDomainDataApiResponse struct {
	Status int `json:"status"`
	Data   struct {
		Domain       string `json:"domain"`
		DocumentRoot string `json:"documentroot"`
	} `json:"data"`
}

func (c CpanelApi) SingleDomainData(domain string) (SingleDomainDataApiResponse, error) {
	var out SingleDomainDataApiResponse

	err := c.Gateway.UAPI("DomainInfo", "single_domain_data", cpanelgo.Args{
		"domain": domain,
	}, &out)

	return out, err
}

type ParkedDomain struct {
	Domain string `json:"domain"`
	Status string `json:"status"`
	Dir    string `json:"dir"`
}

type ListParkedDomainsApiResponse struct {
	cpanelgo.BaseAPI2Response
	Data []ParkedDomain `json:"data"`
}

func (c CpanelApi) ListParkedDomains() (ListParkedDomainsApiResponse, error) {
	var out ListParkedDomainsApiResponse

	err := c.Gateway.API2("Park", "listparkeddomains", cpanelgo.Args{}, &out)

	if err == nil {
		err = out.Error()
	}

	return out, err
}

type WebVhostsListDomainsApiResponse struct {
	cpanelgo.BaseUAPIResponse
	Data []VhostEntry `json:"data"`
}

type VhostEntry struct {
	Domain          string   `json:"domain"`
	VhostName       string   `json:"vhost_name"`
	VhostIsSsl      int      `json:"vhost_is_ssl"`
	ProxySubdomains []string `json:"proxy_subdomains"`
}

func (c CpanelApi) WebVhostsListDomains() (WebVhostsListDomainsApiResponse, error) {
	var out WebVhostsListDomainsApiResponse

	err := c.Gateway.UAPI("WebVhosts", "list_domains", cpanelgo.Args{}, &out)

	if err == nil {
		err = out.Error()
	}

	return out, err
}
<|endoftext|>