<commit_before>package main

import (
	"github.com/asdine/storm"
	"github.com/labstack/echo"
	"github.com/labstack/echo/engine/fasthttp"
	"github.com/labstack/echo/middleware"
	"log"
	"net/http"
)

type (
	Mood struct {
		Value int `json:"mood"`
	}

	Subscribers struct {
		Users []Subscriber `json:"users"`
	}

	Subscription struct {
		Email string `json:"email"`
	}
)

func main() {
	database := createDatabase()
	defer database.Close()

	createCronJob(database, triggerMail(database))

	server := initServer(database)
	server.Run(fasthttp.New(":8081"))

	log.Println("Started server on port 8081.")
}

func initServer(database *storm.DB) (server *echo.Echo) {
	server = echo.New()

	server.Use(middleware.Logger())
	server.Get("/subscribers", getSubscribers(database))
	server.Get("/subscribers/:uuid", getSubscribersByUuid(database))
	server.Post("/subscribers", postSubscriber(database))
	server.Get("/moods/:key", getDailyMoods())
	server.Post("/moods/:key", postDailyMoods(database))

	return server
}

func getDailyMoods() echo.HandlerFunc {
	return (func(context echo.Context) error {
		key := context.Param("key")

		htmlContent := `

Select your mood

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="0">
	<input type="submit" value="Very unhappy">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="1">
	<input type="submit" value="Unhappy">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="2">
	<input type="submit" value="Neutral">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="3">
	<input type="submit" value="Happy">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="4">
	<input type="submit" value="Very happy">
	</form>

	`
		return context.HTML(http.StatusOK, htmlContent)

	})
}

func postDailyMoods(database *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		key := context.Param("key")
		mood := context.FormValue("mood")

		if feedbackIdentifier := getFeedbackIdentifier(database, key); feedbackIdentifier != nil {
			if databaseError := updateDailyMoods(database, feedbackIdentifier.DateString, mood); databaseError != nil {
				return context.String(http.StatusInternalServerError, databaseError.Error())
			} else {
				return context.String(http.StatusCreated, "Thank you!")
			}
		} else {
			return context.String(http.StatusNotFound, "Mood with key '"+key+"' not found!")
		}

		return nil
	})
}

func getSubscribers(database *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		subscriptions, databaseError := getSubscriptions(database)

		if databaseError != nil {
			return context.String(http.StatusInternalServerError, databaseError.Error())
		} else {
			return context.JSON(http.StatusOK, subscriptions)
		}

		return nil
	})
}

func getSubscribersByUuid(database *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		uuid := context.Param("uuid")
		subscriber, databaseError := getSubscriptionByUuid(database, uuid)

		if databaseError != nil {
			return context.String(http.StatusInternalServerError, databaseError.Error())
		} else {
			if subscriber != nil {
				return context.JSON(http.StatusOK, subscriber)
			} else {
				return context.String(http.StatusNotFound, "User with uuid '"+uuid+"' not found!")
			}
		}

		return nil
	})
}

func postSubscriber(db *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		subscription := new(Subscription)
		if jsonError := context.Bind(subscription); jsonError != nil {
			return context.String(http.StatusInternalServerError, jsonError.Error())
		} else {
			subscriber, dbError := saveSubscription(db, subscription)

			log.Printf("Saved user: %s\n", subscriber)

			if dbError != nil {
				return context.String(http.StatusInternalServerError, dbError.Error())
			} else {
				return context.JSON(http.StatusCreated, subscriber)
			}
		}

		return nil
	})
}
<commit_msg>refactoring<commit_after>package main

import (
	"github.com/asdine/storm"
	"github.com/labstack/echo"
	"github.com/labstack/echo/engine/fasthttp"
	"github.com/labstack/echo/middleware"
	"log"
	"net/http"
)

type (
	Mood struct {
		Value int `json:"mood"`
	}

	Subscribers struct {
		Users []Subscriber `json:"users"`
	}

	Subscription struct {
		Email string `json:"email"`
	}
)

func main() {
	database := createDatabase()
	defer database.Close()

	createCronJob(database, triggerMail(database))

	server := initServer(database)
	server.Run(fasthttp.New(":8081"))

	log.Println("Started server on port 8081.")
}

func initServer(database *storm.DB) (server *echo.Echo) {
	server = echo.New()

	server.Use(middleware.Logger())
	server.Get("/subscribers", getSubscribers(database))
	server.Get("/subscribers/:uuid", getSubscribersByUuid(database))
	server.Post("/subscribers", postSubscriber(database))
	server.Get("/moods/:key", getDailyMoods())
	server.Post("/moods/:key", postDailyMoods(database))

	return server
}

func getDailyMoods() echo.HandlerFunc {
	return (func(context echo.Context) error {
		key := context.Param("key")

		htmlContent := `

Select your mood

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="0">
	<input type="submit" value="Very unhappy">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="1">
	<input type="submit" value="Unhappy">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="2">
	<input type="submit" value="Neutral">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="3">
	<input type="submit" value="Happy">
	</form>

	<form method="POST" action="http://aulendorf:8081/moods/` + key + `">
	<input type="hidden" name="mood" value="4">
	<input type="submit" value="Very happy">
	</form>

	`
		return context.HTML(http.StatusOK, htmlContent)

	})
}

func postDailyMoods(database *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		key := context.Param("key")
		mood := context.FormValue("mood")

		if feedbackIdentifier := getFeedbackIdentifier(database, key); feedbackIdentifier != nil {
			if databaseError := updateDailyMoods(database, feedbackIdentifier.DateString, mood); databaseError != nil {
				return databaseError
			} else {
				return context.String(http.StatusCreated, "Thank you!")
			}
		} else {
			return context.String(http.StatusNotFound, "Mood with key '"+key+"' not found!")
		}

		return nil
	})
}

func getSubscribers(database *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		subscriptions, databaseError := getSubscriptions(database)

		if databaseError != nil {
			return databaseError
		} else {
			return context.JSON(http.StatusOK, subscriptions)
		}

		return nil
	})
}

func getSubscribersByUuid(database *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		uuid := context.Param("uuid")
		subscriber, databaseError := getSubscriptionByUuid(database, uuid)

		if databaseError != nil {
			return databaseError
		} else {
			if subscriber != nil {
				return context.JSON(http.StatusOK, subscriber)
			} else {
				return context.String(http.StatusNotFound, "User with uuid '"+uuid+"' not found!")
			}
		}

		return nil
	})
}

func postSubscriber(db *storm.DB) echo.HandlerFunc {
	return (func(context echo.Context) error {
		subscription := new(Subscription)
		if jsonError := context.Bind(subscription); jsonError != nil {
			return jsonError
		} else {
			subscriber, databaseError := saveSubscription(db, subscription)

			log.Printf("Saved user: %s\n", subscriber)

			if databaseError != nil {
				return databaseError.Error()
			} else {
				return context.JSON(http.StatusCreated, subscriber)
			}
		}

		return nil
	})
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

type testCase struct {
	sites      []site
	maxWidth   int
	totalCount int
}

func getTestSites() []site {
	sites := []site{
		site{
			Base:        "http://test.webdav.org",
			BasicAuth:   []string{"auth-basic"},
			NoBasicAuth: []string{"dav", ""},
		},
		site{
			Base:        "https://httpbin.org/",
			BasicAuth:   []string{"basic-auth/:user/:passwd"},
			NoBasicAuth: []string{"html", ""},
		},
	}
	return sites
}

func TestCheckSuccess(t *testing.T) {
	sites := getTestSites()
	for _, site := range sites {
		for _, ep := range site.endpoints {
			ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if ep.BaShouldBe {
					w.WriteHeader(http.StatusUnauthorized)
				} else {
					w.WriteHeader(http.StatusOK)
				}
			}))
			response, _ := http.Get(ts.URL)
			ep.Success, ep.BaEnabled = checkSuccess(response, ep.BaShouldBe)
			if !ep.Success {
				t.Error("No success! Expected success!")
			}
			if ep.BaEnabled != ep.BaShouldBe {
				t.Error("BA unexpected state!")
			}
			ts.Close()
		}
		for _, ep := range site.endpoints {
			response, _ := http.Get(ep.URL)
			ep.Success, ep.BaEnabled = checkSuccess(response, ep.BaShouldBe)
			if !ep.Success {
				t.Logf("Tested URL: %s Response BA: %t Expected BA: %t", ep.URL, response.StatusCode == 401, ep.BaShouldBe)
				t.Error("No success! Expected success!")
			}
			if ep.BaEnabled != ep.BaShouldBe {
				t.Error("BA unexpected state!")
			}
		}

	}
}

func TestCheckSuccessFail(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "testing yay")
	}))
	defer ts.Close()
	baShouldBe := true
	response, _ := http.Get(ts.URL)
	success, baEnabled := checkSuccess(response, baShouldBe)
	if success {
		t.Error("Success?! Expected failure!")
	}
	if baEnabled != false {
		t.Error("BA enabled when it shouldn't!")
	}
}

func TestCheckURL(t *testing.T) {
	sites := getTestSites()
	for _, site := range sites {
		for index := range site.endpoints {
			checkURL(&site.endpoints[index])
			if !site.endpoints[index].Success {
				t.Errorf("Expected 'success' to be true, got false")
			}
		}
	}
}

func TestGetMaxWidth(t *testing.T) {
	tc := testCase{
		sites:    getTestSites(),
		maxWidth: 66,
	}
	populateURLConfig(tc.sites)
	got := getMaxWidth(tc.sites)
	if got != tc.maxWidth {
		t.Errorf("Incorrect maxWidth %d, wanted %d", got, tc.maxWidth)
	}
}

func TestNumberOfTotalURL(t *testing.T) {
	tc := testCase{
		sites:      getTestSites(),
		totalCount: 6,
	}
	populateURLConfig(tc.sites)
	got := numberOfTotalURLs(tc.sites)
	if got != tc.totalCount {
		t.Errorf("Incorrect total URL count %d, wanted %d", got, tc.totalCount)
	}
}
<commit_msg>Update tests<commit_after>package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

type testCase struct {
	sites      []site
	maxWidth   int
	totalCount int
}

func getTestSites() []site {
	sites := []site{
		site{
			Base:        "http://test.webdav.org",
			BasicAuth:   []string{"auth-basic"},
			NoBasicAuth: []string{"dav", ""},
		},
		site{
			Base:        "https://httpbin.org/",
			BasicAuth:   []string{"basic-auth/:user/:passwd"},
			NoBasicAuth: []string{"html", ""},
		},
	}
	return sites
}

func TestCheckSuccess(t *testing.T) {
	sites := getTestSites()
	for _, site := range sites {
		for _, ep := range site.endpoints {
			ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if ep.BaShouldBe {
					w.WriteHeader(http.StatusUnauthorized)
				} else {
					w.WriteHeader(http.StatusOK)
				}
			}))
			response, _ := http.Get(ts.URL)
			ep.Success, ep.BaEnabled, ep.Unknown = checkSuccess(response, ep.BaShouldBe)
			if !ep.Success {
				t.Error("No success! Expected success!")
			}
			if ep.BaEnabled != ep.BaShouldBe {
				t.Error("BA unexpected state!")
			}
			ts.Close()
		}
		for _, ep := range site.endpoints {
			response, _ := http.Get(ep.URL)
			ep.Success, ep.BaEnabled, ep.Unknown = checkSuccess(response, ep.BaShouldBe)
			if !ep.Success {
				t.Logf("Tested URL: %s Response BA: %t Expected BA: %t", ep.URL, response.StatusCode == 401, ep.BaShouldBe)
				t.Error("No success! Expected success!")
			}
			if ep.BaEnabled != ep.BaShouldBe {
				t.Error("BA unexpected state!")
			}
		}

	}
}

func TestCheckSuccessFail(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "testing yay")
	}))
	defer ts.Close()
	baShouldBe := true
	response, _ := http.Get(ts.URL)
	success, baEnabled, _ := checkSuccess(response, baShouldBe)
	if success {
		t.Error("Success?! Expected failure!")
	}
	if baEnabled != false {
		t.Error("BA enabled when it shouldn't!")
	}
}

func TestCheckURL(t *testing.T) {
	sites := getTestSites()
	for _, site := range sites {
		for index := range site.endpoints {
			checkURL(&site.endpoints[index])
			if !site.endpoints[index].Success {
				t.Errorf("Expected 'success' to be true, got false")
			}
		}
	}
}

func TestGetMaxWidth(t *testing.T) {
	tc := testCase{
		sites:    getTestSites(),
		maxWidth: 66,
	}
	populateURLConfig(tc.sites)
	got := getMaxWidth(tc.sites)
	if got != tc.maxWidth {
		t.Errorf("Incorrect maxWidth %d, wanted %d", got, tc.maxWidth)
	}
}

func TestNumberOfTotalURL(t *testing.T) {
	tc := testCase{
		sites:      getTestSites(),
		totalCount: 6,
	}
	populateURLConfig(tc.sites)
	got := numberOfTotalURLs(tc.sites)
	if got != tc.totalCount {
		t.Errorf("Incorrect total URL count %d, wanted %d", got, tc.totalCount)
	}
}
<|endoftext|>


<commit_before>// Copyright © 2015 - Rémy MATHIEU

package db

import (
	"database/sql"
	"time"

	_ "github.com/lib/pq"
)

const (
	SENSOR_VALUE_FIELDS = `
		"sensor_value"."sensor_id",
		"sensor_value"."type",
		"sensor_value"."time",
		"sensor_value"."value"
	`
)

type SensorValueDAO struct {
	db *sql.DB

	findLast  *sql.Stmt
	findRange *sql.Stmt
	insert    *sql.Stmt
}

type SensorValue struct {
	SensorId string
	Type     string
	Time     time.Time
	Value    float64
	Ip       string
}

func NewSensorValueDAO(db *sql.DB) (*SensorValueDAO, error) {
	dao := &SensorValueDAO{
		db: db,
	}
	err := dao.initStmt()
	return dao, err
}

func (d *SensorValueDAO) initStmt() error {
	var err error

	if d.findRange, err = d.db.Prepare(`
		SELECT ` +
		SENSOR_VALUE_FIELDS + `
		FROM "sensor_value"
		WHERE
			"sensor_value"."time" >= $1
			AND
			"sensor_value"."time" <= $2
			AND
			"sensor_value"."type" = $3
		ORDER BY "sensor_value"."time"
	`); err != nil {
		return err
	}

	if d.findLast, err = d.db.Prepare(`
		SELECT ` +
		SENSOR_VALUE_FIELDS + `
		FROM "sensor_value"
		WHERE
			"sensor_value"."sensor_id" = $1
			AND
			"sensor_value"."type" = $2
		ORDER BY "sensor_value"."time" DESC
		LIMIT 1
	`); err != nil {
		return err
	}

	if d.insert, err = d.db.Prepare(`
		INSERT INTO
		"sensor_value"
		(` + insertFields("sensor_value", SENSOR_VALUE_FIELDS) + `)
		VALUES
		($1, $2, $3, $4, $5)
	`); err != nil {
		return err
	}

	return nil
}

func (d *SensorValueDAO) Insert(sensorValue SensorValue) (sql.Result, error) {
	return d.insert.Exec(
		sensorValue.SensorId,
		sensorValue.Type,
		sensorValue.Time,
		sensorValue.Value,
		sensorValue.Ip,
	)
}

func (d *SensorValueDAO) FindRange(start, end time.Time, typ string) ([]SensorValue, error) {
	return readValues(d.findRange.Query(start, end, typ))
}

func (d *SensorValueDAO) FindLast(sensorId string, typ string) (SensorValue, error) {
	return ReadSensorValueAndReturn(d.findLast.Query(sensorId, typ))
}

func ReadSensorValueAndReturn(rows *sql.Rows, err error) (SensorValue, error) {
	var rv SensorValue

	if err != nil {
		return rv, err
	}

	if rows == nil {
		return rv, nil
	}

	defer rows.Close()

	if rows.Next() {
		rv, err = sensorValueFromRow(rows)
	}

	return rv, err
}

func readValues(rows *sql.Rows, err error) ([]SensorValue, error) {
	rv := make([]SensorValue, 0)
	if rows == nil {
		return rv, nil
	}

	defer rows.Close()

	for rows.Next() {
		var v SensorValue
		var err error
		if v, err = sensorValueFromRow(rows); err != nil {
			return rv, err
		}
		rv = append(rv, v)
	}

	return rv, nil
}

// sensorValueFromRow reads an parking model from the current row.
func sensorValueFromRow(rows *sql.Rows) (SensorValue, error) {
	var sensorId,
		typ string
	var t time.Time
	var value float64

	err := rows.Scan(
		&sensorId,
		&typ,
		&t,
		&value)

	return SensorValue{
		SensorId: sensorId,
		Type:     typ,
		Time:     t,
		Value:    value,
	}, err
}
<commit_msg>Missing IP fields on INSERT.<commit_after>// Copyright © 2015 - Rémy MATHIEU

package db

import (
	"database/sql"
	"time"

	_ "github.com/lib/pq"
)

const (
	SENSOR_VALUE_FIELDS = `
		"sensor_value"."sensor_id",
		"sensor_value"."type",
		"sensor_value"."time",
		"sensor_value"."value",
		"sensor_value"."ip"
	`
)

type SensorValueDAO struct {
	db *sql.DB

	findLast  *sql.Stmt
	findRange *sql.Stmt
	insert    *sql.Stmt
}

type SensorValue struct {
	SensorId string
	Type     string
	Time     time.Time
	Value    float64
	Ip       string
}

func NewSensorValueDAO(db *sql.DB) (*SensorValueDAO, error) {
	dao := &SensorValueDAO{
		db: db,
	}
	err := dao.initStmt()
	return dao, err
}

func (d *SensorValueDAO) initStmt() error {
	var err error

	if d.findRange, err = d.db.Prepare(`
		SELECT ` +
		SENSOR_VALUE_FIELDS + `
		FROM "sensor_value"
		WHERE
			"sensor_value"."time" >= $1
			AND
			"sensor_value"."time" <= $2
			AND
			"sensor_value"."type" = $3
		ORDER BY "sensor_value"."time"
	`); err != nil {
		return err
	}

	if d.findLast, err = d.db.Prepare(`
		SELECT ` +
		SENSOR_VALUE_FIELDS + `
		FROM "sensor_value"
		WHERE
			"sensor_value"."sensor_id" = $1
			AND
			"sensor_value"."type" = $2
		ORDER BY "sensor_value"."time" DESC
		LIMIT 1
	`); err != nil {
		return err
	}

	if d.insert, err = d.db.Prepare(`
		INSERT INTO
		"sensor_value"
		(` + insertFields("sensor_value", SENSOR_VALUE_FIELDS) + `)
		VALUES
		($1, $2, $3, $4, $5)
	`); err != nil {
		return err
	}

	return nil
}

func (d *SensorValueDAO) Insert(sensorValue SensorValue) (sql.Result, error) {
	return d.insert.Exec(
		sensorValue.SensorId,
		sensorValue.Type,
		sensorValue.Time,
		sensorValue.Value,
		sensorValue.Ip,
	)
}

func (d *SensorValueDAO) FindRange(start, end time.Time, typ string) ([]SensorValue, error) {
	return readValues(d.findRange.Query(start, end, typ))
}

func (d *SensorValueDAO) FindLast(sensorId string, typ string) (SensorValue, error) {
	return ReadSensorValueAndReturn(d.findLast.Query(sensorId, typ))
}

func ReadSensorValueAndReturn(rows *sql.Rows, err error) (SensorValue, error) {
	var rv SensorValue

	if err != nil {
		return rv, err
	}

	if rows == nil {
		return rv, nil
	}

	defer rows.Close()

	if rows.Next() {
		rv, err = sensorValueFromRow(rows)
	}

	return rv, err
}

func readValues(rows *sql.Rows, err error) ([]SensorValue, error) {
	rv := make([]SensorValue, 0)
	if rows == nil {
		return rv, nil
	}

	defer rows.Close()

	for rows.Next() {
		var v SensorValue
		var err error
		if v, err = sensorValueFromRow(rows); err != nil {
			return rv, err
		}
		rv = append(rv, v)
	}

	return rv, nil
}

// sensorValueFromRow reads an parking model from the current row.
func sensorValueFromRow(rows *sql.Rows) (SensorValue, error) {
	var sensorId,
		ip,
		typ string
	var t time.Time
	var value float64

	err := rows.Scan(
		&sensorId,
		&typ,
		&t,
		&value,
		&ip)

	return SensorValue{
		SensorId: sensorId,
		Type:     typ,
		Time:     t,
		Value:    value,
		Ip:       ip,
	}, err
}
<|endoftext|>


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

// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file implements the symbol table.

package golisp

import (
	"container/list"
	"errors"
	"fmt"
)

type SymbolTableFrame struct {
	Parent      *SymbolTableFrame
	Previous    *SymbolTableFrame
	Frame       *FrameMap
	Bindings    map[string]*Binding
	CurrentCode *list.List
}

var Global *SymbolTableFrame

func (self *SymbolTableFrame) Depth() int {
	if self.Previous == nil {
		return 1
	} else {
		return 1 + self.Previous.Depth()
	}
}

func (self *SymbolTableFrame) InternalDump(frameNumber int) {
	fmt.Printf("Frame %d: %s\n", frameNumber, self.CurrentCode.Front().Value)
	for _, b := range self.Bindings {
		if b.Val == nil || TypeOf(b.Val) != PrimitiveType {
			b.Dump()
		}
	}
	fmt.Printf("\n")
	if self.Previous != nil {
		self.Previous.InternalDump(frameNumber + 1)
	}
}

func (self *SymbolTableFrame) Dump() {
	println()
	self.InternalDump(0)
}

func (self *SymbolTableFrame) DumpSingleFrame(frameNumber int) {
	if frameNumber == 0 {
		fmt.Printf("%s\n", self.CurrentCode.Front().Value)
		for _, b := range self.Bindings {
			if b.Val == nil || TypeOf(b.Val) != PrimitiveType {
				b.Dump()
			}
		}
		fmt.Printf("\n")
	} else if self.Previous != nil {
		self.Previous.DumpSingleFrame(frameNumber - 1)
	} else {
		fmt.Printf("Invalid frame selected.\n")
	}
}

func (self *SymbolTableFrame) InternalDumpHeaders(frameNumber int) {
	fmt.Printf("Frame %d: %s\n", frameNumber, self.CurrentCode.Front().Value)
	if self.Previous != nil {
		self.Previous.InternalDumpHeaders(frameNumber + 1)
	}
}

func (self *SymbolTableFrame) DumpHeaders() {
	println()
	self.InternalDumpHeaders(0)
}

func (self *SymbolTableFrame) DumpHeader() {
	fmt.Printf("%s\n", self.CurrentCode.Front().Value)
}

func NewSymbolTableFrameBelow(p *SymbolTableFrame) *SymbolTableFrame {
	var f *FrameMap = nil
	if p != nil {
		f = p.Frame
	}
	return &SymbolTableFrame{Parent: p, Bindings: make(map[string]*Binding), Frame: f, CurrentCode: list.New()}
}

func NewSymbolTableFrameBelowWithFrame(p *SymbolTableFrame, f *FrameMap) *SymbolTableFrame {
	if f == nil {
		f = p.Frame
	}
	return &SymbolTableFrame{Parent: p, Bindings: make(map[string]*Binding, 10), Frame: f, CurrentCode: list.New()}
}

func (self *SymbolTableFrame) HasFrame() bool {
	return self.Frame != nil
}

func (self *SymbolTableFrame) BindingNamed(name string) (b *Binding, present bool) {
	b, present = self.Bindings[name]
	return
}

func (self *SymbolTableFrame) SetBindingAt(name string, b *Binding) {
	self.Bindings[name] = b
}

func (self *SymbolTableFrame) findSymbol(name string) (symbol *Data, found bool) {
	binding, found := self.BindingNamed(name)
	if found {
		return binding.Sym, true
	} else if self.Parent != nil {
		return self.Parent.findSymbol(name)
	} else {
		return nil, false
	}
}

func (self *SymbolTableFrame) findBindingFor(symbol *Data) (binding *Binding, found bool) {
	name := StringValue(symbol)
	binding, found = self.BindingNamed(name)
	if found {
		return
	} else if self.Parent != nil {
		return self.Parent.findBindingFor(symbol)
	} else {
		return nil, false
	}
}

func (self *SymbolTableFrame) Intern(name string) (sym *Data) {
	sym, found := self.findSymbol(name)
	if !found {
		sym = SymbolWithName(name)
		self.BindTo(sym, nil)
		return
	} else {
		return nil
	}
}

func (self *SymbolTableFrame) BindTo(symbol *Data, value *Data) *Data {
	binding, found := self.findBindingFor(symbol)
	if found {
		binding.Val = value
	} else {
		binding := BindingWithSymbolAndValue(symbol, value)
		self.SetBindingAt(StringValue(symbol), binding)
	}
	return value
}

func (self *SymbolTableFrame) SetTo(symbol *Data, value *Data) (result *Data, err error) {
	localBinding, found := self.findBindingInLocalFrameFor(symbol)
	if found {
		localBinding.Val = value
		return value, nil
	}

	naked := StringValue(NakedSymbolFrom(symbol))
	if self.HasFrame() && self.Frame.HasSlot(naked) {
		self.Frame.Set(naked, value)
		return value, nil
	}

	binding, found := self.findBindingFor(symbol)
	if found {
		binding.Val = value
		return value, nil
	}

	return nil, errors.New(fmt.Sprintf("%s is undefined", StringValue(symbol)))
}

func (self *SymbolTableFrame) findBindingInLocalFrameFor(symbol *Data) (b *Binding, found bool) {
	return self.BindingNamed(StringValue(symbol))
}

func (self *SymbolTableFrame) BindLocallyTo(symbol *Data, value *Data) *Data {
	binding, found := self.findBindingInLocalFrameFor(symbol)
	if found {
		binding.Val = value
	} else {
		binding := BindingWithSymbolAndValue(symbol, value)
		self.SetBindingAt(StringValue(symbol), binding)
	}
	return value
}

func (self *SymbolTableFrame) ValueOf(symbol *Data) *Data {
	localBinding, found := self.findBindingInLocalFrameFor(symbol)
	if found {
		return localBinding.Val
	}

	naked := StringValue(NakedSymbolFrom(symbol))
	if self.HasFrame() && self.Frame.HasSlot(naked) {
		return self.Frame.Get(naked)
	}

	binding, found := self.findBindingFor(symbol)
	if found {
		return binding.Val
	} else {
		return nil
	}
}
<commit_msg>Handle a break before current code string is set.<commit_after>// Copyright 2014 SteelSeries ApS.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file implements the symbol table.

package golisp

import (
	"container/list"
	"errors"
	"fmt"
)

type SymbolTableFrame struct {
	Parent      *SymbolTableFrame
	Previous    *SymbolTableFrame
	Frame       *FrameMap
	Bindings    map[string]*Binding
	CurrentCode *list.List
}

var Global *SymbolTableFrame

func (self *SymbolTableFrame) Depth() int {
	if self.Previous == nil {
		return 1
	} else {
		return 1 + self.Previous.Depth()
	}
}

func (self *SymbolTableFrame) CurrentCodeString() string {
	if self.CurrentCode.Len() > 0 {
		return self.CurrentCode.Front().Value
	} else {
		return "Unknown code"
	}
}

func (self *SymbolTableFrame) InternalDump(frameNumber int) {
	fmt.Printf("Frame %d: %s\n", frameNumber, self.CurrentCodeString())
	for _, b := range self.Bindings {
		if b.Val == nil || TypeOf(b.Val) != PrimitiveType {
			b.Dump()
		}
	}
	fmt.Printf("\n")
	if self.Previous != nil {
		self.Previous.InternalDump(frameNumber + 1)
	}
}

func (self *SymbolTableFrame) Dump() {
	println()
	self.InternalDump(0)
}

func (self *SymbolTableFrame) DumpSingleFrame(frameNumber int) {
	if frameNumber == 0 {
		fmt.Printf("%s\n", self.CurrentCodeString())
		for _, b := range self.Bindings {
			if b.Val == nil || TypeOf(b.Val) != PrimitiveType {
				b.Dump()
			}
		}
		fmt.Printf("\n")
	} else if self.Previous != nil {
		self.Previous.DumpSingleFrame(frameNumber - 1)
	} else {
		fmt.Printf("Invalid frame selected.\n")
	}
}

func (self *SymbolTableFrame) InternalDumpHeaders(frameNumber int) {
	fmt.Printf("Frame %d: %s\n", frameNumber, self.CurrentCodeString())
	if self.Previous != nil {
		self.Previous.InternalDumpHeaders(frameNumber + 1)
	}
}

func (self *SymbolTableFrame) DumpHeaders() {
	println()
	self.InternalDumpHeaders(0)
}

func (self *SymbolTableFrame) DumpHeader() {
	fmt.Printf("%s\n", self.CurrentCodeString())
}

func NewSymbolTableFrameBelow(p *SymbolTableFrame) *SymbolTableFrame {
	var f *FrameMap = nil
	if p != nil {
		f = p.Frame
	}
	return &SymbolTableFrame{Parent: p, Bindings: make(map[string]*Binding), Frame: f, CurrentCode: list.New()}
}

func NewSymbolTableFrameBelowWithFrame(p *SymbolTableFrame, f *FrameMap) *SymbolTableFrame {
	if f == nil {
		f = p.Frame
	}
	return &SymbolTableFrame{Parent: p, Bindings: make(map[string]*Binding, 10), Frame: f, CurrentCode: list.New()}
}

func (self *SymbolTableFrame) HasFrame() bool {
	return self.Frame != nil
}

func (self *SymbolTableFrame) BindingNamed(name string) (b *Binding, present bool) {
	b, present = self.Bindings[name]
	return
}

func (self *SymbolTableFrame) SetBindingAt(name string, b *Binding) {
	self.Bindings[name] = b
}

func (self *SymbolTableFrame) findSymbol(name string) (symbol *Data, found bool) {
	binding, found := self.BindingNamed(name)
	if found {
		return binding.Sym, true
	} else if self.Parent != nil {
		return self.Parent.findSymbol(name)
	} else {
		return nil, false
	}
}

func (self *SymbolTableFrame) findBindingFor(symbol *Data) (binding *Binding, found bool) {
	name := StringValue(symbol)
	binding, found = self.BindingNamed(name)
	if found {
		return
	} else if self.Parent != nil {
		return self.Parent.findBindingFor(symbol)
	} else {
		return nil, false
	}
}

func (self *SymbolTableFrame) Intern(name string) (sym *Data) {
	sym, found := self.findSymbol(name)
	if !found {
		sym = SymbolWithName(name)
		self.BindTo(sym, nil)
		return
	} else {
		return nil
	}
}

func (self *SymbolTableFrame) BindTo(symbol *Data, value *Data) *Data {
	binding, found := self.findBindingFor(symbol)
	if found {
		binding.Val = value
	} else {
		binding := BindingWithSymbolAndValue(symbol, value)
		self.SetBindingAt(StringValue(symbol), binding)
	}
	return value
}

func (self *SymbolTableFrame) SetTo(symbol *Data, value *Data) (result *Data, err error) {
	localBinding, found := self.findBindingInLocalFrameFor(symbol)
	if found {
		localBinding.Val = value
		return value, nil
	}

	naked := StringValue(NakedSymbolFrom(symbol))
	if self.HasFrame() && self.Frame.HasSlot(naked) {
		self.Frame.Set(naked, value)
		return value, nil
	}

	binding, found := self.findBindingFor(symbol)
	if found {
		binding.Val = value
		return value, nil
	}

	return nil, errors.New(fmt.Sprintf("%s is undefined", StringValue(symbol)))
}

func (self *SymbolTableFrame) findBindingInLocalFrameFor(symbol *Data) (b *Binding, found bool) {
	return self.BindingNamed(StringValue(symbol))
}

func (self *SymbolTableFrame) BindLocallyTo(symbol *Data, value *Data) *Data {
	binding, found := self.findBindingInLocalFrameFor(symbol)
	if found {
		binding.Val = value
	} else {
		binding := BindingWithSymbolAndValue(symbol, value)
		self.SetBindingAt(StringValue(symbol), binding)
	}
	return value
}

func (self *SymbolTableFrame) ValueOf(symbol *Data) *Data {
	localBinding, found := self.findBindingInLocalFrameFor(symbol)
	if found {
		return localBinding.Val
	}

	naked := StringValue(NakedSymbolFrom(symbol))
	if self.HasFrame() && self.Frame.HasSlot(naked) {
		return self.Frame.Get(naked)
	}

	binding, found := self.findBindingFor(symbol)
	if found {
		return binding.Val
	} else {
		return nil
	}
}
<|endoftext|>


<commit_before>package myqlib

import (
	"bytes"
	"errors"
	"fmt"
)

// All Columns must implement the following
type Col interface {
	// outputs (write to the buffer)
	Help(b *bytes.Buffer)    // short help
	Header1(b *bytes.Buffer) // if empty, must print width spaces
	Header2(b *bytes.Buffer) // header to print above data

	// A full line of output given the state
	Data(b *bytes.Buffer, state MyqState)

	Width() uint8 // width of the column
}

// 'Default' column -- "inherited" by others
type DefaultCol struct {
	name string // name/header of the group
	help string // short description of the group
	width uint8 // width of the column output (header and data)
}
func (c DefaultCol) Help(b *bytes.Buffer) {
  b.WriteString(fmt.Sprint( c.name, ": ", c.help))
}
func (c DefaultCol) Width() uint8 { return c.width }
func (c DefaultCol) Header1(b *bytes.Buffer) {
  b.WriteString(fmt.Sprintf(fmt.Sprint(`%-`, c.Width(), `s`), ""))
}
func (c DefaultCol) Header2(b *bytes.Buffer) {
	b.WriteString(fmt.Sprintf(fmt.Sprint(`%`, c.Width(), `s`), c.name))
}

// Groups of columns
type GroupCol struct {
  DefaultCol
	cols []Col // slice of columns in this group
}

func (c GroupCol) Help(b *bytes.Buffer) {
  b.WriteString(c.help)
  b.WriteString("\n")
	for _, col := range c.cols {
    b.WriteString("\t")
    col.Help(b)
    b.WriteString("\n")
	}
}
func (c GroupCol) Width() uint8 {
	var w uint8
	for _, col := range c.cols {
		w += col.Width() + 1
	}
	w -= 1
	return w
}
func (c GroupCol) Header1(b *bytes.Buffer) {
  b.WriteString(fmt.Sprintf(fmt.Sprint(`%-`, c.Width(), `s`),
      c.name))
}
func (c GroupCol) Header2(b *bytes.Buffer) {
	space := false
	for _, col := range c.cols {
		if space {
			b.WriteString(" ") // one space before each column
		}
		col.Header2(b)
		space = true
	}
}
func (c GroupCol) Data(b *bytes.Buffer, state MyqState) {
	space := false
	for _, col := range c.cols {
		if space {
			b.WriteString(" ") // one space before each column
		}
		col.Data(b, state)
		space = true
	}
}

// Gauge Columns simply display SHOW STATUS variable
type GaugeCol struct {
  DefaultCol
	variable_name string // SHOW STATUS variable of this column
	precision uint8 // # of decimals to show on floats (optional)
  units UnitsDef
}

func (c GaugeCol) Data(b *bytes.Buffer, state MyqState) {
	val := state.Cur[c.variable_name]

	switch v := val.(type) {
	case int64:
		// format number here
    cv := collapse_number( float64(v), int64(c.width), int64(c.precision), c.units )
		b.WriteString(
			fmt.Sprintf(fmt.Sprint(`%`, c.width, `s`), cv))
	case float64:
		// format number here
		// precision subtracts from total width (+ the decimal point)
    cv := collapse_number( v, int64(c.width), int64(c.precision), c.units )
		b.WriteString(fmt.Sprintf(fmt.Sprint(`%`, c.width, `s`), cv))
	case string:
		b.WriteString(v)
	default:
		filler(b, c)
	}
}

// Rate Columns the rate of change of a SHOW STATUS variable
type RateCol struct {
  DefaultCol
	variable_name string // SHOW STATUS variable of this column
	precision uint8 // # of decimals to show on floats (optional)
  units UnitsDef
}

func (c RateCol) Data(b *bytes.Buffer, state MyqState) {
	// !! still not sure I like the uptime here
	diff, err := calculate_rate(state.Cur[c.variable_name], state.Prev[c.variable_name], state.TimeDiff)
	if err != nil {
		// Can't output, just put a filler
		// fmt.Println( err )
		filler(b, c)
	} else {
    cv := collapse_number( diff, int64(c.width), int64(c.precision), c.units )
		b.WriteString(fmt.Sprintf(fmt.Sprint(`%`, c.width, `s`), cv))
	}
}

// calculate the difference over the time to get the rate.  This is complex, and we need to verify several things:
// 1. input intefaces are non-nil
// 2. cur & prev are int or float64
// 3. if prev is nil  and/or time is <0, we just return cur
// 4. output type always a float, deal with output format later
// 5. handle cur < prev (usually time would be <0 here, but in case), by just returing cur / time
func calculate_rate(cur, prev interface{}, time float64) (float64, error) {
	// cur and prev must not be nil
	if cur == nil {
		return 0.00, errors.New("nil cur")
	}

	// Rates only work on numeric types.  Error on non-numeric and convert numerics to float64 as needed
	// fmt.Println( reflect.TypeOf( cur ))
	var c, p float64
	switch cu := cur.(type) {
	case int64:
		c = float64(cu)
	case float64:
		c = cu
	default:
		return 0.00, errors.New("cur is not numeric!")
	}

	if prev != nil {
		switch pr := prev.(type) {
		case int64:
			p = float64(pr)
		case float64:
			p = pr
		default:
			return 0.00, errors.New("prev is not numeric!")
		}
	}

	if prev == nil || time <= 0 {
		return c, nil
	} else if c < p {
		return c / time, nil
	} else {
		return (c - p) / time, nil
	}
}

func filler(b *bytes.Buffer, c Col) {
	b.WriteString(fmt.Sprintf( fmt.Sprint(`%`, c.Width(), `s`), "-"))
}

// Func Columns run a custom function to produce their output
type FuncCol struct {
  DefaultCol
	precision uint8 // # of decimals to show on floats (optional)
	fn func(b *bytes.Buffer, state MyqState, c Col) // takes the state and returns the (unformatted) value
}
func (c FuncCol) Data(b *bytes.Buffer, state MyqState) {
	c.fn(b, state, c)
}<commit_msg>more concise logic for spacing<commit_after>package myqlib

import (
	"bytes"
	"errors"
	"fmt"
)

// All Columns must implement the following
type Col interface {
	// outputs (write to the buffer)
	Help(b *bytes.Buffer)    // short help
	Header1(b *bytes.Buffer) // if empty, must print width spaces
	Header2(b *bytes.Buffer) // header to print above data

	// A full line of output given the state
	Data(b *bytes.Buffer, state MyqState)

	Width() uint8 // width of the column
}

// 'Default' column -- "inherited" by others
type DefaultCol struct {
	name string // name/header of the group
	help string // short description of the group
	width uint8 // width of the column output (header and data)
}
func (c DefaultCol) Help(b *bytes.Buffer) {
  b.WriteString(fmt.Sprint( c.name, ": ", c.help))
}
func (c DefaultCol) Width() uint8 { return c.width }
func (c DefaultCol) Header1(b *bytes.Buffer) {
  b.WriteString(fmt.Sprintf(fmt.Sprint(`%-`, c.Width(), `s`), ""))
}
func (c DefaultCol) Header2(b *bytes.Buffer) {
	b.WriteString(fmt.Sprintf(fmt.Sprint(`%`, c.Width(), `s`), c.name))
}

// Groups of columns
type GroupCol struct {
  DefaultCol
	cols []Col // slice of columns in this group
}

func (c GroupCol) Help(b *bytes.Buffer) {
  b.WriteString(c.help)
  b.WriteString("\n")
	for _, col := range c.cols {
    b.WriteString("\t")
    col.Help(b)
    b.WriteString("\n")
	}
}
func (c GroupCol) Width() (w uint8) {
	for _, col := range c.cols { w += col.Width() + 1 }
	w -= 1
	return
}
func (c GroupCol) Header1(b *bytes.Buffer) {
  b.WriteString(fmt.Sprintf(fmt.Sprint(`%-`, c.Width(), `s`),
      c.name))
}
func (c GroupCol) Header2(b *bytes.Buffer) {
	space := false
	for _, col := range c.cols {
		if space {b.WriteString(" ")} else {space = true}
		col.Header2(b)
	}
}
func (c GroupCol) Data(b *bytes.Buffer, state MyqState) {
	space := false
	for _, col := range c.cols {
		if space {b.WriteString(" ")} else {space = true}
		col.Data(b, state)
	}
}

// Gauge Columns simply display SHOW STATUS variable
type GaugeCol struct {
  DefaultCol
	variable_name string // SHOW STATUS variable of this column
	precision uint8 // # of decimals to show on floats (optional)
  units UnitsDef
}

func (c GaugeCol) Data(b *bytes.Buffer, state MyqState) {
	val := state.Cur[c.variable_name]

	switch v := val.(type) {
	case int64:
		// format number here
    cv := collapse_number( float64(v), int64(c.width), int64(c.precision), c.units )
		b.WriteString(
			fmt.Sprintf(fmt.Sprint(`%`, c.width, `s`), cv))
	case float64:
		// format number here
		// precision subtracts from total width (+ the decimal point)
    cv := collapse_number( v, int64(c.width), int64(c.precision), c.units )
		b.WriteString(fmt.Sprintf(fmt.Sprint(`%`, c.width, `s`), cv))
	case string:
		b.WriteString(v)
	default:
		filler(b, c)
	}
}

// Rate Columns the rate of change of a SHOW STATUS variable
type RateCol struct {
  DefaultCol
	variable_name string // SHOW STATUS variable of this column
	precision uint8 // # of decimals to show on floats (optional)
  units UnitsDef
}

func (c RateCol) Data(b *bytes.Buffer, state MyqState) {
	// !! still not sure I like the uptime here
	diff, err := calculate_rate(state.Cur[c.variable_name], state.Prev[c.variable_name], state.TimeDiff)
	if err != nil {
		// Can't output, just put a filler
		// fmt.Println( err )
		filler(b, c)
	} else {
    cv := collapse_number( diff, int64(c.width), int64(c.precision), c.units )
		b.WriteString(fmt.Sprintf(fmt.Sprint(`%`, c.width, `s`), cv))
	}
}

// calculate the difference over the time to get the rate.  This is complex, and we need to verify several things:
// 1. input intefaces are non-nil
// 2. cur & prev are int or float64
// 3. if prev is nil  and/or time is <0, we just return cur
// 4. output type always a float, deal with output format later
// 5. handle cur < prev (usually time would be <0 here, but in case), by just returing cur / time
func calculate_rate(cur, prev interface{}, time float64) (float64, error) {
	// cur and prev must not be nil
	if cur == nil {
		return 0.00, errors.New("nil cur")
	}

	// Rates only work on numeric types.  Error on non-numeric and convert numerics to float64 as needed
	// fmt.Println( reflect.TypeOf( cur ))
	var c, p float64
	switch cu := cur.(type) {
	case int64:
		c = float64(cu)
	case float64:
		c = cu
	default:
		return 0.00, errors.New("cur is not numeric!")
	}

	if prev != nil {
		switch pr := prev.(type) {
		case int64:
			p = float64(pr)
		case float64:
			p = pr
		default:
			return 0.00, errors.New("prev is not numeric!")
		}
	}

	if prev == nil || time <= 0 {
		return c, nil
	} else if c < p {
		return c / time, nil
	} else {
		return (c - p) / time, nil
	}
}

func filler(b *bytes.Buffer, c Col) {
	b.WriteString(fmt.Sprintf( fmt.Sprint(`%`, c.Width(), `s`), "-"))
}

// Func Columns run a custom function to produce their output
type FuncCol struct {
  DefaultCol
	precision uint8 // # of decimals to show on floats (optional)
	fn func(b *bytes.Buffer, state MyqState, c Col) // takes the state and returns the (unformatted) value
}
func (c FuncCol) Data(b *bytes.Buffer, state MyqState) {
	c.fn(b, state, c)
}<|endoftext|>


<commit_before>package ntlmssp

import (
	"bytes"
	"encoding/base64"
	"io/ioutil"
	"net/http"
)

//Negotiator is a http.Roundtripper decorator that automatically
//converts basic authentication to NTLM/Negotiate authentication when appropriate.
type Negotiator struct{ http.RoundTripper }

//RoundTrip sends the request to the server, handling any authentication
//re-sends as needed.
func (l Negotiator) RoundTrip(req *http.Request) (res *http.Response, err error) {
	body := bytes.Buffer{}
	_, err = body.ReadFrom(req.Body)
	if err != nil {
		return nil, err
	}

	req.Body.Close()
	req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

	reqauth := authheader(req.Header.Get("Authorization"))
	if reqauth.IsBasic() {
		// first try anonymous, in case the server still finds us
		// authenticated from previous traffic
		req.Header.Del("Authorization")

		res, err = l.RoundTripper.RoundTrip(req)
		if err != nil {
			return nil, err
		}
		if res.StatusCode != 401 {
			return res, err
		}
	}

	resauth := authheader(res.Header.Get("Www-Authenticate"))
	if !resauth.IsNegotiate() {
		// Unauthorized, Negotiate not requested, let's try with basic auth
		res.Body.Close()
		req.Header.Set("Authorization", string(reqauth))
		req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

		res, err = l.RoundTripper.RoundTrip(req)
		if err != nil {
			return nil, err
		}
	}

	if res.StatusCode == 401 {
		resauth := authheader(res.Header.Get("Www-Authenticate"))
		if reqauth.IsBasic() && resauth.IsNegotiate() {
			// 401 with request:Basic and response:Negotiate
			res.Body.Close()

			// recycle credentials
			u, p, err := reqauth.GetBasicCreds()
			if err != nil {
				return nil, err
			}

			// send negotiate
			negotiateMessage := NewNegotiateMessage()
			req.Header.Set("Authorization", "Negotiate "+base64.StdEncoding.EncodeToString(negotiateMessage))
			req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

			res, err = l.RoundTripper.RoundTrip(req)
			if err != nil {
				return nil, err
			}

			// receive challenge?
			resauth = authheader(res.Header.Get("Www-Authenticate"))
			challengeMessage, err := resauth.GetData()
			if err != nil {
				return nil, err
			}
			if !resauth.IsNegotiate() || len(challengeMessage) == 0 {
				// Negotiation failed, let client deal with response
				return res, nil
			}
			res.Body.Close()

			// send authenticate
			authenticateMessage, err := ProcessChallenge(challengeMessage, u, p)
			if err != nil {
				return nil, err
			}
			req.Header.Set("Authorization", "Negotiate "+base64.StdEncoding.EncodeToString(authenticateMessage))
			req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

			res, err = l.RoundTripper.RoundTrip(req)
		}
	}

	return res, err
}
<commit_msg>Handle http redirect (#4)<commit_after>package ntlmssp

import (
	"bytes"
	"encoding/base64"
	"io/ioutil"
	"net/http"
)

//Negotiator is a http.Roundtripper decorator that automatically
//converts basic authentication to NTLM/Negotiate authentication when appropriate.
type Negotiator struct{ http.RoundTripper }

//RoundTrip sends the request to the server, handling any authentication
//re-sends as needed.
func (l Negotiator) RoundTrip(req *http.Request) (res *http.Response, err error) {
	// Use default round tripper if not provided
	rt := l.RoundTripper
	if rt == nil {
		rt = http.DefaultTransport
	}
	// If it is not basic auth, just round trip the request as usual
	reqauth := authheader(req.Header.Get("Authorization"))
	if !reqauth.IsBasic() {
		return rt.RoundTrip(req)
	}
	// Save request body
	body := bytes.Buffer{}
	if req.Body != nil {
		_, err = body.ReadFrom(req.Body)
		if err != nil {
			return nil, err
		}

		req.Body.Close()
		req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))
	}
	// first try anonymous, in case the server still finds us
	// authenticated from previous traffic
	req.Header.Del("Authorization")
	res, err = rt.RoundTrip(req)
	if err != nil {
		return nil, err
	}
	if res.StatusCode != http.StatusUnauthorized {
		return res, err
	}

	resauth := authheader(res.Header.Get("Www-Authenticate"))
	if !resauth.IsNegotiate() {
		// Unauthorized, Negotiate not requested, let's try with basic auth
		req.Header.Set("Authorization", string(reqauth))
		res.Body.Close()
		req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

		res, err = rt.RoundTrip(req)
		if err != nil {
			return nil, err
		}
		if res.StatusCode != http.StatusUnauthorized {
			return res, err
		}
		resauth = authheader(res.Header.Get("Www-Authenticate"))
	}

	if resauth.IsNegotiate() {
		// 401 with request:Basic and response:Negotiate
		res.Body.Close()

		// recycle credentials
		u, p, err := reqauth.GetBasicCreds()
		if err != nil {
			return nil, err
		}

		// send negotiate
		negotiateMessage := NewNegotiateMessage()
		req.Header.Set("Authorization", "Negotiate "+base64.StdEncoding.EncodeToString(negotiateMessage))
		req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

		res, err = rt.RoundTrip(req)
		if err != nil {
			return nil, err
		}

		// receive challenge?
		resauth = authheader(res.Header.Get("Www-Authenticate"))
		challengeMessage, err := resauth.GetData()
		if err != nil {
			return nil, err
		}
		if !resauth.IsNegotiate() || len(challengeMessage) == 0 {
			// Negotiation failed, let client deal with response
			return res, nil
		}
		res.Body.Close()

		// send authenticate
		authenticateMessage, err := ProcessChallenge(challengeMessage, u, p)
		if err != nil {
			return nil, err
		}
		req.Header.Set("Authorization", "Negotiate "+base64.StdEncoding.EncodeToString(authenticateMessage))
		req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))

		res, err = rt.RoundTrip(req)
	}

	return res, err
}
<|endoftext|>


<commit_before>package net

import (
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

// Connect to a peer.
//
// Given parameters cert/key/ca are PEM-encoded array of bytes.
// Closing must be defered after call.
func Connect(addrPort string, cert *x509.Certificate, key *rsa.PrivateKey, ca *x509.Certificate) (*grpc.ClientConn, error) {

	var certificates = make([]tls.Certificate, 1)

	if key != nil && cert != nil {
		peerCert := tls.Certificate{
			Certificate: [][]byte{cert.Raw},
			PrivateKey:  key,
		}
		certificates = append(certificates, peerCert)
	}

	caCertPool := x509.NewCertPool()
	caCertPool.AddCert(ca)

	// configure transport authentificator
	ta := credentials.NewTLS(&tls.Config{
		Certificates: certificates,
		RootCAs:      caCertPool,
	})

	// let's do the dialing !
	return grpc.Dial(addrPort, grpc.WithTransportCredentials(ta))
}
<commit_msg>[net] Add support for direct IP connection<commit_after>package net

import (
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"net"
	"time"

	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

// Connect to a peer.
//
// Given parameters cert/key/ca are PEM-encoded array of bytes.
// Closing must be defered after call.
func Connect(addrPort string, cert *x509.Certificate, key *rsa.PrivateKey, ca *x509.Certificate) (*grpc.ClientConn, error) {

	var certificates = make([]tls.Certificate, 1)

	if key != nil && cert != nil {
		peerCert := tls.Certificate{
			Certificate: [][]byte{cert.Raw},
			PrivateKey:  key,
		}
		certificates = append(certificates, peerCert)
	}

	caCertPool := x509.NewCertPool()
	caCertPool.AddCert(ca)

	// configure transport authentificator
	conf := tls.Config{
		Certificates:       certificates,
		RootCAs:            caCertPool,
		InsecureSkipVerify: true, // Don't panic, it's normal and safe. See tlsCreds structure.
	}

	// let's do the dialing !
	return grpc.Dial(
		addrPort,
		grpc.WithTransportCredentials(&tlsCreds{config: conf}),
	)
}

// tlsCreds reimplements the default grpc TLS authenticator with no hostname verification.
// It is required because we need to connect to clients with their IP, and there is no IP SANs in our certificates.
//
// We need to enable the "InsecureSkipVerify" to perform this, that's why it's important to check the server certificate
// during the authentication process.
//
// See crypto/tls/handshake_client.go and google.golang.org/grpc/credentials/credentials.go
type tlsCreds struct {
	config tls.Config
}

func (c *tlsCreds) Info() credentials.ProtocolInfo {
	return credentials.ProtocolInfo{
		SecurityProtocol: "tls",
		SecurityVersion:  "1.2",
	}
}

func (c *tlsCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return nil, nil
}

func (c *tlsCreds) RequireTransportSecurity() bool {
	return true
}

func (c *tlsCreds) ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (_ net.Conn, _ credentials.AuthInfo, err error) {
	var errChannel chan error
	if timeout != 0 {
		errChannel = make(chan error, 2)
		time.AfterFunc(timeout, func() {
			errChannel <- errors.New("credentials: Dial timed out")
		})
	}

	// Establish a secure connection WITHOUT certificate verification
	conn := tls.Client(rawConn, &c.config)
	if timeout == 0 {
		err = conn.Handshake()
	} else {
		go func() { errChannel <- conn.Handshake() }()
		err = <-errChannel
	}

	if err != nil { // Error during handshake
		_ = rawConn.Close()
		return nil, nil, err
	}

	// Successful handshake, BUT we have to authentify the server NOW
	opts := x509.VerifyOptions{
		Roots:       c.config.RootCAs,
		CurrentTime: time.Now(),
	}

	var chains [][]*x509.Certificate

	state := conn.ConnectionState()
	serverCert := state.PeerCertificates[0]
	chains, err = serverCert.Verify(opts)
	state.VerifiedChains = chains

	if err != nil {
		_ = rawConn.Close()
		return nil, nil, err
	}

	return conn, nil, nil
}

func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
	return nil, nil, errors.New("Server side handshake not implemented")
}
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package protobuf

import (
	"fmt"
	"reflect"
	"strings"

	"k8s.io/gengo/generator"
	"k8s.io/gengo/namer"
	"k8s.io/gengo/types"
)

type localNamer struct {
	localPackage types.Name
}

func (n localNamer) Name(t *types.Type) string {
	if t.Key != nil && t.Elem != nil {
		return fmt.Sprintf("map<%s, %s>", n.Name(t.Key), n.Name(t.Elem))
	}
	if len(n.localPackage.Package) != 0 && n.localPackage.Package == t.Name.Package {
		return t.Name.Name
	}
	return t.Name.String()
}

type protobufNamer struct {
	packages       []*protobufPackage
	packagesByPath map[string]*protobufPackage
}

func NewProtobufNamer() *protobufNamer {
	return &protobufNamer{
		packagesByPath: make(map[string]*protobufPackage),
	}
}

func (n *protobufNamer) Name(t *types.Type) string {
	if t.Kind == types.Map {
		return fmt.Sprintf("map<%s, %s>", n.Name(t.Key), n.Name(t.Elem))
	}
	return t.Name.String()
}

func (n *protobufNamer) List() []generator.Package {
	packages := make([]generator.Package, 0, len(n.packages))
	for i := range n.packages {
		packages = append(packages, n.packages[i])
	}
	return packages
}

func (n *protobufNamer) Add(p *protobufPackage) {
	if _, ok := n.packagesByPath[p.PackagePath]; !ok {
		n.packagesByPath[p.PackagePath] = p
		n.packages = append(n.packages, p)
	}
}

func (n *protobufNamer) GoNameToProtoName(name types.Name) types.Name {
	if p, ok := n.packagesByPath[name.Package]; ok {
		return types.Name{
			Name:    name.Name,
			Package: p.PackageName,
			Path:    p.ImportPath(),
		}
	}
	for _, p := range n.packages {
		if _, ok := p.FilterTypes[name]; ok {
			return types.Name{
				Name:    name.Name,
				Package: p.PackageName,
				Path:    p.ImportPath(),
			}
		}
	}
	return types.Name{Name: name.Name}
}

func protoSafePackage(name string) string {
	pkg := strings.Replace(name, "/", ".", -1)
	return strings.Replace(pkg, "-", "_", -1)
}

type typeNameSet map[types.Name]*protobufPackage

// assignGoTypeToProtoPackage looks for Go and Protobuf types that are referenced by a type in
// a package. It will not recurse into protobuf types.
func assignGoTypeToProtoPackage(p *protobufPackage, t *types.Type, local, global typeNameSet, optional map[types.Name]struct{}) {
	newT, isProto := isFundamentalProtoType(t)
	if isProto {
		t = newT
	}
	if otherP, ok := global[t.Name]; ok {
		if _, ok := local[t.Name]; !ok {
			p.Imports.AddType(&types.Type{
				Kind: types.Protobuf,
				Name: otherP.ProtoTypeName(),
			})
		}
		return
	}
	global[t.Name] = p
	if _, ok := local[t.Name]; ok {
		return
	}
	// don't recurse into existing proto types
	if isProto {
		p.Imports.AddType(t)
		return
	}

	local[t.Name] = p
	for _, m := range t.Members {
		if namer.IsPrivateGoName(m.Name) {
			continue
		}
		field := &protoField{}
		tag := reflect.StructTag(m.Tags).Get("protobuf")
		if tag == "-" {
			continue
		}
		if err := protobufTagToField(tag, field, m, t, p.ProtoTypeName()); err == nil && field.Type != nil {
			assignGoTypeToProtoPackage(p, field.Type, local, global, optional)
			continue
		}
		assignGoTypeToProtoPackage(p, m.Type, local, global, optional)
	}
	// TODO: should methods be walked?
	if t.Elem != nil {
		assignGoTypeToProtoPackage(p, t.Elem, local, global, optional)
	}
	if t.Key != nil {
		assignGoTypeToProtoPackage(p, t.Key, local, global, optional)
	}
	if t.Underlying != nil {
		if t.Kind == types.Alias && isOptionalAlias(t) {
			optional[t.Name] = struct{}{}
		}
		assignGoTypeToProtoPackage(p, t.Underlying, local, global, optional)
	}
}

// isTypeApplicableToProtobuf checks to see if a type is relevant for protobuf processing.
// Currently, it filters out functions and private types.
func isTypeApplicableToProtobuf(t *types.Type) bool {
	// skip functions -- we don't care about them for protobuf
	if t.Kind == types.Func || (t.Kind == types.DeclarationOf && t.Underlying.Kind == types.Func) {
		return false
	}
	// skip private types
	if namer.IsPrivateGoName(t.Name.Name) {
		return false
	}

	return true
}

func (n *protobufNamer) AssignTypesToPackages(c *generator.Context) error {
	global := make(typeNameSet)
	for _, p := range n.packages {
		local := make(typeNameSet)
		optional := make(map[types.Name]struct{})
		p.Imports = NewImportTracker(p.ProtoTypeName())
		for _, t := range c.Order {
			if t.Name.Package != p.PackagePath {
				continue
			}
			if !isTypeApplicableToProtobuf(t) {
				// skip types that we don't care about, like functions
				continue
			}
			assignGoTypeToProtoPackage(p, t, local, global, optional)
		}
		p.FilterTypes = make(map[types.Name]struct{})
		p.LocalNames = make(map[string]struct{})
		p.OptionalTypeNames = make(map[string]struct{})
		for k, v := range local {
			if v == p {
				p.FilterTypes[k] = struct{}{}
				p.LocalNames[k.Name] = struct{}{}
				if _, ok := optional[k]; ok {
					p.OptionalTypeNames[k.Name] = struct{}{}
				}
			}
		}
	}
	return nil
}
<commit_msg>Fix Proto Generator to not assign types to packages they don't belong to<commit_after>/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package protobuf

import (
	"fmt"
	"reflect"
	"strings"

	"k8s.io/gengo/generator"
	"k8s.io/gengo/namer"
	"k8s.io/gengo/types"
)

type localNamer struct {
	localPackage types.Name
}

func (n localNamer) Name(t *types.Type) string {
	if t.Key != nil && t.Elem != nil {
		return fmt.Sprintf("map<%s, %s>", n.Name(t.Key), n.Name(t.Elem))
	}
	if len(n.localPackage.Package) != 0 && n.localPackage.Package == t.Name.Package {
		return t.Name.Name
	}
	return t.Name.String()
}

type protobufNamer struct {
	packages       []*protobufPackage
	packagesByPath map[string]*protobufPackage
}

func NewProtobufNamer() *protobufNamer {
	return &protobufNamer{
		packagesByPath: make(map[string]*protobufPackage),
	}
}

func (n *protobufNamer) Name(t *types.Type) string {
	if t.Kind == types.Map {
		return fmt.Sprintf("map<%s, %s>", n.Name(t.Key), n.Name(t.Elem))
	}
	return t.Name.String()
}

func (n *protobufNamer) List() []generator.Package {
	packages := make([]generator.Package, 0, len(n.packages))
	for i := range n.packages {
		packages = append(packages, n.packages[i])
	}
	return packages
}

func (n *protobufNamer) Add(p *protobufPackage) {
	if _, ok := n.packagesByPath[p.PackagePath]; !ok {
		n.packagesByPath[p.PackagePath] = p
		n.packages = append(n.packages, p)
	}
}

func (n *protobufNamer) GoNameToProtoName(name types.Name) types.Name {
	if p, ok := n.packagesByPath[name.Package]; ok {
		return types.Name{
			Name:    name.Name,
			Package: p.PackageName,
			Path:    p.ImportPath(),
		}
	}
	for _, p := range n.packages {
		if _, ok := p.FilterTypes[name]; ok {
			return types.Name{
				Name:    name.Name,
				Package: p.PackageName,
				Path:    p.ImportPath(),
			}
		}
	}
	return types.Name{Name: name.Name}
}

func protoSafePackage(name string) string {
	pkg := strings.Replace(name, "/", ".", -1)
	return strings.Replace(pkg, "-", "_", -1)
}

type typeNameSet map[types.Name]*protobufPackage

// assignGoTypeToProtoPackage looks for Go and Protobuf types that are referenced by a type in
// a package. It will not recurse into protobuf types.
func assignGoTypeToProtoPackage(p *protobufPackage, t *types.Type, local, global typeNameSet, optional map[types.Name]struct{}) {
	newT, isProto := isFundamentalProtoType(t)
	if isProto {
		t = newT
	}
	if otherP, ok := global[t.Name]; ok {
		if _, ok := local[t.Name]; !ok {
			p.Imports.AddType(&types.Type{
				Kind: types.Protobuf,
				Name: otherP.ProtoTypeName(),
			})
		}
		return
	}
	if t.Name.Package == p.PackagePath {
		// Associate types only to their own package
		global[t.Name] = p
	}
	if _, ok := local[t.Name]; ok {
		return
	}
	// don't recurse into existing proto types
	if isProto {
		p.Imports.AddType(t)
		return
	}

	local[t.Name] = p
	for _, m := range t.Members {
		if namer.IsPrivateGoName(m.Name) {
			continue
		}
		field := &protoField{}
		tag := reflect.StructTag(m.Tags).Get("protobuf")
		if tag == "-" {
			continue
		}
		if err := protobufTagToField(tag, field, m, t, p.ProtoTypeName()); err == nil && field.Type != nil {
			assignGoTypeToProtoPackage(p, field.Type, local, global, optional)
			continue
		}
		assignGoTypeToProtoPackage(p, m.Type, local, global, optional)
	}
	// TODO: should methods be walked?
	if t.Elem != nil {
		assignGoTypeToProtoPackage(p, t.Elem, local, global, optional)
	}
	if t.Key != nil {
		assignGoTypeToProtoPackage(p, t.Key, local, global, optional)
	}
	if t.Underlying != nil {
		if t.Kind == types.Alias && isOptionalAlias(t) {
			optional[t.Name] = struct{}{}
		}
		assignGoTypeToProtoPackage(p, t.Underlying, local, global, optional)
	}
}

// isTypeApplicableToProtobuf checks to see if a type is relevant for protobuf processing.
// Currently, it filters out functions and private types.
func isTypeApplicableToProtobuf(t *types.Type) bool {
	// skip functions -- we don't care about them for protobuf
	if t.Kind == types.Func || (t.Kind == types.DeclarationOf && t.Underlying.Kind == types.Func) {
		return false
	}
	// skip private types
	if namer.IsPrivateGoName(t.Name.Name) {
		return false
	}

	return true
}

func (n *protobufNamer) AssignTypesToPackages(c *generator.Context) error {
	global := make(typeNameSet)
	for _, p := range n.packages {
		local := make(typeNameSet)
		optional := make(map[types.Name]struct{})
		p.Imports = NewImportTracker(p.ProtoTypeName())
		for _, t := range c.Order {
			if t.Name.Package != p.PackagePath {
				continue
			}
			if !isTypeApplicableToProtobuf(t) {
				// skip types that we don't care about, like functions
				continue
			}
			assignGoTypeToProtoPackage(p, t, local, global, optional)
		}
		p.FilterTypes = make(map[types.Name]struct{})
		p.LocalNames = make(map[string]struct{})
		p.OptionalTypeNames = make(map[string]struct{})
		for k, v := range local {
			if v == p {
				p.FilterTypes[k] = struct{}{}
				p.LocalNames[k.Name] = struct{}{}
				if _, ok := optional[k]; ok {
					p.OptionalTypeNames[k.Name] = struct{}{}
				}
			}
		}
	}
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

// package kubectlcobra contains cobra commands from kubectl
package kubectlcobra

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/kubectl/pkg/cmd/apply"
	"k8s.io/kubectl/pkg/cmd/diff"
	"k8s.io/kubectl/pkg/cmd/util"
	cmdutil "k8s.io/kubectl/pkg/cmd/util"
	"k8s.io/kubectl/pkg/util/i18n"
	"sigs.k8s.io/kustomize/kyaml/commandutil"
)

// GetCommand returns a command from kubectl to install
func GetCommand(parent *cobra.Command) *cobra.Command {
	if !commandutil.GetAlphaEnabled() {
		return &cobra.Command{
			Use:   "resources",
			Short: "[Alpha] To enable set KUSTOMIZE_ENABLE_ALPHA_COMMANDS=true",
			Long:  "[Alpha] To enable set KUSTOMIZE_ENABLE_ALPHA_COMMANDS=true",
		}
	}

	r := &cobra.Command{
		Use:   "resources",
		Short: "[Alpha] Perform cluster operations using declarative configuration",
		Long:  "[Alpha] Perform cluster operations using declarative configuration",
	}

	// configure kubectl dependencies and flags
	flags := r.Flags()
	kubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
	kubeConfigFlags.AddFlags(flags)
	matchVersionKubeConfigFlags := util.NewMatchVersionFlags(kubeConfigFlags)
	matchVersionKubeConfigFlags.AddFlags(r.PersistentFlags())
	r.PersistentFlags().AddGoFlagSet(flag.CommandLine)
	f := util.NewFactory(matchVersionKubeConfigFlags)

	var ioStreams genericclioptions.IOStreams

	if parent != nil {
		ioStreams.In = parent.InOrStdin()
		ioStreams.Out = parent.OutOrStdout()
		ioStreams.ErrOut = parent.ErrOrStderr()
	} else {
		ioStreams.In = os.Stdin
		ioStreams.Out = os.Stdout
		ioStreams.ErrOut = os.Stderr
	}

	names := []string{"apply", "diff"}
	applyCmd := NewCmdApply("kustomize", f, ioStreams)
	updateHelp(names, applyCmd)
	diffCmd := diff.NewCmdDiff(f, ioStreams)
	updateHelp(names, diffCmd)

	r.AddCommand(applyCmd, diffCmd)
	return r
}

// updateHelp replaces `kubectl` help messaging with `kustomize` help messaging
func updateHelp(names []string, c *cobra.Command) {
	for i := range names {
		name := names[i]
		c.Short = strings.ReplaceAll(c.Short, "kubectl "+name, "kustomize "+name)
		c.Long = strings.ReplaceAll(c.Long, "kubectl "+name, "kustomize "+name)
		c.Example = strings.ReplaceAll(c.Example, "kubectl "+name, "kustomize "+name)
	}
}

// NewCmdApply creates the `apply` command
func NewCmdApply(baseName string, f util.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := apply.NewApplyOptions(ioStreams)
	so := newStatusOptions(f, ioStreams)
	o.PreProcessorFn = PrependGroupingObject(o)

	cmd := &cobra.Command{
		Use:                   "apply (-f FILENAME | -k DIRECTORY)",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Apply a configuration to a resource by filename or stdin"),
		//Long:                  applyLong,
		//Example:               applyExample,
		Args: cobra.MaximumNArgs(1),
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) > 0 {
				// check is kustomize, if so update
				o.DeleteFlags.FileNameFlags.Kustomize = &args[0]
			}

			cmdutil.CheckErr(o.Complete(f, cmd))
			cmdutil.CheckErr(o.Run())
			infos, _ := o.GetObjects()
			if so.wait {
				cmdutil.CheckErr(so.waitForStatus(infos))
			}
		},
	}

	// bind flag structs
	o.DeleteFlags.AddFlags(cmd)
	o.RecordFlags.AddFlags(cmd)
	o.PrintFlags.AddFlags(cmd)
	so.AddFlags(cmd)

	o.Overwrite = true

	cmdutil.AddValidateFlags(cmd)
	cmd.Flags().BoolVar(&o.ServerDryRun, "server-dry-run", o.ServerDryRun, "If true, request will be sent to server with dry-run flag, which means the modifications won't be persisted. This is an alpha feature and flag.")
	cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without sending it. Warning: --dry-run cannot accurately output the result of merging the local manifest and the server-side data. Use --server-dry-run to get the merged result instead.")
	cmdutil.AddServerSideApplyFlags(cmd)

	return cmd
}

// PrependGroupingObject orders the objects to apply so the "grouping"
// object stores the inventory, and it is first to be applied.
func PrependGroupingObject(o *apply.ApplyOptions) func() error {
	return func() error {
		if o == nil {
			return fmt.Errorf("ApplyOptions are nil")
		}
		infos, err := o.GetObjects()
		if err != nil {
			return err
		}
		_, exists := findGroupingObject(infos)
		if exists {
			if err := addInventoryToGroupingObj(infos); err != nil {
				return err
			}
			if !sortGroupingObject(infos) {
				return err
			}
		}
		return nil
	}
}
<commit_msg>Connect prune to apply<commit_after>// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

// package kubectlcobra contains cobra commands from kubectl
package kubectlcobra

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/kubectl/pkg/cmd/apply"
	"k8s.io/kubectl/pkg/cmd/diff"
	"k8s.io/kubectl/pkg/cmd/util"
	cmdutil "k8s.io/kubectl/pkg/cmd/util"
	"k8s.io/kubectl/pkg/util/i18n"
	"sigs.k8s.io/kustomize/kyaml/commandutil"
)

// GetCommand returns a command from kubectl to install
func GetCommand(parent *cobra.Command) *cobra.Command {
	if !commandutil.GetAlphaEnabled() {
		return &cobra.Command{
			Use:   "resources",
			Short: "[Alpha] To enable set KUSTOMIZE_ENABLE_ALPHA_COMMANDS=true",
			Long:  "[Alpha] To enable set KUSTOMIZE_ENABLE_ALPHA_COMMANDS=true",
		}
	}

	r := &cobra.Command{
		Use:   "resources",
		Short: "[Alpha] Perform cluster operations using declarative configuration",
		Long:  "[Alpha] Perform cluster operations using declarative configuration",
	}

	// configure kubectl dependencies and flags
	flags := r.Flags()
	kubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
	kubeConfigFlags.AddFlags(flags)
	matchVersionKubeConfigFlags := util.NewMatchVersionFlags(kubeConfigFlags)
	matchVersionKubeConfigFlags.AddFlags(r.PersistentFlags())
	r.PersistentFlags().AddGoFlagSet(flag.CommandLine)
	f := util.NewFactory(matchVersionKubeConfigFlags)

	var ioStreams genericclioptions.IOStreams

	if parent != nil {
		ioStreams.In = parent.InOrStdin()
		ioStreams.Out = parent.OutOrStdout()
		ioStreams.ErrOut = parent.ErrOrStderr()
	} else {
		ioStreams.In = os.Stdin
		ioStreams.Out = os.Stdout
		ioStreams.ErrOut = os.Stderr
	}

	names := []string{"apply", "diff"}
	applyCmd := NewCmdApply("kustomize", f, ioStreams)
	updateHelp(names, applyCmd)
	diffCmd := diff.NewCmdDiff(f, ioStreams)
	updateHelp(names, diffCmd)

	r.AddCommand(applyCmd, diffCmd)
	return r
}

// updateHelp replaces `kubectl` help messaging with `kustomize` help messaging
func updateHelp(names []string, c *cobra.Command) {
	for i := range names {
		name := names[i]
		c.Short = strings.ReplaceAll(c.Short, "kubectl "+name, "kustomize "+name)
		c.Long = strings.ReplaceAll(c.Long, "kubectl "+name, "kustomize "+name)
		c.Example = strings.ReplaceAll(c.Example, "kubectl "+name, "kustomize "+name)
	}
}

// NewCmdApply creates the `apply` command
func NewCmdApply(baseName string, f util.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := apply.NewApplyOptions(ioStreams)
	so := newStatusOptions(f, ioStreams)
	// Set up grouping object for this apply; used in subsequent prune.
	o.PreProcessorFn = PrependGroupingObject(o)

	cmd := &cobra.Command{
		Use:                   "apply (-f FILENAME | -k DIRECTORY)",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Apply a configuration to a resource by filename or stdin"),
		//Long:                  applyLong,
		//Example:               applyExample,
		Args: cobra.MaximumNArgs(1),
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) > 0 {
				// check is kustomize, if so update
				o.DeleteFlags.FileNameFlags.Kustomize = &args[0]
			}

			cmdutil.CheckErr(o.Complete(f, cmd))
			// Default PostProcessor is configured in "Complete" function,
			// so the prune must happen after "Complete".
			o.PostProcessorFn = prune(f, o)
			cmdutil.CheckErr(o.Run())
			infos, _ := o.GetObjects()
			if so.wait {
				cmdutil.CheckErr(so.waitForStatus(infos))
			}
		},
	}

	// bind flag structs
	o.DeleteFlags.AddFlags(cmd)
	o.RecordFlags.AddFlags(cmd)
	o.PrintFlags.AddFlags(cmd)
	so.AddFlags(cmd)

	o.Overwrite = true

	cmdutil.AddValidateFlags(cmd)
	cmd.Flags().BoolVar(&o.ServerDryRun, "server-dry-run", o.ServerDryRun, "If true, request will be sent to server with dry-run flag, which means the modifications won't be persisted. This is an alpha feature and flag.")
	cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without sending it. Warning: --dry-run cannot accurately output the result of merging the local manifest and the server-side data. Use --server-dry-run to get the merged result instead.")
	cmdutil.AddServerSideApplyFlags(cmd)

	return cmd
}

// PrependGroupingObject orders the objects to apply so the "grouping"
// object stores the inventory, and it is first to be applied.
func PrependGroupingObject(o *apply.ApplyOptions) func() error {
	return func() error {
		if o == nil {
			return fmt.Errorf("ApplyOptions are nil")
		}
		infos, err := o.GetObjects()
		if err != nil {
			return err
		}
		_, exists := findGroupingObject(infos)
		if exists {
			if err := addInventoryToGroupingObj(infos); err != nil {
				return err
			}
			if !sortGroupingObject(infos) {
				return err
			}
		}
		return nil
	}
}

// Prune deletes previously applied objects that have been
// omitted in the current apply. The previously applied objects
// are reached through ConfigMap grouping objects.
func prune(f util.Factory, o *apply.ApplyOptions) func() error {
	return func() error {
		po, err := NewPruneOptions(f, o)
		if err != nil {
			return err
		}
		return po.Prune()
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/masci/flickr"
	"github.com/masci/flickr/photosets"
)

func main() {
	// retrieve Flickr credentials from env vars
	apik := os.Getenv("FLICKRGO_API_KEY")
	apisec := os.Getenv("FLICKRGO_API_SECRET")
	token := os.Getenv("FLICKRGO_OAUTH_TOKEN")
	tokenSecret := os.Getenv("FLICKRGO_OAUTH_TOKEN_SECRET")
	nsid := os.Getenv("FLICKRGO_USER_ID")

	// do not proceed if credentials were not provided
	if apik == "" || apisec == "" || token == "" || tokenSecret == "" {
		fmt.Fprintln(os.Stderr, "Please set FLICKRGO_API_KEY, FLICKRGO_API_SECRET "+
			"and FLICKRGO_OAUTH_TOKEN, FLICKRGO_OAUTH_TOKEN_SECRET env vars")
		os.Exit(1)
	}

	// create an API client with credentials
	client := flickr.NewFlickrClient(apik, apisec)
	client.OAuthToken = token
	client.OAuthTokenSecret = tokenSecret
	client.Id = nsid

	/*
		response, _ := photosets.GetList(client, false, "23148015@N00", 1)
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.GetPhotos(client, false, "72157632076344815", "23148015@N00", 1)
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.EditMeta(client, "72157654143356943", "bar", "Baz")
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.EditPhotos(client, "72157654143356943", "9518691684", []string{"9518691684", "19681581995"})
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.RemovePhotos(client, "72157654143356943", []string{"9518691684", "19681581995"})
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.SetPrimaryPhoto(client, "72157656097802609", "16438207896")
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.OrderSets(client, []string{"72157656097802609"})
		fmt.Println(fmt.Sprintf("%+v", *response))
	*/

	response, _ := photosets.GetInfo(client, true, "72157656097802609", "")
	fmt.Println(fmt.Sprintf("%+v", *response))
}
<commit_msg>change output<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/masci/flickr"
	"github.com/masci/flickr/photosets"
)

func main() {
	// retrieve Flickr credentials from env vars
	apik := os.Getenv("FLICKRGO_API_KEY")
	apisec := os.Getenv("FLICKRGO_API_SECRET")
	token := os.Getenv("FLICKRGO_OAUTH_TOKEN")
	tokenSecret := os.Getenv("FLICKRGO_OAUTH_TOKEN_SECRET")
	nsid := os.Getenv("FLICKRGO_USER_ID")

	// do not proceed if credentials were not provided
	if apik == "" || apisec == "" || token == "" || tokenSecret == "" {
		fmt.Fprintln(os.Stderr, "Please set FLICKRGO_API_KEY, FLICKRGO_API_SECRET "+
			"and FLICKRGO_OAUTH_TOKEN, FLICKRGO_OAUTH_TOKEN_SECRET env vars")
		os.Exit(1)
	}

	// create an API client with credentials
	client := flickr.NewFlickrClient(apik, apisec)
	client.OAuthToken = token
	client.OAuthTokenSecret = tokenSecret
	client.Id = nsid

	/*
		response, _ := photosets.GetList(client, false, "23148015@N00", 1)
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.GetPhotos(client, false, "72157632076344815", "23148015@N00", 1)
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.EditMeta(client, "72157654143356943", "bar", "Baz")
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.EditPhotos(client, "72157654143356943", "9518691684", []string{"9518691684", "19681581995"})
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.RemovePhotos(client, "72157654143356943", []string{"9518691684", "19681581995"})
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.SetPrimaryPhoto(client, "72157656097802609", "16438207896")
		fmt.Println(fmt.Sprintf("%+v", *response))

		response, _ := photosets.OrderSets(client, []string{"72157656097802609"})
		fmt.Println(fmt.Sprintf("%+v", *response))
	*/

	response, _ := photosets.GetInfo(client, true, "72157656097802609", "")
	fmt.Println(response.Set.Title)
}
<|endoftext|>