<commit_before>package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/nicksnyder/go-i18n/i18n"
	"html/template"
	"net/http"
	"net/url"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
)

// The location of the configuration file to read.
const CONFIG_FILE string = "./config/client.json"

// A global configuration instance. Must be instantiated properly in main().
var Configuration Config

// Verifies a URL as valid (enough)
const URL_REGEX = "(https?://)?(www\\.)?\\w+\\.\\w+"

// The header used to communicate from the browser extension to the bundle server
// that a request for http://site.com was rewritten from one for https://site.com.
const REWRITTEN_HEADER = "X-Ceno-Rewritten"

// Result of a bundle lookup from cache server.
type Result struct {
	ErrCode  ErrorCode
	ErrMsg   string
	Complete bool
	Found    bool
	Bundle   string
}

/**
 * Set a header on responses that indicates that the response was served by the CENO client.
 * Useful for checking if the CENO Client is running via an HTTP request.
 * @param {ResponseWriter} w - The ResponseWriter used to serve the current request's response.
 */
func WriteProxyHeader(w http.ResponseWriter) http.ResponseWriter {
	w.Header().Add("X-Ceno-Proxy", "yxorP-oneC-X")
	return w
}

/**
 * Serve a page to inform the user that the bundle for the site they requested is being prepared.
 * This function terminates requests.
 * @param {string} URL - The URL that was originally requested
 * @param {ResponseWriter} w - The object handling writing to the client
 */
func pleaseWait(URL string, w http.ResponseWriter) {
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	t, err := template.ParseFiles(path.Join(".", "views", "wait.html"))
	if err != nil {
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte(T("please_wait_txt")))
	} else {
		w.Header().Set("Content-Type", "text/html")
		t.Execute(w, map[string]string{
			"PrepareMessage": T("please_wait_header_html"),
			"Paragraph1":     T("please_wait_p1_html"),
			"Paragraph2":     T("please_wait_p2_html"),
			"Retry":          T("retry_html"),
			"Contact":        T("contact_html"),
			"Redirect":       URL,
		})
	}
}

/**
 * Request that the LCS start a lookup process for a particular URL.
 * @param {string} lookupURL - The URL to try to find in the distributed cache
 */
func lookup(lookupURL string) Result {
	response, err := http.Get(BundleLookupURL(Configuration, lookupURL))
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if err != nil {
		fmt.Println(T("error_cli", map[string]interface{}{
			"Message": err.Error(),
		}))
		return Result{ERR_NO_CONNECT_LCS, err.Error(), false, false, ""}
	} else if response == nil || response.StatusCode != 200 {
		errMsg := T("lcs_not_ready_cli")
		fmt.Println(errMsg)
		return Result{ERR_LCS_NOT_READY, errMsg, false, false, ""}
	}
	decoder := json.NewDecoder(response.Body)
	var result Result
	err = decoder.Decode(&result)
	if err != nil {
		decodeErrorMessage := T("decode_error_cli", map[string]interface{}{
			"Message": err.Error(),
		})
		fmt.Println(decodeErrorMessage)
		reachedLCS := HandleCCError(ERR_MALFORMED_LCS_RESPONSE, err.Error(), ErrorState{
			"requestURL": DecodeErrReportURL(Configuration),
		})
		if reachedLCS {
			return Result{ERR_MALFORMED_LCS_RESPONSE, decodeErrorMessage, false, false, ""}
		} else {
			errMsg := T("no_reach_lcs_cli")
			return Result{ERR_NO_CONNECT_LCS, errMsg, false, false, ""}
		}
	}
	return result
}

/**
 * Request that the RS issue a request to create a new bundle.
 * @param {string} lookupURL - The URL of the site to create a bundle for
 * @param {bool} wasRewritten - True if the requested URL was rewritten from HTTPS to HTTP
 */
func requestNewBundle(lookupURL string, wasRewritten bool) error {
	// We can ignore the content of the response since it is not used.
	reader := bytes.NewReader([]byte(lookupURL))
	URL := CreateBundleURL(Configuration, lookupURL)
	req, err := http.NewRequest("POST", URL, reader)
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "text/plain")
	req.Header.Set(REWRITTEN_HEADER, strconv.FormatBool(wasRewritten))
	client := &http.Client{}
	_, err2 := client.Do(req)
	return err2
}

/**
 * Strip out the S in HTTPS from URLs provided to the CC via the /lookup path.
 * Returns the written URL and a boolean indicating whether the downgrade was made.
 * @param {string} URL - The decoded (from b64) URL being requested
 */
func stripHttps(URL string) (string, bool) {
	if strings.Index(URL, "https") != 0 {
		return URL, false
	} else {
		return strings.Replace(URL, "https", "http", 1), true
	}
}

/**
 * Handle requests of the form `http://127.0.0.1:3090/lookup?url=<base64-enc-url>`
 * so that we can simplify the problem of certain browsers trying particularly hard
 * to enforce HTTPS.  Rather than trying to deal with infinite redirecting between
 * HTTP and HTTPS, we can make requests directly to the client.
 * @param {ResponseWriter} w - The object used to handle writing responses to the client
 * @param {*Request} r - Information about the request
 */
func directHandler(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	URLS, found := qs["url"]
	if !found {
		HandleCCError(ERR_MALFORMED_URL, T("querystring_no_url_cli"), ErrorState{
			"responseWriter": w,
			"request":        r,
		})
	} else {
		// Decode the URL so we can save effort by just passing the modified request to
		// the proxyHandler function from here.
		decodedBytes, err := base64.StdEncoding.DecodeString(URLS[0])
		if err != nil {
			HandleCCError(ERR_MALFORMED_URL, T("url_b64_cli"), ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		} else {
			decodedURL := string(decodedBytes)
			stripped, rewritten := stripHttps(decodedURL)
			if rewritten {
				r.Header.Set(REWRITTEN_HEADER, "true")
			}
			newURL, parseErr := url.Parse(stripped)
			if parseErr != nil {
				HandleCCError(ERR_MALFORMED_URL, T("malformed_url_cli", map[string]interface{}{
					"URL": stripped,
				}), ErrorState{"responseWriter": w, "request": r})
			} else {
				// Finally we can pass the modified request onto the proxy server.
				r.URL = newURL
				proxyHandler(w, r)
			}
		}
	}
}

/**
 * Check if a provided URL is well-formed.  If not, serve an error page.
 * This call terminates requests when the return value is false (i.e. invalid URL).
 * @param {string} URL - The URL being requested
 * @param {ResponseWriter} w - The object handling writing responses to the client
 * @param {*Request} r - Information about the request
 */
func validateURL(URL string, w http.ResponseWriter, r *http.Request) bool {
	isValid, err := regexp.MatchString(URL_REGEX, URL)
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if !isValid || err != nil {
		HandleCCError(ERR_MALFORMED_URL, T("malformed_url_cli", map[string]interface{}{
			"URL": URL,
		}), ErrorState{"responseWriter": w, "request": r})
		return false
	}
	return true
}

/**
 * Try to request a new bundle be created and serve the please wait page.
 * This function should terminate requests.
 * @param {string} URL - The URL to POST to to request a new bundle
 * @param {bool} rewritten - True if the request was downgraded from HTTPS to HTTP else false
 * @param {ResponseWriter} w - the object handling responding to the client
 * @param {*Request} r - Information about the request
 */
func tryRequestBundle(URL string, rewritten bool, w http.ResponseWriter, r *http.Request) {
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if err := requestNewBundle(URL, rewritten); err != nil {
		fmt.Println(T("bundle_err_cli", map[string]interface{}{
			"Message": err.Error(),
		}))
		HandleLCSError(ERR_NO_CONNECT_RS, err.Error(), ErrorState{
			"responseWriter": w,
			"request":        r,
		})
	} else {
		pleaseWait(URL, w)
	}
}

/**
 * Handle incoming requests for bundles.
 * 1. Initiate bundle lookup process
 * 2. Initiate bundle creation process when no bundle exists anywhere
 * @param {ResponseWriter} w - The object handling responding to the client
 * @param {*Request} r - Information about the request
 */
func proxyHandler(w http.ResponseWriter, r *http.Request) {
	w = WriteProxyHeader(w)
	URL := r.URL.String()
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	wasRewritten := r.Header.Get(REWRITTEN_HEADER) == "true"
	fmt.Println(T("got_request_msg_cli", map[string]interface{}{
		"URL":       URL,
		"Rewritten": wasRewritten,
	}))
	if isValidURL := validateURL(URL, w, r); !isValidURL {
		return
	}
	result := lookup(URL)
	if result.ErrCode > 0 {
		fmt.Println(T("err_from_lcs_cli", map[string]interface{}{
			"Code":    result.ErrCode,
			"Message": result.ErrMsg,
		}))
		// Assuming the reason the response is malformed is because of the formation of the bundle,
		// so we will request that a new bundle be created.
		if result.ErrCode == ERR_MALFORMED_LCS_RESPONSE {
			tryRequestBundle(URL, wasRewritten, w, r)
		} else if IsCacheServerError(result.ErrCode) {
			HandleLCSError(result.ErrCode, result.ErrMsg, ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		} else {
			HandleCCError(result.ErrCode, result.ErrMsg, ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		}
	} else if result.Complete {
		if result.Found {
			w.Write([]byte(result.Bundle))
		} else {
			tryRequestBundle(URL, wasRewritten, w, r)
		}
	} else {
		pleaseWait(URL, w)
	}
}

func main() {
	// Configure the i18n library to use the preferred language set in the CENOLANG environement variable
	setLanguage := os.Getenv("CENOLANG")
	if setLanguage == "" {
		os.Setenv("CENOLANG", "en-us")
		setLanguage = "en-us"
	}
	i18n.MustLoadTranslationFile("./translations/" + setLanguage + ".all.json")
	T, _ := i18n.Tfunc(setLanguage, "en-us")
	// Read an existing configuration file or have the user supply settings
	if conf, err := ReadConfigFile(CONFIG_FILE); err != nil {
		fmt.Println(T("no_config_cli", map[string]interface{}{"Location": CONFIG_FILE}))
		Configuration = GetConfigFromUser()
	} else {
		Configuration = conf
	}
	// Create an HTTP proxy server
	http.HandleFunc("/lookup", directHandler)
	http.HandleFunc("/", proxyHandler)
	fmt.Println(T("listening_msg_cli", map[string]interface{}{"Port": Configuration.PortNumber}))
	err := http.ListenAndServe(Configuration.PortNumber, nil)
	if err != nil {
		panic(err)
	}
    fmt.Println("Hi mom!")
}
<commit_msg>Revert "Commit for CI"<commit_after>package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/nicksnyder/go-i18n/i18n"
	"html/template"
	"net/http"
	"net/url"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
)

// The location of the configuration file to read.
const CONFIG_FILE string = "./config/client.json"

// A global configuration instance. Must be instantiated properly in main().
var Configuration Config

// Verifies a URL as valid (enough)
const URL_REGEX = "(https?://)?(www\\.)?\\w+\\.\\w+"

// The header used to communicate from the browser extension to the bundle server
// that a request for http://site.com was rewritten from one for https://site.com.
const REWRITTEN_HEADER = "X-Ceno-Rewritten"

// Result of a bundle lookup from cache server.
type Result struct {
	ErrCode  ErrorCode
	ErrMsg   string
	Complete bool
	Found    bool
	Bundle   string
}

/**
 * Set a header on responses that indicates that the response was served by the CENO client.
 * Useful for checking if the CENO Client is running via an HTTP request.
 * @param {ResponseWriter} w - The ResponseWriter used to serve the current request's response.
 */
func WriteProxyHeader(w http.ResponseWriter) http.ResponseWriter {
	w.Header().Add("X-Ceno-Proxy", "yxorP-oneC-X")
	return w
}

/**
 * Serve a page to inform the user that the bundle for the site they requested is being prepared.
 * This function terminates requests.
 * @param {string} URL - The URL that was originally requested
 * @param {ResponseWriter} w - The object handling writing to the client
 */
func pleaseWait(URL string, w http.ResponseWriter) {
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	t, err := template.ParseFiles(path.Join(".", "views", "wait.html"))
	if err != nil {
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte(T("please_wait_txt")))
	} else {
		w.Header().Set("Content-Type", "text/html")
		t.Execute(w, map[string]string{
			"PrepareMessage": T("please_wait_header_html"),
			"Paragraph1":     T("please_wait_p1_html"),
			"Paragraph2":     T("please_wait_p2_html"),
			"Retry":          T("retry_html"),
			"Contact":        T("contact_html"),
			"Redirect":       URL,
		})
	}
}

/**
 * Request that the LCS start a lookup process for a particular URL.
 * @param {string} lookupURL - The URL to try to find in the distributed cache
 */
func lookup(lookupURL string) Result {
	response, err := http.Get(BundleLookupURL(Configuration, lookupURL))
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if err != nil {
		fmt.Println(T("error_cli", map[string]interface{}{
			"Message": err.Error(),
		}))
		return Result{ERR_NO_CONNECT_LCS, err.Error(), false, false, ""}
	} else if response == nil || response.StatusCode != 200 {
		errMsg := T("lcs_not_ready_cli")
		fmt.Println(errMsg)
		return Result{ERR_LCS_NOT_READY, errMsg, false, false, ""}
	}
	decoder := json.NewDecoder(response.Body)
	var result Result
	err = decoder.Decode(&result)
	if err != nil {
		decodeErrorMessage := T("decode_error_cli", map[string]interface{}{
			"Message": err.Error(),
		})
		fmt.Println(decodeErrorMessage)
		reachedLCS := HandleCCError(ERR_MALFORMED_LCS_RESPONSE, err.Error(), ErrorState{
			"requestURL": DecodeErrReportURL(Configuration),
		})
		if reachedLCS {
			return Result{ERR_MALFORMED_LCS_RESPONSE, decodeErrorMessage, false, false, ""}
		} else {
			errMsg := T("no_reach_lcs_cli")
			return Result{ERR_NO_CONNECT_LCS, errMsg, false, false, ""}
		}
	}
	return result
}

/**
 * Request that the RS issue a request to create a new bundle.
 * @param {string} lookupURL - The URL of the site to create a bundle for
 * @param {bool} wasRewritten - True if the requested URL was rewritten from HTTPS to HTTP
 */
func requestNewBundle(lookupURL string, wasRewritten bool) error {
	// We can ignore the content of the response since it is not used.
	reader := bytes.NewReader([]byte(lookupURL))
	URL := CreateBundleURL(Configuration, lookupURL)
	req, err := http.NewRequest("POST", URL, reader)
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "text/plain")
	req.Header.Set(REWRITTEN_HEADER, strconv.FormatBool(wasRewritten))
	client := &http.Client{}
	_, err2 := client.Do(req)
	return err2
}

/**
 * Strip out the S in HTTPS from URLs provided to the CC via the /lookup path.
 * Returns the written URL and a boolean indicating whether the downgrade was made.
 * @param {string} URL - The decoded (from b64) URL being requested
 */
func stripHttps(URL string) (string, bool) {
	if strings.Index(URL, "https") != 0 {
		return URL, false
	} else {
		return strings.Replace(URL, "https", "http", 1), true
	}
}

/**
 * Handle requests of the form `http://127.0.0.1:3090/lookup?url=<base64-enc-url>`
 * so that we can simplify the problem of certain browsers trying particularly hard
 * to enforce HTTPS.  Rather than trying to deal with infinite redirecting between
 * HTTP and HTTPS, we can make requests directly to the client.
 * @param {ResponseWriter} w - The object used to handle writing responses to the client
 * @param {*Request} r - Information about the request
 */
func directHandler(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	URLS, found := qs["url"]
	if !found {
		HandleCCError(ERR_MALFORMED_URL, T("querystring_no_url_cli"), ErrorState{
			"responseWriter": w,
			"request":        r,
		})
	} else {
		// Decode the URL so we can save effort by just passing the modified request to
		// the proxyHandler function from here.
		decodedBytes, err := base64.StdEncoding.DecodeString(URLS[0])
		if err != nil {
			HandleCCError(ERR_MALFORMED_URL, T("url_b64_cli"), ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		} else {
			decodedURL := string(decodedBytes)
			stripped, rewritten := stripHttps(decodedURL)
			if rewritten {
				r.Header.Set(REWRITTEN_HEADER, "true")
			}
			newURL, parseErr := url.Parse(stripped)
			if parseErr != nil {
				HandleCCError(ERR_MALFORMED_URL, T("malformed_url_cli", map[string]interface{}{
					"URL": stripped,
				}), ErrorState{"responseWriter": w, "request": r})
			} else {
				// Finally we can pass the modified request onto the proxy server.
				r.URL = newURL
				proxyHandler(w, r)
			}
		}
	}
}

/**
 * Check if a provided URL is well-formed.  If not, serve an error page.
 * This call terminates requests when the return value is false (i.e. invalid URL).
 * @param {string} URL - The URL being requested
 * @param {ResponseWriter} w - The object handling writing responses to the client
 * @param {*Request} r - Information about the request
 */
func validateURL(URL string, w http.ResponseWriter, r *http.Request) bool {
	isValid, err := regexp.MatchString(URL_REGEX, URL)
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if !isValid || err != nil {
		HandleCCError(ERR_MALFORMED_URL, T("malformed_url_cli", map[string]interface{}{
			"URL": URL,
		}), ErrorState{"responseWriter": w, "request": r})
		return false
	}
	return true
}

/**
 * Try to request a new bundle be created and serve the please wait page.
 * This function should terminate requests.
 * @param {string} URL - The URL to POST to to request a new bundle
 * @param {bool} rewritten - True if the request was downgraded from HTTPS to HTTP else false
 * @param {ResponseWriter} w - the object handling responding to the client
 * @param {*Request} r - Information about the request
 */
func tryRequestBundle(URL string, rewritten bool, w http.ResponseWriter, r *http.Request) {
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if err := requestNewBundle(URL, rewritten); err != nil {
		fmt.Println(T("bundle_err_cli", map[string]interface{}{
			"Message": err.Error(),
		}))
		HandleLCSError(ERR_NO_CONNECT_RS, err.Error(), ErrorState{
			"responseWriter": w,
			"request":        r,
		})
	} else {
		pleaseWait(URL, w)
	}
}

/**
 * Handle incoming requests for bundles.
 * 1. Initiate bundle lookup process
 * 2. Initiate bundle creation process when no bundle exists anywhere
 * @param {ResponseWriter} w - The object handling responding to the client
 * @param {*Request} r - Information about the request
 */
func proxyHandler(w http.ResponseWriter, r *http.Request) {
	w = WriteProxyHeader(w)
	URL := r.URL.String()
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	wasRewritten := r.Header.Get(REWRITTEN_HEADER) == "true"
	fmt.Println(T("got_request_msg_cli", map[string]interface{}{
		"URL":       URL,
		"Rewritten": wasRewritten,
	}))
	if isValidURL := validateURL(URL, w, r); !isValidURL {
		return
	}
	result := lookup(URL)
	if result.ErrCode > 0 {
		fmt.Println(T("err_from_lcs_cli", map[string]interface{}{
			"Code":    result.ErrCode,
			"Message": result.ErrMsg,
		}))
		// Assuming the reason the response is malformed is because of the formation of the bundle,
		// so we will request that a new bundle be created.
		if result.ErrCode == ERR_MALFORMED_LCS_RESPONSE {
			tryRequestBundle(URL, wasRewritten, w, r)
		} else if IsCacheServerError(result.ErrCode) {
			HandleLCSError(result.ErrCode, result.ErrMsg, ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		} else {
			HandleCCError(result.ErrCode, result.ErrMsg, ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		}
	} else if result.Complete {
		if result.Found {
			w.Write([]byte(result.Bundle))
		} else {
			tryRequestBundle(URL, wasRewritten, w, r)
		}
	} else {
		pleaseWait(URL, w)
	}
}

func main() {
	// Configure the i18n library to use the preferred language set in the CENOLANG environement variable
	setLanguage := os.Getenv("CENOLANG")
	if setLanguage == "" {
		os.Setenv("CENOLANG", "en-us")
		setLanguage = "en-us"
	}
	i18n.MustLoadTranslationFile("./translations/" + setLanguage + ".all.json")
	T, _ := i18n.Tfunc(setLanguage, "en-us")
	// Read an existing configuration file or have the user supply settings
	if conf, err := ReadConfigFile(CONFIG_FILE); err != nil {
		fmt.Println(T("no_config_cli", map[string]interface{}{"Location": CONFIG_FILE}))
		Configuration = GetConfigFromUser()
	} else {
		Configuration = conf
	}
	// Create an HTTP proxy server
	http.HandleFunc("/lookup", directHandler)
	http.HandleFunc("/", proxyHandler)
	fmt.Println(T("listening_msg_cli", map[string]interface{}{"Port": Configuration.PortNumber}))
	err := http.ListenAndServe(Configuration.PortNumber, nil)
	if err != nil {
		panic(err)
	}
}
<|endoftext|>


<commit_before>package commands

import (
	"fmt"

	"code.cloudfoundry.org/cli/cf/api/organizations"
	"code.cloudfoundry.org/cli/cf/api/spaces"
	"code.cloudfoundry.org/cli/cf/commandregistry"
	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
	"code.cloudfoundry.org/cli/cf/errors"
	"code.cloudfoundry.org/cli/cf/flags"
	. "code.cloudfoundry.org/cli/cf/i18n"
	"code.cloudfoundry.org/cli/cf/models"
	"code.cloudfoundry.org/cli/cf/requirements"
	"code.cloudfoundry.org/cli/cf/terminal"
)

type Target struct {
	ui        terminal.UI
	config    coreconfig.ReadWriter
	orgRepo   organizations.OrganizationRepository
	spaceRepo spaces.SpaceRepository
}

func init() {
	commandregistry.Register(&Target{})
}

func (cmd *Target) MetaData() commandregistry.CommandMetadata {
	fs := make(map[string]flags.FlagSet)
	fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Organization")}
	fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")}

	return commandregistry.CommandMetadata{
		Name:        "target",
		ShortName:   "t",
		Description: T("Set or view the targeted org or space"),
		Usage: []string{
			T("CF_NAME target [-o ORG] [-s SPACE]"),
		},
		Flags: fs,
	}
}

func (cmd *Target) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	usageReq := requirements.NewUsageRequirement(commandregistry.CLICommandUsagePresenter(cmd),
		T("No argument required"),
		func() bool {
			return len(fc.Args()) != 0
		},
	)

	reqs := []requirements.Requirement{
		usageReq,
		requirementsFactory.NewAPIEndpointRequirement(),
	}

	if fc.IsSet("o") || fc.IsSet("s") {
		reqs = append(reqs, requirementsFactory.NewLoginRequirement())
	}

	return reqs, nil
}

func (cmd *Target) SetDependency(deps commandregistry.Dependency, _ bool) commandregistry.Command {
	cmd.ui = deps.UI
	cmd.config = deps.Config
	cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
	cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository()
	return cmd
}

func (cmd *Target) Execute(c flags.FlagContext) error {
	orgName := c.String("o")
	spaceName := c.String("s")

	if orgName != "" {
		err := cmd.setOrganization(orgName)
		if err != nil {
			return err
		} else if spaceName == "" {
			spaceList, apiErr := cmd.getSpaceList()
			if apiErr == nil && len(spaceList) == 1 {
				cmd.setSpace(spaceList[0].Name)
			}
		}
	}

	if spaceName != "" {
		err := cmd.setSpace(spaceName)
		if err != nil {
			return err
		}
	}

	err := cmd.ui.ShowConfiguration(cmd.config)
	if err != nil {
		return err
	}
	cmd.ui.NotifyUpdateIfNeeded(cmd.config)
	if !cmd.config.IsLoggedIn() {
		return fmt.Errorf(terminal.NotLoggedInText())
	}
	return nil
}

func (cmd Target) setOrganization(orgName string) error {
	// setting an org necessarily invalidates any space you had previously targeted
	cmd.config.SetOrganizationFields(models.OrganizationFields{})
	cmd.config.SetSpaceFields(models.SpaceFields{})

	org, apiErr := cmd.orgRepo.FindByName(orgName)
	if apiErr != nil {
		return fmt.Errorf(T("Could not target org.\n{{.APIErr}}",
			map[string]interface{}{"APIErr": apiErr.Error()}))
	}

	cmd.config.SetOrganizationFields(org.OrganizationFields)
	return nil
}

func (cmd Target) setSpace(spaceName string) error {
	cmd.config.SetSpaceFields(models.SpaceFields{})

	if !cmd.config.HasOrganization() {
		return errors.New(T("An org must be targeted before targeting a space"))
	}

	space, apiErr := cmd.spaceRepo.FindByName(spaceName)
	if apiErr != nil {
		return fmt.Errorf(T("Unable to access space {{.SpaceName}}.\n{{.APIErr}}",
			map[string]interface{}{"SpaceName": spaceName, "APIErr": apiErr.Error()}))
	}

	cmd.config.SetSpaceFields(space.SpaceFields)
	return nil
}

func (cmd Target) getSpaceList() ([]models.Space, error) {
	spaceList := []models.Space{}
	apiErr := cmd.spaceRepo.ListSpaces(
		func(space models.Space) bool {
			spaceList = append(spaceList, space)
			return true
		})
	return spaceList, apiErr
}
<commit_msg>don't display error twice, doing the hacky thing<commit_after>package commands

import (
	"fmt"

	"code.cloudfoundry.org/cli/cf/api/organizations"
	"code.cloudfoundry.org/cli/cf/api/spaces"
	"code.cloudfoundry.org/cli/cf/commandregistry"
	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
	"code.cloudfoundry.org/cli/cf/errors"
	"code.cloudfoundry.org/cli/cf/flags"
	. "code.cloudfoundry.org/cli/cf/i18n"
	"code.cloudfoundry.org/cli/cf/models"
	"code.cloudfoundry.org/cli/cf/requirements"
	"code.cloudfoundry.org/cli/cf/terminal"
)

type Target struct {
	ui        terminal.UI
	config    coreconfig.ReadWriter
	orgRepo   organizations.OrganizationRepository
	spaceRepo spaces.SpaceRepository
}

func init() {
	commandregistry.Register(&Target{})
}

func (cmd *Target) MetaData() commandregistry.CommandMetadata {
	fs := make(map[string]flags.FlagSet)
	fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Organization")}
	fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")}

	return commandregistry.CommandMetadata{
		Name:        "target",
		ShortName:   "t",
		Description: T("Set or view the targeted org or space"),
		Usage: []string{
			T("CF_NAME target [-o ORG] [-s SPACE]"),
		},
		Flags: fs,
	}
}

func (cmd *Target) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
	usageReq := requirements.NewUsageRequirement(commandregistry.CLICommandUsagePresenter(cmd),
		T("No argument required"),
		func() bool {
			return len(fc.Args()) != 0
		},
	)

	reqs := []requirements.Requirement{
		usageReq,
		requirementsFactory.NewAPIEndpointRequirement(),
	}

	if fc.IsSet("o") || fc.IsSet("s") {
		reqs = append(reqs, requirementsFactory.NewLoginRequirement())
	}

	return reqs, nil
}

func (cmd *Target) SetDependency(deps commandregistry.Dependency, _ bool) commandregistry.Command {
	cmd.ui = deps.UI
	cmd.config = deps.Config
	cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
	cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository()
	return cmd
}

func (cmd *Target) Execute(c flags.FlagContext) error {
	orgName := c.String("o")
	spaceName := c.String("s")

	if orgName != "" {
		err := cmd.setOrganization(orgName)
		if err != nil {
			return err
		} else if spaceName == "" {
			spaceList, apiErr := cmd.getSpaceList()
			if apiErr == nil && len(spaceList) == 1 {
				cmd.setSpace(spaceList[0].Name)
			}
		}
	}

	if spaceName != "" {
		err := cmd.setSpace(spaceName)
		if err != nil {
			return err
		}
	}

	err := cmd.ui.ShowConfiguration(cmd.config)
	if err != nil {
		return err
	}
	cmd.ui.NotifyUpdateIfNeeded(cmd.config)
	if !cmd.config.IsLoggedIn() {
		return fmt.Errorf("") // Done on purpose, do not redo this in refactor code
	}
	return nil
}

func (cmd Target) setOrganization(orgName string) error {
	// setting an org necessarily invalidates any space you had previously targeted
	cmd.config.SetOrganizationFields(models.OrganizationFields{})
	cmd.config.SetSpaceFields(models.SpaceFields{})

	org, apiErr := cmd.orgRepo.FindByName(orgName)
	if apiErr != nil {
		return fmt.Errorf(T("Could not target org.\n{{.APIErr}}",
			map[string]interface{}{"APIErr": apiErr.Error()}))
	}

	cmd.config.SetOrganizationFields(org.OrganizationFields)
	return nil
}

func (cmd Target) setSpace(spaceName string) error {
	cmd.config.SetSpaceFields(models.SpaceFields{})

	if !cmd.config.HasOrganization() {
		return errors.New(T("An org must be targeted before targeting a space"))
	}

	space, apiErr := cmd.spaceRepo.FindByName(spaceName)
	if apiErr != nil {
		return fmt.Errorf(T("Unable to access space {{.SpaceName}}.\n{{.APIErr}}",
			map[string]interface{}{"SpaceName": spaceName, "APIErr": apiErr.Error()}))
	}

	cmd.config.SetSpaceFields(space.SpaceFields)
	return nil
}

func (cmd Target) getSpaceList() ([]models.Space, error) {
	spaceList := []models.Space{}
	apiErr := cmd.spaceRepo.ListSpaces(
		func(space models.Space) bool {
			spaceList = append(spaceList, space)
			return true
		})
	return spaceList, apiErr
}
<|endoftext|>


<commit_before>// Copyright 2015 The Hugo Authors. 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 commands

import (
	"os"
	"runtime/pprof"

	"github.com/spf13/cobra"
)

var (
	benchmarkTimes int
	cpuProfilefile string
	memProfilefile string
)

var benchmarkCmd = &cobra.Command{
	Use:   "benchmark",
	Short: "Benchmark Hugo by building a site a number of times.",
	Long: `Hugo can build a site many times over and analyze the running process
creating a benchmark.`,
}

func init() {
	initHugoBuilderFlags(benchmarkCmd)
	initBenchmarkBuildingFlags(benchmarkCmd)

	benchmarkCmd.Flags().StringVar(&cpuProfilefile, "cpuprofile", "", "path/filename for the CPU profile file")
	benchmarkCmd.Flags().StringVar(&memProfilefile, "memprofile", "", "path/filename for the memory profile file")

	benchmarkCmd.Flags().IntVarP(&benchmarkTimes, "count", "n", 13, "number of times to build the site")

	benchmarkCmd.RunE = benchmark
}

func benchmark(cmd *cobra.Command, args []string) error {
	if err := InitializeConfig(benchmarkCmd); err != nil {
		return err
	}

	if memProfilefile != "" {
		f, err := os.Create(memProfilefile)

		if err != nil {
			return err
		}
		for i := 0; i < benchmarkTimes; i++ {
			_ = resetAndbuildSites(false)
		}
		pprof.WriteHeapProfile(f)
		f.Close()

	} else {
		if cpuProfilefile == "" {
			cpuProfilefile = "/tmp/hugo-cpuprofile"
		}
		f, err := os.Create(cpuProfilefile)

		if err != nil {
			return err
		}

		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
		for i := 0; i < benchmarkTimes; i++ {
			_ = resetAndbuildSites(false)
		}
	}

	return nil

}
<commit_msg>commands: Make benchmark command more useful<commit_after>// Copyright 2015 The Hugo Authors. 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 commands

import (
	"os"
	"runtime"
	"runtime/pprof"
	"time"

	"github.com/spf13/cobra"
	jww "github.com/spf13/jwalterweatherman"
)

var (
	benchmarkTimes int
	cpuProfileFile string
	memProfileFile string
)

var benchmarkCmd = &cobra.Command{
	Use:   "benchmark",
	Short: "Benchmark Hugo by building a site a number of times.",
	Long: `Hugo can build a site many times over and analyze the running process
creating a benchmark.`,
}

func init() {
	initHugoBuilderFlags(benchmarkCmd)
	initBenchmarkBuildingFlags(benchmarkCmd)

	benchmarkCmd.Flags().StringVar(&cpuProfileFile, "cpuprofile", "", "path/filename for the CPU profile file")
	benchmarkCmd.Flags().StringVar(&memProfileFile, "memprofile", "", "path/filename for the memory profile file")
	benchmarkCmd.Flags().IntVarP(&benchmarkTimes, "count", "n", 13, "number of times to build the site")

	benchmarkCmd.RunE = benchmark
}

func benchmark(cmd *cobra.Command, args []string) error {
	var err error
	if err = InitializeConfig(benchmarkCmd); err != nil {
		return err
	}

	var memProf *os.File
	if memProfileFile != "" {
		memProf, err = os.Create(memProfileFile)
		if err != nil {
			return err
		}
	}

	var cpuProf *os.File
	if cpuProfileFile != "" {
		cpuProf, err = os.Create(cpuProfileFile)
		if err != nil {
			return err
		}
	}

	var memStats runtime.MemStats
	runtime.ReadMemStats(&memStats)
	memAllocated := memStats.TotalAlloc
	mallocs := memStats.Mallocs
	if cpuProf != nil {
		pprof.StartCPUProfile(cpuProf)
	}

	t := time.Now()
	for i := 0; i < benchmarkTimes; i++ {
		if err = resetAndbuildSites(false); err != nil {
			return err
		}
	}
	totalTime := time.Since(t)

	if memProf != nil {
		pprof.WriteHeapProfile(memProf)
		memProf.Close()
	}
	if cpuProf != nil {
		pprof.StopCPUProfile()
		cpuProf.Close()
	}

	runtime.ReadMemStats(&memStats)
	totalMemAllocated := memStats.TotalAlloc - memAllocated
	totalMallocs := memStats.Mallocs - mallocs

	jww.FEEDBACK.Println()
	jww.FEEDBACK.Printf("Average time per operation: %vms\n", int(1000*totalTime.Seconds()/float64(benchmarkTimes)))
	jww.FEEDBACK.Printf("Average memory allocated per operation: %vkB\n", totalMemAllocated/uint64(benchmarkTimes)/1024)
	jww.FEEDBACK.Printf("Average allocations per operation: %v\n", totalMallocs/uint64(benchmarkTimes))

	return nil
}
<|endoftext|>


<commit_before>package commands

import (
	"fmt"
	"io/ioutil"
	"qaz/bucket"
	stks "qaz/stacks"
	"qaz/utils"
	"strings"
	"text/template"

	"encoding/base64"
	"encoding/json"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/kms"
)

// Common Functions - Both Deploy/Gen
var (
	kmsEncrypt = func(kid string, text string) (string, error) {
		sess, err := manager.GetSess(run.profile)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}

		svc := kms.New(sess)

		params := &kms.EncryptInput{
			KeyId:     aws.String(kid),
			Plaintext: []byte(text),
		}

		resp, err := svc.Encrypt(params)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}

		return base64.StdEncoding.EncodeToString(resp.CiphertextBlob), nil
	}

	kmsDecrypt = func(cipher string) (string, error) {
		sess, err := manager.GetSess(run.profile)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}

		svc := kms.New(sess)

		ciph, err := base64.StdEncoding.DecodeString(cipher)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}

		params := &kms.DecryptInput{
			CiphertextBlob: []byte(ciph),
		}

		resp, err := svc.Decrypt(params)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}

		return string(resp.Plaintext), nil
	}

	httpGet = func(url string) (interface{}, error) {
		log.Debug(fmt.Sprintln("Calling Template Function [GET] with arguments:", url))
		resp, err := utils.Get(url)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}

		return resp, nil
	}

	s3Read = func(url string, profile ...string) (string, error) {
		log.Debug(fmt.Sprintln("Calling Template Function [S3Read] with arguments:", url))

		var p = run.profile
		if len(profile) < 1 {
			log.Warn(fmt.Sprintf("No Profile specified for S3read, using: %s", p))
		} else {
			p = profile[0]
		}

		sess, err := manager.GetSess(p)
		utils.HandleError(err)

		resp, err := bucket.S3Read(url, sess)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}
		return resp, nil
	}

	lambdaInvoke = func(name string, payload string) (interface{}, error) {
		f := awsLambda{name: name}
		var m interface{}

		if payload != "" {
			f.payload = []byte(payload)
		}

		sess, err := manager.GetSess(run.profile)
		if err != nil {
			log.Error(err.Error())
			return "", err
		}

		if err := f.Invoke(sess); err != nil {
			log.Error(err.Error())
			return "", err
		}

		log.Debug(fmt.Sprintln("Lambda response:", f.response))

		// parse json if possible
		if err := json.Unmarshal([]byte(f.response), &m); err != nil {
			log.Debug(err.Error())
			return f.response, nil
		}

		return m, nil
	}

	prefix = func(s string, pre string) bool {
		return strings.HasPrefix(s, pre)
	}

	suffix = func(s string, suf string) bool {
		return strings.HasSuffix(s, suf)
	}

	contains = func(s string, con string) bool {
		return strings.Contains(s, con)
	}

	loop = func(n int) []struct{} {
		return make([]struct{}, n)
	}

	// gentime function maps
	GenTimeFunctions = template.FuncMap{
		// simple additon function useful for counters in loops
		"add": func(a int, b int) int {
			log.Debug(fmt.Sprintln("Calling Template Function [add] with arguments:", a, b))
			return a + b
		},

		// strip function for removing characters from text
		"strip": func(s string, rmv string) string {
			log.Debug(fmt.Sprintln("Calling Template Function [strip] with arguments:", s, rmv))
			return strings.Replace(s, rmv, "", -1)
		},

		// cat function for reading text from a given file under the files folder
		"cat": func(path string) (string, error) {

			log.Debug(fmt.Sprintln("Calling Template Function [cat] with arguments:", path))
			b, err := ioutil.ReadFile(path)
			if err != nil {
				log.Error(err.Error())
				return "", err
			}
			return string(b), nil
		},

		// suffix - returns true if string starts with given suffix
		"suffix": suffix,

		// prefix - returns true if string starts with given prefix
		"prefix": prefix,

		// contains - returns true if string contains
		"contains": contains,

		// loop - useful to range over an int (rather than a slice, map, or channel). see examples/loop
		"loop": loop,

		// Get get does an HTTP Get request of the given url and returns the output string
		"GET": httpGet,

		// S3Read reads content of file from s3 and returns string contents
		"s3_read": s3Read,

		// invoke - invokes a lambda function and returns a raw string/interface{}
		"invoke": lambdaInvoke,

		// kms-encrypt - Encrypts PlainText using KMS key
		"kms_encrypt": kmsEncrypt,

		// kms-decrypt - Descrypts CipherText
		"kms_decrypt": kmsDecrypt,
	}

	// deploytime function maps
	DeployTimeFunctions = template.FuncMap{
		// Fetching stackoutputs
		"stack_output": func(target string) (string, error) {
			log.Debug(fmt.Sprintf("Deploy-Time function resolving: %s", target))
			req := strings.Split(target, "::")

			s := stacks[req[0]]

			if err := s.Outputs(); err != nil {
				return "", err
			}

			for _, i := range s.Output.Stacks {
				for _, o := range i.Outputs {
					if *o.OutputKey == req[1] {
						return *o.OutputValue, nil
					}
				}
			}

			return "", fmt.Errorf("Stack Output Not found - Stack:%s | Output:%s", req[0], req[1])
		},

		"stack_output_ext": func(target string) (string, error) {
			log.Debug(fmt.Sprintf("Deploy-Time function resolving: %s", target))
			req := strings.Split(target, "::")

			sess, err := manager.GetSess(run.profile)
			if err != nil {
				log.Error(err.Error())
				return "", nil
			}

			s := stks.Stack{
				Stackname: req[0],
				Session:   sess,
			}

			if err := s.Outputs(); err != nil {
				return "", err
			}

			for _, i := range s.Output.Stacks {
				for _, o := range i.Outputs {
					if *o.OutputKey == req[1] {
						return *o.OutputValue, nil
					}
				}
			}

			return "", fmt.Errorf("Stack Output Not found - Stack:%s | Output:%s", req[0], req[1])
		},

		// suffix - returns true if string starts with given suffix
		"suffix": suffix,

		// prefix - returns true if string starts with given prefix
		"prefix": prefix,

		// contains - returns true if string contains
		"contains": contains,

		// loop - useful to range over an int (rather than a slice, map, or channel). see examples/loop
		"loop": loop,

		// Get get does an HTTP Get request of the given url and returns the output string
		"GET": httpGet,

		// S3Read reads content of file from s3 and returns string contents
		"s3_read": s3Read,

		// invoke - invokes a lambda function and returns a raw string/interface{}
		"invoke": lambdaInvoke,

		// kms-encrypt - Encrypts PlainText using KMS key
		"kms_encrypt": kmsEncrypt,

		// kms-decrypt - Descrypts CipherText
		"kms_decrypt": kmsDecrypt,
	}
)
<commit_msg>updated error handling in functions.go<commit_after>package commands

import (
	"fmt"
	"io/ioutil"
	"qaz/bucket"
	stks "qaz/stacks"
	"qaz/utils"
	"strings"
	"text/template"

	"encoding/base64"
	"encoding/json"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/kms"
)

// Common Functions - Both Deploy/Gen
var (
	kmsEncrypt = func(kid string, text string) string {
		log.Debug("running template function: [kms_encrypt]")
		sess, err := manager.GetSess(run.profile)
		utils.HandleError(err)

		svc := kms.New(sess)

		params := &kms.EncryptInput{
			KeyId:     aws.String(kid),
			Plaintext: []byte(text),
		}

		resp, err := svc.Encrypt(params)
		utils.HandleError(err)

		return base64.StdEncoding.EncodeToString(resp.CiphertextBlob)
	}

	kmsDecrypt = func(cipher string) string {
		log.Debug("running template function: [kms_decrypt]")
		sess, err := manager.GetSess(run.profile)
		utils.HandleError(err)

		svc := kms.New(sess)

		ciph, err := base64.StdEncoding.DecodeString(cipher)
		utils.HandleError(err)

		params := &kms.DecryptInput{
			CiphertextBlob: []byte(ciph),
		}

		resp, err := svc.Decrypt(params)
		utils.HandleError(err)

		return string(resp.Plaintext)
	}

	httpGet = func(url string) interface{} {
		log.Debug(fmt.Sprintln("Calling Template Function [GET] with arguments:", url))
		resp, err := utils.Get(url)
		utils.HandleError(err)

		return resp
	}

	s3Read = func(url string, profile ...string) string {
		log.Debug(fmt.Sprintln("Calling Template Function [S3Read] with arguments:", url))

		var p = run.profile
		if len(profile) < 1 {
			log.Warn(fmt.Sprintf("No Profile specified for S3read, using: %s", p))
		} else {
			p = profile[0]
		}

		sess, err := manager.GetSess(p)
		utils.HandleError(err)

		resp, err := bucket.S3Read(url, sess)
		utils.HandleError(err)

		return resp
	}

	lambdaInvoke = func(name string, payload string) interface{} {
		log.Debug("running template function: [invoke]")
		f := awsLambda{name: name}
		var m interface{}

		if payload != "" {
			f.payload = []byte(payload)
		}

		sess, err := manager.GetSess(run.profile)
		utils.HandleError(err)

		err = f.Invoke(sess)
		utils.HandleError(err)

		log.Debug(fmt.Sprintln("Lambda response:", f.response))

		// parse json if possible
		if err := json.Unmarshal([]byte(f.response), &m); err != nil {
			log.Debug(err.Error())
			return f.response
		}

		return m
	}

	prefix = func(s string, pre string) bool {
		return strings.HasPrefix(s, pre)
	}

	suffix = func(s string, suf string) bool {
		return strings.HasSuffix(s, suf)
	}

	contains = func(s string, con string) bool {
		return strings.Contains(s, con)
	}

	loop = func(n int) []struct{} {
		return make([]struct{}, n)
	}

	// gentime function maps
	GenTimeFunctions = template.FuncMap{
		// simple additon function useful for counters in loops
		"add": func(a int, b int) int {
			log.Debug(fmt.Sprintln("Calling Template Function [add] with arguments:", a, b))
			return a + b
		},

		// strip function for removing characters from text
		"strip": func(s string, rmv string) string {
			log.Debug(fmt.Sprintln("Calling Template Function [strip] with arguments:", s, rmv))
			return strings.Replace(s, rmv, "", -1)
		},

		// cat function for reading text from a given file under the files folder
		"cat": func(path string) string {
			log.Debug(fmt.Sprintln("Calling Template Function [cat] with arguments:", path))
			b, err := ioutil.ReadFile(path)
			utils.HandleError(err)
			return string(b)
		},

		// suffix - returns true if string starts with given suffix
		"suffix": suffix,

		// prefix - returns true if string starts with given prefix
		"prefix": prefix,

		// contains - returns true if string contains
		"contains": contains,

		// loop - useful to range over an int (rather than a slice, map, or channel). see examples/loop
		"loop": loop,

		// Get get does an HTTP Get request of the given url and returns the output string
		"GET": httpGet,

		// S3Read reads content of file from s3 and returns string contents
		"s3_read": s3Read,

		// invoke - invokes a lambda function and returns a raw string/interface{}
		"invoke": lambdaInvoke,

		// kms-encrypt - Encrypts PlainText using KMS key
		"kms_encrypt": kmsEncrypt,

		// kms-decrypt - Descrypts CipherText
		"kms_decrypt": kmsDecrypt,
	}

	// deploytime function maps
	DeployTimeFunctions = template.FuncMap{
		// Fetching stackoutputs
		"stack_output": func(target string) string {
			log.Debug(fmt.Sprintf("Deploy-Time function resolving: %s", target))
			req := strings.Split(target, "::")

			s := stacks[req[0]]

			err := s.Outputs()
			utils.HandleError(err)

			for _, i := range s.Output.Stacks {
				for _, o := range i.Outputs {
					if *o.OutputKey == req[1] {
						return *o.OutputValue
					}
				}
			}

			utils.HandleError(fmt.Errorf("Stack Output Not found - Stack:%s | Output:%s", req[0], req[1]))
			return ""
		},

		"stack_output_ext": func(target string) string {
			log.Debug(fmt.Sprintf("Deploy-Time function resolving: %s", target))
			req := strings.Split(target, "::")

			sess, err := manager.GetSess(run.profile)
			utils.HandleError(err)

			s := stks.Stack{
				Stackname: req[0],
				Session:   sess,
			}

			err = s.Outputs()
			utils.HandleError(err)

			for _, i := range s.Output.Stacks {
				for _, o := range i.Outputs {
					if *o.OutputKey == req[1] {
						return *o.OutputValue
					}
				}
			}

			utils.HandleError(fmt.Errorf("Stack Output Not found - Stack:%s | Output:%s", req[0], req[1]))
			return ""
		},

		// suffix - returns true if string starts with given suffix
		"suffix": suffix,

		// prefix - returns true if string starts with given prefix
		"prefix": prefix,

		// contains - returns true if string contains
		"contains": contains,

		// loop - useful to range over an int (rather than a slice, map, or channel). see examples/loop
		"loop": loop,

		// Get get does an HTTP Get request of the given url and returns the output string
		"GET": httpGet,

		// S3Read reads content of file from s3 and returns string contents
		"s3_read": s3Read,

		// invoke - invokes a lambda function and returns a raw string/interface{}
		"invoke": lambdaInvoke,

		// kms-encrypt - Encrypts PlainText using KMS key
		"kms_encrypt": kmsEncrypt,

		// kms-decrypt - Descrypts CipherText
		"kms_decrypt": kmsDecrypt,
	}
)
<|endoftext|>


<commit_before>package main

import (
	"github.com/workfit/tester/assert"
	"testing"
)

func TestEnumParent(t *testing.T) {
	tests := []struct {
		description string
		strValues   map[string]string
		//If nil, expect no change from strValues
		expectedValues  map[string]string
		expectedParents map[string]string
	}{
		{
			"Single layer",
			map[string]string{
				"Phase":         "",
				"PhaseAnother":  "Another",
				"PhaseOverride": "Heyo",
			},
			nil,
			map[string]string{
				"Phase":         "Phase",
				"PhaseAnother":  "Phase",
				"PhaseOverride": "Phase",
			},
		},
		{
			"No Tree",
			map[string]string{
				"ColorBlue":  "Blue",
				"ColorGreen": "Green",
				"ColorRed":   "Red",
			},
			nil,
			nil,
		},
		{
			"Two layers",
			map[string]string{
				"Color":          "",
				"ColorBlue":      "Blue",
				"ColorBlue_One":  "Blue > One",
				"ColorBlue_Two":  "Blue > Two",
				"ColorGreen":     "Green",
				"ColorGreen_One": "Green > One",
			},
			map[string]string{
				"Color":          "",
				"ColorBlue":      "Blue",
				"ColorBlue_One":  "One",
				"ColorBlue_Two":  "Two",
				"ColorGreen":     "Green",
				"ColorGreen_One": "One",
			},
			map[string]string{
				"Color":          "Color",
				"ColorBlue":      "Color",
				"ColorBlue_One":  "ColorBlue",
				"ColorBlue_Two":  "ColorBlue",
				"ColorGreen":     "Color",
				"ColorGreen_One": "ColorGreen",
			},
		},
		{
			"Three layers",
			map[string]string{
				"Color":             "",
				"ColorBlue":         "Blue",
				"ColorBlue_One":     "Blue > One",
				"ColorBlue_Two":     "Blue > Two",
				"ColorBlue_One_One": "Blue > One > One",
				"ColorBlue_One_Two": "Blue > One > Two",
			},
			map[string]string{
				"Color":             "",
				"ColorBlue":         "Blue",
				"ColorBlue_One":     "One",
				"ColorBlue_Two":     "Two",
				"ColorBlue_One_One": "One",
				"ColorBlue_One_Two": "Two",
			},
			map[string]string{
				"Color":             "Color",
				"ColorBlue":         "Color",
				"ColorBlue_One":     "ColorBlue",
				"ColorBlue_Two":     "ColorBlue",
				"ColorBlue_One_One": "ColorBlue_One",
				"ColorBlue_One_Two": "ColorBlue_One",
			},
		},
		{
			"Single implied layer",
			map[string]string{
				"Color":         "",
				"ColorBlue_One": "Blue > One",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Blue",
				"ColorBlue_One":        "One",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"ColorBlue_One":        "-9223372036854775808",
			},
		},
		{
			"Two implied layers",
			map[string]string{
				"Color":            "",
				"ColorGreen_One_A": "Green > One > A",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Green",
				"-9223372036854775807": "One",
				"ColorGreen_One_A":     "A",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"-9223372036854775807": "-9223372036854775808",
				"ColorGreen_One_A":     "-9223372036854775807",
			},
		},
		{
			"Single word implied nesting",
			map[string]string{
				"Color":        "",
				"ColorBlue":    "Blue",
				"ColorBlueOne": "Blue One",
				"ColorBlueTwo": "Blue Two",
			},
			map[string]string{
				"Color":        "",
				"ColorBlue":    "Blue",
				"ColorBlueOne": "One",
				"ColorBlueTwo": "Two",
			},
			map[string]string{
				"Color":        "Color",
				"ColorBlue":    "Color",
				"ColorBlueOne": "ColorBlue",
				"ColorBlueTwo": "ColorBlue",
			},
		},
		{
			"Multi-Word implied nesting",
			map[string]string{
				"Color":             "",
				"ColorBlueGreen":    "Blue Green",
				"ColorBlueGreenOne": "Blue Green One",
				"ColorBlueGreenTwo": "Blue Green Two",
			},
			map[string]string{
				"Color":             "",
				"ColorBlueGreen":    "Blue Green",
				"ColorBlueGreenOne": "One",
				"ColorBlueGreenTwo": "Two",
			},
			map[string]string{
				"Color":             "Color",
				"ColorBlueGreen":    "Color",
				"ColorBlueGreenOne": "ColorBlueGreen",
				"ColorBlueGreenTwo": "ColorBlueGreen",
			},
		},
		{
			"Implied node with implied nesting",
			map[string]string{
				"Color":             "",
				"ColorBlueGreenOne": "Blue Green One",
				"ColorBlueGreenTwo": "Blue Green Two",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Blue Green",
				"ColorBlueGreenOne":    "One",
				"ColorBlueGreenTwo":    "Two",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"ColorBlueGreenOne":    "-9223372036854775808",
				"ColorBlueGreenTwo":    "-9223372036854775808",
			},
		},
		{
			"Multiple implied layers",
			map[string]string{
				"Color":              "",
				"ColorBlueGreen":     "Blue Green",
				"ColorBlueGreenOne":  "Blue Green One",
				"ColorBlueGreenOneA": "Blue Green One A",
				"ColorBlueGreenOneB": "Blue Green One B",
				"ColorBlueGreenTwo":  "Blue Green Two",
			},
			map[string]string{
				"Color":              "",
				"ColorBlueGreen":     "Blue Green",
				"ColorBlueGreenOne":  "One",
				"ColorBlueGreenOneA": "A",
				"ColorBlueGreenOneB": "B",
				"ColorBlueGreenTwo":  "Two",
			},
			map[string]string{
				"Color":              "Color",
				"ColorBlueGreen":     "Color",
				"ColorBlueGreenOne":  "ColorBlueGreen",
				"ColorBlueGreenOneA": "ColorBlueGreenOne",
				"ColorBlueGreenOneB": "ColorBlueGreenOne",
				"ColorBlueGreenTwo":  "ColorBlueGreen",
			},
		},

		{
			"Multiple implied layers with implied node",
			map[string]string{
				"Color":              "",
				"ColorBlueGreen":     "Blue Green",
				"ColorBlueGreenOneA": "Blue Green One A",
				"ColorBlueGreenOneB": "Blue Green One B",
				"ColorBlueGreenTwo":  "Blue Green Two",
			},
			map[string]string{
				"Color":                "",
				"ColorBlueGreen":       "Blue Green",
				"-9223372036854775808": "One",
				"ColorBlueGreenOneA":   "A",
				"ColorBlueGreenOneB":   "B",
				"ColorBlueGreenTwo":    "Two",
			},
			map[string]string{
				"Color":                "Color",
				"ColorBlueGreen":       "Color",
				"-9223372036854775808": "ColorBlueGreen",
				"ColorBlueGreenOneA":   "-9223372036854775808",
				"ColorBlueGreenOneB":   "-9223372036854775808",
				"ColorBlueGreenTwo":    "ColorBlueGreen",
			},
		},
		{
			"Mix implicit and explicit layers",
			map[string]string{
				"Color":               "",
				"ColorBlueGreen":      "Blue Green",
				"ColorBlueGreenOne":   "Blue Green One",
				"ColorBlueGreenOne_A": "Blue Green One > A",
				"ColorBlueGreenOne_B": "Blue Green One > B",
				"ColorBlueGreenTwo":   "Blue Green Two",
			},
			map[string]string{
				"Color":               "",
				"ColorBlueGreen":      "Blue Green",
				"ColorBlueGreenOne":   "One",
				"ColorBlueGreenOne_A": "A",
				"ColorBlueGreenOne_B": "B",
				"ColorBlueGreenTwo":   "Two",
			},
			map[string]string{
				"Color":               "Color",
				"ColorBlueGreen":      "Color",
				"ColorBlueGreenOne":   "ColorBlueGreen",
				"ColorBlueGreenOne_A": "ColorBlueGreenOne",
				"ColorBlueGreenOne_B": "ColorBlueGreenOne",
				"ColorBlueGreenTwo":   "ColorBlueGreen",
			},
		},
		{
			"Multiple implied layers in a row",
			map[string]string{
				"Color":              "",
				"ColorBlueGreenOneA": "Blue Green One A",
				"ColorBlueGreenOneB": "Blue Green One B",
				"ColorBlueGreenTwo":  "Blue Green Two",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Blue Green",
				"-9223372036854775807": "One",
				"ColorBlueGreenOneA":   "A",
				"ColorBlueGreenOneB":   "B",
				"ColorBlueGreenTwo":    "Two",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"-9223372036854775807": "-9223372036854775808",
				"ColorBlueGreenOneA":   "-9223372036854775807",
				"ColorBlueGreenOneB":   "-9223372036854775807",
				"ColorBlueGreenTwo":    "-9223372036854775808",
			},
		},
	}

	for i, test := range tests {

		e := newEnum("test", transformNone)

		for key, val := range test.strValues {
			e.AddTransformKey(key, true, val, transformNone)
		}

		err := e.Process()
		assert.For(t, i).ThatActual(err).IsNil()

		actualValues := e.ValueMap()
		actualParents := e.Parents()
		if test.expectedValues == nil {
			//Expect no change from test.strValues
			assert.For(t, i).ThatActual(actualValues).Equals(test.strValues).ThenDiffOnFail()
		} else {
			assert.For(t, i).ThatActual(actualValues).Equals(test.expectedValues).ThenDiffOnFail()
		}
		assert.For(t, i).ThatActual(actualParents).Equals(test.expectedParents).ThenDiffOnFail()
	}
}
<commit_msg>Added another test for an elided parent underneath a non-elided parent. Part of #628.<commit_after>package main

import (
	"github.com/workfit/tester/assert"
	"testing"
)

func TestEnumParent(t *testing.T) {
	tests := []struct {
		description string
		strValues   map[string]string
		//If nil, expect no change from strValues
		expectedValues  map[string]string
		expectedParents map[string]string
	}{
		{
			"Single layer",
			map[string]string{
				"Phase":         "",
				"PhaseAnother":  "Another",
				"PhaseOverride": "Heyo",
			},
			nil,
			map[string]string{
				"Phase":         "Phase",
				"PhaseAnother":  "Phase",
				"PhaseOverride": "Phase",
			},
		},
		{
			"No Tree",
			map[string]string{
				"ColorBlue":  "Blue",
				"ColorGreen": "Green",
				"ColorRed":   "Red",
			},
			nil,
			nil,
		},
		{
			"Two layers",
			map[string]string{
				"Color":          "",
				"ColorBlue":      "Blue",
				"ColorBlue_One":  "Blue > One",
				"ColorBlue_Two":  "Blue > Two",
				"ColorGreen":     "Green",
				"ColorGreen_One": "Green > One",
			},
			map[string]string{
				"Color":          "",
				"ColorBlue":      "Blue",
				"ColorBlue_One":  "One",
				"ColorBlue_Two":  "Two",
				"ColorGreen":     "Green",
				"ColorGreen_One": "One",
			},
			map[string]string{
				"Color":          "Color",
				"ColorBlue":      "Color",
				"ColorBlue_One":  "ColorBlue",
				"ColorBlue_Two":  "ColorBlue",
				"ColorGreen":     "Color",
				"ColorGreen_One": "ColorGreen",
			},
		},
		{
			"Three layers",
			map[string]string{
				"Color":             "",
				"ColorBlue":         "Blue",
				"ColorBlue_One":     "Blue > One",
				"ColorBlue_Two":     "Blue > Two",
				"ColorBlue_One_One": "Blue > One > One",
				"ColorBlue_One_Two": "Blue > One > Two",
			},
			map[string]string{
				"Color":             "",
				"ColorBlue":         "Blue",
				"ColorBlue_One":     "One",
				"ColorBlue_Two":     "Two",
				"ColorBlue_One_One": "One",
				"ColorBlue_One_Two": "Two",
			},
			map[string]string{
				"Color":             "Color",
				"ColorBlue":         "Color",
				"ColorBlue_One":     "ColorBlue",
				"ColorBlue_Two":     "ColorBlue",
				"ColorBlue_One_One": "ColorBlue_One",
				"ColorBlue_One_Two": "ColorBlue_One",
			},
		},
		{
			"Single implied layer",
			map[string]string{
				"Color":         "",
				"ColorBlue_One": "Blue > One",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Blue",
				"ColorBlue_One":        "One",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"ColorBlue_One":        "-9223372036854775808",
			},
		},
		{
			"Two implied layers",
			map[string]string{
				"Color":            "",
				"ColorGreen_One_A": "Green > One > A",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Green",
				"-9223372036854775807": "One",
				"ColorGreen_One_A":     "A",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"-9223372036854775807": "-9223372036854775808",
				"ColorGreen_One_A":     "-9223372036854775807",
			},
		},
		{
			"Single word implied nesting",
			map[string]string{
				"Color":        "",
				"ColorBlue":    "Blue",
				"ColorBlueOne": "Blue One",
				"ColorBlueTwo": "Blue Two",
			},
			map[string]string{
				"Color":        "",
				"ColorBlue":    "Blue",
				"ColorBlueOne": "One",
				"ColorBlueTwo": "Two",
			},
			map[string]string{
				"Color":        "Color",
				"ColorBlue":    "Color",
				"ColorBlueOne": "ColorBlue",
				"ColorBlueTwo": "ColorBlue",
			},
		},
		{
			"Multi-Word implied nesting",
			map[string]string{
				"Color":             "",
				"ColorBlueGreen":    "Blue Green",
				"ColorBlueGreenOne": "Blue Green One",
				"ColorBlueGreenTwo": "Blue Green Two",
			},
			map[string]string{
				"Color":             "",
				"ColorBlueGreen":    "Blue Green",
				"ColorBlueGreenOne": "One",
				"ColorBlueGreenTwo": "Two",
			},
			map[string]string{
				"Color":             "Color",
				"ColorBlueGreen":    "Color",
				"ColorBlueGreenOne": "ColorBlueGreen",
				"ColorBlueGreenTwo": "ColorBlueGreen",
			},
		},
		{
			"Implied node with implied nesting",
			map[string]string{
				"Color":             "",
				"ColorBlueGreenOne": "Blue Green One",
				"ColorBlueGreenTwo": "Blue Green Two",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Blue Green",
				"ColorBlueGreenOne":    "One",
				"ColorBlueGreenTwo":    "Two",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"ColorBlueGreenOne":    "-9223372036854775808",
				"ColorBlueGreenTwo":    "-9223372036854775808",
			},
		},
		{
			"Multiple implied layers",
			map[string]string{
				"Color":              "",
				"ColorBlueGreen":     "Blue Green",
				"ColorBlueGreenOne":  "Blue Green One",
				"ColorBlueGreenOneA": "Blue Green One A",
				"ColorBlueGreenOneB": "Blue Green One B",
				"ColorBlueGreenTwo":  "Blue Green Two",
			},
			map[string]string{
				"Color":              "",
				"ColorBlueGreen":     "Blue Green",
				"ColorBlueGreenOne":  "One",
				"ColorBlueGreenOneA": "A",
				"ColorBlueGreenOneB": "B",
				"ColorBlueGreenTwo":  "Two",
			},
			map[string]string{
				"Color":              "Color",
				"ColorBlueGreen":     "Color",
				"ColorBlueGreenOne":  "ColorBlueGreen",
				"ColorBlueGreenOneA": "ColorBlueGreenOne",
				"ColorBlueGreenOneB": "ColorBlueGreenOne",
				"ColorBlueGreenTwo":  "ColorBlueGreen",
			},
		},

		{
			"Multiple implied layers with implied node",
			map[string]string{
				"Color":              "",
				"ColorBlueGreen":     "Blue Green",
				"ColorBlueGreenOneA": "Blue Green One A",
				"ColorBlueGreenOneB": "Blue Green One B",
				"ColorBlueGreenTwo":  "Blue Green Two",
			},
			map[string]string{
				"Color":                "",
				"ColorBlueGreen":       "Blue Green",
				"-9223372036854775808": "One",
				"ColorBlueGreenOneA":   "A",
				"ColorBlueGreenOneB":   "B",
				"ColorBlueGreenTwo":    "Two",
			},
			map[string]string{
				"Color":                "Color",
				"ColorBlueGreen":       "Color",
				"-9223372036854775808": "ColorBlueGreen",
				"ColorBlueGreenOneA":   "-9223372036854775808",
				"ColorBlueGreenOneB":   "-9223372036854775808",
				"ColorBlueGreenTwo":    "ColorBlueGreen",
			},
		},
		{
			"Mix implicit and explicit layers",
			map[string]string{
				"Color":               "",
				"ColorBlueGreen":      "Blue Green",
				"ColorBlueGreenOne":   "Blue Green One",
				"ColorBlueGreenOne_A": "Blue Green One > A",
				"ColorBlueGreenOne_B": "Blue Green One > B",
				"ColorBlueGreenTwo":   "Blue Green Two",
			},
			map[string]string{
				"Color":               "",
				"ColorBlueGreen":      "Blue Green",
				"ColorBlueGreenOne":   "One",
				"ColorBlueGreenOne_A": "A",
				"ColorBlueGreenOne_B": "B",
				"ColorBlueGreenTwo":   "Two",
			},
			map[string]string{
				"Color":               "Color",
				"ColorBlueGreen":      "Color",
				"ColorBlueGreenOne":   "ColorBlueGreen",
				"ColorBlueGreenOne_A": "ColorBlueGreenOne",
				"ColorBlueGreenOne_B": "ColorBlueGreenOne",
				"ColorBlueGreenTwo":   "ColorBlueGreen",
			},
		},
		{
			"Multiple implied layers in a row",
			map[string]string{
				"Color":              "",
				"ColorBlueGreenOneA": "Blue Green One A",
				"ColorBlueGreenOneB": "Blue Green One B",
				"ColorBlueGreenTwo":  "Blue Green Two",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Blue Green",
				"-9223372036854775807": "One",
				"ColorBlueGreenOneA":   "A",
				"ColorBlueGreenOneB":   "B",
				"ColorBlueGreenTwo":    "Two",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"-9223372036854775807": "-9223372036854775808",
				"ColorBlueGreenOneA":   "-9223372036854775807",
				"ColorBlueGreenOneB":   "-9223372036854775807",
				"ColorBlueGreenTwo":    "-9223372036854775808",
			},
		},
		{
			"Elided parent beneath non-elided multi-word node",
			map[string]string{
				"Color":              "",
				"ColorBlueGreenOne":  "Blue Green One",
				"ColorBlueGreenOneA": "Blue Green One A",
				"ColorBlueGreenOneB": "Blue Green One B",
				"ColorBlueGreenTwoA": "Blue Green Two A",
			},
			map[string]string{
				"Color":                "",
				"-9223372036854775808": "Blue Green",
				"ColorBlueGreenOne":    "One",
				"ColorBlueGreenOneA":   "A",
				"ColorBlueGreenOneB":   "B",
				"ColorBlueGreenTwoA":   "Two A",
			},
			map[string]string{
				"Color":                "Color",
				"-9223372036854775808": "Color",
				"ColorBlueGreenOne":    "-9223372036854775808",
				"ColorBlueGreenOneA":   "ColorBlueGreenOne",
				"ColorBlueGreenOneB":   "ColorBlueGreenOne",
				"ColorBlueGreenTwoA":   "-9223372036854775808",
			},
		},
	}

	for i, test := range tests {

		e := newEnum("test", transformNone)

		for key, val := range test.strValues {
			e.AddTransformKey(key, true, val, transformNone)
		}

		err := e.Process()
		assert.For(t, i).ThatActual(err).IsNil()

		actualValues := e.ValueMap()
		actualParents := e.Parents()
		if test.expectedValues == nil {
			//Expect no change from test.strValues
			assert.For(t, i).ThatActual(actualValues).Equals(test.strValues).ThenDiffOnFail()
		} else {
			assert.For(t, i).ThatActual(actualValues).Equals(test.expectedValues).ThenDiffOnFail()
		}
		assert.For(t, i).ThatActual(actualParents).Equals(test.expectedParents).ThenDiffOnFail()
	}
}
<|endoftext|>


<commit_before>package brightbox

import (
	"fmt"
	"testing"

	"github.com/gophercloud/gophercloud/openstack/objectstorage/v1/containers"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccBrightboxOrbitContainer_Basic(t *testing.T) {
	resourceName := "brightbox_orbit_container.foobar"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckBrightboxOrbitContainerDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists(resourceName),
					resource.TestCheckResourceAttr(
						resourceName, "name", "test-acc-initial"),
				),
			},
			{
				ResourceName:            resourceName,
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"created_at"},
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_updated,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists(resourceName),
					resource.TestCheckResourceAttr(
						resourceName, "name", "test-acc-updated"),
				),
			},
		},
	})
}

func TestAccBrightboxOrbitContainer_metadata(t *testing.T) {
	resourceName := "brightbox_orbit_container.foobar"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckBrightboxOrbitContainerDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists(resourceName),
					resource.TestCheckResourceAttr(
						resourceName, "name", "initial"),
				),
			},
			{
				ResourceName:            resourceName,
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"created_at"},
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata_add,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists("brightbox_orbit_container.foobar"),
					resource.TestCheckResourceAttr(
						"brightbox_orbit_container.foobar", "name", "test-acc-initial"),
				),
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists("brightbox_orbit_container.foobar"),
					resource.TestCheckResourceAttr(
						"brightbox_orbit_container.foobar", "name", "test-acc-initial"),
				),
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata_delete,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists("brightbox_orbit_container.foobar"),
					resource.TestCheckResourceAttr(
						"brightbox_orbit_container.foobar", "name", "test-acc-initial"),
				),
			},
		},
	})
}

func testAccCheckBrightboxOrbitContainerDestroy(s *terraform.State) error {
	client := testAccProvider.Meta().(*CompositeClient).OrbitClient

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "brightbox_orbit_container" {
			continue
		}

		// Try to find the container
		getresult := containers.Get(client, rs.Primary.ID, nil)

		// Wait

		err := getresult.Err
		if err != nil && err.Error() != "Resource not found" {
			return fmt.Errorf(
				"Error waiting for container %s to be destroyed: %s",
				rs.Primary.ID, getresult.Err)
		}
	}

	return nil
}

func testAccCheckBrightboxOrbitContainerExists(n string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		_, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}
		return nil
	}
}

const testAccCheckBrightboxOrbitContainerConfig_basic = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
}
`

const testAccCheckBrightboxOrbitContainerConfig_updated = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-updated"
}
`

const testAccCheckBrightboxOrbitContainerConfig_metadata = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
	container_read = [ "acc-testy", "acc-12345"]
	metadata = {
		"foo"= "bar"
		"bar"= "baz"
		"uni" = "€uro"
	}
}
`

const testAccCheckBrightboxOrbitContainerConfig_metadata_add = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
	metadata = {
		"foo"= "bar"
		"bar"= "foo"
		"uni" = "€uro"
	}
	container_read = [ "acc-testy", "acc-12345", "acc-98765" ]
}
`

const testAccCheckBrightboxOrbitContainerConfig_metadata_delete = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
	metadata = {
		"bar"= "foo"
		"uni" = "€uro"
	}
	container_read = [ "acc-testy", "acc-12345", "acc-98765" ]
}
`
<commit_msg>Check for correct name in orbit tests<commit_after>package brightbox

import (
	"fmt"
	"testing"

	"github.com/gophercloud/gophercloud/openstack/objectstorage/v1/containers"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccBrightboxOrbitContainer_Basic(t *testing.T) {
	resourceName := "brightbox_orbit_container.foobar"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckBrightboxOrbitContainerDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists(resourceName),
					resource.TestCheckResourceAttr(
						resourceName, "name", "test-acc-initial"),
				),
			},
			{
				ResourceName:            resourceName,
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"created_at"},
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_updated,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists(resourceName),
					resource.TestCheckResourceAttr(
						resourceName, "name", "test-acc-updated"),
				),
			},
		},
	})
}

func TestAccBrightboxOrbitContainer_metadata(t *testing.T) {
	resourceName := "brightbox_orbit_container.foobar"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckBrightboxOrbitContainerDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists(resourceName),
					resource.TestCheckResourceAttr(
						resourceName, "name", "test-acc-initial"),
				),
			},
			{
				ResourceName:            resourceName,
				ImportState:             true,
				ImportStateVerify:       true,
				ImportStateVerifyIgnore: []string{"created_at"},
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata_add,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists("brightbox_orbit_container.foobar"),
					resource.TestCheckResourceAttr(
						"brightbox_orbit_container.foobar", "name", "test-acc-initial"),
				),
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists("brightbox_orbit_container.foobar"),
					resource.TestCheckResourceAttr(
						"brightbox_orbit_container.foobar", "name", "test-acc-initial"),
				),
			},
			{
				Config: testAccCheckBrightboxOrbitContainerConfig_metadata_delete,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBrightboxOrbitContainerExists("brightbox_orbit_container.foobar"),
					resource.TestCheckResourceAttr(
						"brightbox_orbit_container.foobar", "name", "test-acc-initial"),
				),
			},
		},
	})
}

func testAccCheckBrightboxOrbitContainerDestroy(s *terraform.State) error {
	client := testAccProvider.Meta().(*CompositeClient).OrbitClient

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "brightbox_orbit_container" {
			continue
		}

		// Try to find the container
		getresult := containers.Get(client, rs.Primary.ID, nil)

		// Wait

		err := getresult.Err
		if err != nil && err.Error() != "Resource not found" {
			return fmt.Errorf(
				"Error waiting for container %s to be destroyed: %s",
				rs.Primary.ID, getresult.Err)
		}
	}

	return nil
}

func testAccCheckBrightboxOrbitContainerExists(n string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		_, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}
		return nil
	}
}

const testAccCheckBrightboxOrbitContainerConfig_basic = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
}
`

const testAccCheckBrightboxOrbitContainerConfig_updated = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-updated"
}
`

const testAccCheckBrightboxOrbitContainerConfig_metadata = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
	container_read = [ "acc-testy", "acc-12345"]
	metadata = {
		"foo"= "bar"
		"bar"= "baz"
		"uni" = "€uro"
	}
}
`

const testAccCheckBrightboxOrbitContainerConfig_metadata_add = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
	metadata = {
		"foo"= "bar"
		"bar"= "foo"
		"uni" = "€uro"
	}
	container_read = [ "acc-testy", "acc-12345", "acc-98765" ]
}
`

const testAccCheckBrightboxOrbitContainerConfig_metadata_delete = `

resource "brightbox_orbit_container" "foobar" {
	name = "test-acc-initial"
	metadata = {
		"bar"= "foo"
		"uni" = "€uro"
	}
	container_read = [ "acc-testy", "acc-12345", "acc-98765" ]
}
`
<|endoftext|>


<commit_before>package main

func init() {
	registerFilesystemFlags()
	disableCollectors("arp", "bcache", "bonding", "buddyinfo", "conntrack",
		"drbd", "edac", "entropy", "filefd", "hwmon", "infiniband",
		"interrupts", "ipvs", "ksmd", "logind", "mdadm", "meminfo_numa",
		"mountstats", "nfs", "nfsd", "ntp", "qdisc", "runit", "sockstat",
		"supervisord", "systemd", "tcpstat", "textfile", "time", "timex",
		"vmstat", "wifi", "xfs", "zfs",
	)
}
<commit_msg>remove timex from config_linux for compat reasons (#101)<commit_after>package main

func init() {
	registerFilesystemFlags()
	disableCollectors("arp", "bcache", "bonding", "buddyinfo", "conntrack",
		"drbd", "edac", "entropy", "filefd", "hwmon", "infiniband",
		"interrupts", "ipvs", "ksmd", "logind", "mdadm", "meminfo_numa",
		"mountstats", "nfs", "nfsd", "ntp", "qdisc", "runit", "sockstat",
		"supervisord", "systemd", "tcpstat", "textfile", "time", "vmstat",
		"wifi", "xfs", "zfs",
	)
}
<|endoftext|>


<commit_before>package main

import "fmt"

func displayWhatWillChange(rules []Rule) {
	updates := WillUpdateRulesAndTargets(rules)
	deletes := WillDeleteRulesAndTargets(rules)
	if len(updates) == 0 && len(deletes) == 0 {
		fmt.Println("No Changes")
	}
	if len(updates) > 0 {
		fmt.Println("Updates")
		for _, r := range updates {
			ShowWillUpdateFieldInRule(r)
			for _, t := range r.Targets {
				if t.NeedUpdate && !t.NeedDelete {
					ShowWillUpdateFieldInTarget(t)
				}
			}
		}
	}
	if len(deletes) > 0 {
		fmt.Println("Deletes")
		for _, r := range deletes {
			ShowWillDeleteRule(r)
			for _, t := range r.Targets {
				if t.NeedDelete {
					ShowWillDeleteTarget(t)
				}
			}
		}
	}
}

// WillUpdateRulesAndTargets return will be updated rules and targets
func WillUpdateRulesAndTargets(rules []Rule) []Rule {
	u := make([]Rule, 0)
	for _, rule := range rules {
		if rule.NeedUpdate && !rule.NeedDelete {
			u = append(u, rule)
		} else {
			for _, target := range rule.Targets {
				if target.NeedUpdate && !target.NeedDelete {
					u = append(u, rule)
					break
				}
			}
		}
	}
	return u
}

// WillDeleteRulesAndTargets return will be deleted rules and targets
func WillDeleteRulesAndTargets(rules []Rule) []Rule {
	d := make([]Rule, 0)
	for _, rule := range rules {
		if rule.NeedDelete {
			d = append(d, rule)
		} else {
			for _, target := range rule.Targets {
				if target.NeedDelete {
					d = append(d, rule)
					break
				}
			}
		}
	}
	return d
}

// ShowWillUpdateFieldInRule print what will rule changes to stdout
func ShowWillUpdateFieldInRule(rule Rule) {
	fmt.Printf("Rule: %s\n", rule.Name)
	if !CompareString(&rule.Name, rule.ActualRule.Name) {
		fmt.Printf("  Name: %s  ->  %s\n", NilSafeStr(rule.ActualRule.Name), rule.Name)
	}
	if !CompareString(&rule.Description, rule.ActualRule.Description) {
		fmt.Printf("  Description: %s  ->  %s\n", NilSafeStr(rule.ActualRule.Description), rule.Description)
	}
	if !CompareString(&rule.EventPattern, rule.ActualRule.EventPattern) {
		fmt.Printf("  EventPattern: %s  ->  %s\n", NilSafeStr(rule.ActualRule.EventPattern), rule.EventPattern)
	}
	if !CompareString(&rule.RoleArn, rule.ActualRule.RoleArn) {
		fmt.Printf("  RoleArn: %s  ->  %s\n", NilSafeStr(rule.ActualRule.RoleArn), rule.RoleArn)
	}
	if !CompareString(&rule.ScheduleExpression, rule.ActualRule.ScheduleExpression) {
		fmt.Printf("  ScheduleExpression: %s  ->  %s\n", NilSafeStr(rule.ActualRule.ScheduleExpression), rule.ScheduleExpression)
	}
	if !CompareString(&rule.State, rule.ActualRule.State) {
		fmt.Printf("  State: %s  ->  %s\n", NilSafeStr(rule.ActualRule.State), rule.State)
	}
}

// ShowWillUpdateFieldInTarget print what will target changes to stdout
func ShowWillUpdateFieldInTarget(target Target) {
	fmt.Printf("  Target: %s\n", target.Arn)
	if !CompareString(&target.Arn, target.ActualTarget.Arn) {
		fmt.Printf("    Arn: %s  ->  %s\n", NilSafeStr(target.ActualTarget.Arn), target.Arn)
	}
	if !CompareString(&target.Id, target.ActualTarget.Id) {
		fmt.Printf("    Id: %s  ->  %s\n", NilSafeStr(target.ActualTarget.Id), target.Id)
	}
	if !CompareString(&target.Input, target.ActualTarget.Input) {
		fmt.Printf("    Input: %s  ->  %s\n", NilSafeStr(target.ActualTarget.Input), target.Input)
	}
	if !CompareString(&target.InputPath, target.ActualTarget.InputPath) {
		fmt.Printf("    InputPath: %s  ->  %s\n", NilSafeStr(target.ActualTarget.InputPath), target.InputPath)
	}
}

// ShowWillDeleteRule print the rule will delete to stdout
func ShowWillDeleteRule(rule Rule) {
	if rule.NeedDelete {
		fmt.Printf("Rule: %s this will delete\n", *rule.ActualRule.Name)
	} else {
		fmt.Printf("Rule: %s\n", rule.Name)
	}
}

// ShowWillDeleteTarget print the target will delete to stdout
func ShowWillDeleteTarget(target Target) {
	fmt.Printf("  Target: %s this will delete\n", *target.ActualTarget.Id)
}
<commit_msg>Create presenter functions<commit_after>package main

import (
	"fmt"
	"strconv"

	"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)

func displayWhatWillChange(rules []Rule) {
	updates := WillUpdateRulesAndTargets(rules)
	deletes := WillDeleteRulesAndTargets(rules)
	if len(updates) == 0 && len(deletes) == 0 {
		fmt.Println("No Changes")
	}
	if len(updates) > 0 {
		fmt.Println("Updates")
		for _, r := range updates {
			ShowWillUpdateFieldInRule(r)
			for _, t := range r.Targets {
				if t.NeedUpdate && !t.NeedDelete {
					ShowWillUpdateFieldInTarget(t)
				}
			}
		}
	}
	if len(deletes) > 0 {
		fmt.Println("Deletes")
		for _, r := range deletes {
			ShowWillDeleteRule(r)
			for _, t := range r.Targets {
				if t.NeedDelete {
					ShowWillDeleteTarget(t)
				}
			}
		}
	}
}

// WillUpdateRulesAndTargets return will be updated rules and targets
func WillUpdateRulesAndTargets(rules []Rule) []Rule {
	u := make([]Rule, 0)
	for _, rule := range rules {
		if rule.NeedUpdate && !rule.NeedDelete {
			u = append(u, rule)
		} else {
			for _, target := range rule.Targets {
				if target.NeedUpdate && !target.NeedDelete {
					u = append(u, rule)
					break
				}
			}
		}
	}
	return u
}

// WillDeleteRulesAndTargets return will be deleted rules and targets
func WillDeleteRulesAndTargets(rules []Rule) []Rule {
	d := make([]Rule, 0)
	for _, rule := range rules {
		if rule.NeedDelete {
			d = append(d, rule)
		} else {
			for _, target := range rule.Targets {
				if target.NeedDelete {
					d = append(d, rule)
					break
				}
			}
		}
	}
	return d
}

// ShowWillUpdateFieldInRule print what will rule changes to stdout
func ShowWillUpdateFieldInRule(rule Rule) {
	fmt.Printf("Rule: %s\n", rule.Name)
	if !CompareString(&rule.Name, rule.ActualRule.Name) {
		fmt.Printf("  Name: %s  ->  %s\n", NilSafeStr(rule.ActualRule.Name), rule.Name)
	}
	if !CompareString(&rule.Description, rule.ActualRule.Description) {
		fmt.Printf("  Description: %s  ->  %s\n", NilSafeStr(rule.ActualRule.Description), rule.Description)
	}
	if !CompareString(&rule.EventPattern, rule.ActualRule.EventPattern) {
		fmt.Printf("  EventPattern: %s  ->  %s\n", NilSafeStr(rule.ActualRule.EventPattern), rule.EventPattern)
	}
	if !CompareString(&rule.RoleArn, rule.ActualRule.RoleArn) {
		fmt.Printf("  RoleArn: %s  ->  %s\n", NilSafeStr(rule.ActualRule.RoleArn), rule.RoleArn)
	}
	if !CompareString(&rule.ScheduleExpression, rule.ActualRule.ScheduleExpression) {
		fmt.Printf("  ScheduleExpression: %s  ->  %s\n", NilSafeStr(rule.ActualRule.ScheduleExpression), rule.ScheduleExpression)
	}
	if !CompareString(&rule.State, rule.ActualRule.State) {
		fmt.Printf("  State: %s  ->  %s\n", NilSafeStr(rule.ActualRule.State), rule.State)
	}
}

// ShowWillUpdateFieldInTarget print what will target changes to stdout
func ShowWillUpdateFieldInTarget(target Target) {
	fmt.Printf("  Target: %s\n", target.Arn)
	if !CompareString(&target.Arn, target.ActualTarget.Arn) {
		fmt.Printf("    Arn: %s  ->  %s\n", NilSafeStr(target.ActualTarget.Arn), target.Arn)
	}
	if !CompareString(&target.Id, target.ActualTarget.Id) {
		fmt.Printf("    Id: %s  ->  %s\n", NilSafeStr(target.ActualTarget.Id), target.Id)
	}
	if !CompareString(&target.Input, target.ActualTarget.Input) {
		fmt.Printf("    Input: %s  ->  %s\n", NilSafeStr(target.ActualTarget.Input), target.Input)
	}
	if !CompareString(&target.InputPath, target.ActualTarget.InputPath) {
		fmt.Printf("    InputPath: %s  ->  %s\n", NilSafeStr(target.ActualTarget.InputPath), target.InputPath)
	}
}

// ShowDiffOfTheEcsParameters print what will EcsParameters in target changes to stdout
func ShowDiffOfTheEcsParameters(current *cloudwatchevents.EcsParameters, expect EcsParameters) {
	var currTaskDefinitionArn, currTaskCount string
	if current != nil {
		currTaskDefinitionArn = *current.TaskDefinitionArn
		currTaskCount = strconv.FormatInt(*current.TaskCount, 10)
	}

	if !CompareString(current.TaskDefinitionArn, &expect.TaskDefinitionArn) {
		fmt.Printf("      TaskDefinitionArn: %s  ->  %s\n", currTaskDefinitionArn, expect.TaskDefinitionArn)
	}

	if !CompareInt64(current.TaskCount, &expect.TaskCount) {
		fmt.Printf("      TaskCount: %s  ->  %d\n", currTaskCount, expect.TaskCount)
	}
}

// ShowDiffOfTheKinesisParameters print what will KinesisParameters in target changes to stdout
func ShowDiffOfTheKinesisParameters(current *cloudwatchevents.KinesisParameters, expect KinesisParameters) {
	var currPart string
	if current != nil {
		currPart = *current.PartitionKeyPath
	}
	fmt.Printf("      PartitionKeyPath: %s  ->  %s\n", currPart, expect.PartitionKeyPath)
}

// ShowWillDeleteRule print the rule will delete to stdout
func ShowWillDeleteRule(rule Rule) {
	if rule.NeedDelete {
		fmt.Printf("Rule: %s this will delete\n", *rule.ActualRule.Name)
	} else {
		fmt.Printf("Rule: %s\n", rule.Name)
	}
}

// ShowWillDeleteTarget print the target will delete to stdout
func ShowWillDeleteTarget(target Target) {
	fmt.Printf("  Target: %s this will delete\n", *target.ActualTarget.Id)
}
<|endoftext|>


<commit_before>package main

import (
    "fmt"
    "flag"
    "time"
    "net/http"
    "log"
    "github.com/gin-gonic/gin" // An http routing library similar to sinatra
    "github.com/Sirupsen/logrus" // A logging library - we could have used the built in logger, but this one has appenders, etc.
    metrics "github.com/rcrowley/go-metrics" // A Go port of the Coda Hale metrics library
    "math/rand"
    "errors"
)

const FLAG_FAULTY = "faulty"

func main() {
    // Parse command line arguments
    arguments := parseCommandLine()

    // setup a logrus logger as a writer for our metrics logging
    logger := logrus.New()
    writer := logger.Writer()
    defer writer.Close()

    // Kick off background metrics logger that will spit out metric info every 5 seconds
    go metrics.Log(metrics.DefaultRegistry, 12 * time.Second, log.New(writer, "metrics", log.Lmicroseconds))

    // Create a router with default middleware
    router := gin.Default()

    // Add middlewares. They are like servlet filters
    router.Use(counterMiddleware())
    if faulty, _ := arguments[FLAG_FAULTY].(bool) ; faulty {
        router.Use(faultyMiddleware())

    }

    // Create rest endpoints
    router.GET("/hello/:name", metricsWrapper("hello"), hello)
    router.GET("/goodbye/:name", metricsWrapper("goodbye"), goodbye)

    // Start listening
    router.Run()
}

func hello(ctx *gin.Context) {
    name := ctx.Param("name")
    ctx.String(http.StatusOK, "Server says, 'Hello, %s!'", name)
}

func goodbye(ctx *gin.Context) {
    name := ctx.Param("name")
    ctx.String(http.StatusOK, "Server says, 'Goodbye, %s.'", name)
}

func parseCommandLine() map[string]interface{} {
    arguments := make(map[string]interface{})
    faulty :=  flag.Bool(FLAG_FAULTY, false, "Should this server randomly 'fail'")

    flag.Parse()

    arguments[FLAG_FAULTY] = *faulty

    return arguments
}

func metricsWrapper(name string) gin.HandlerFunc {
    // Using a closure. This allows us to create singletons and register them once.
    counter := metrics.NewCounter()
    timer := metrics.NewTimer()

    metrics.Register(fmt.Sprintf("api.%s.counter", name), counter)
    metrics.Register(fmt.Sprintf("api.%s.timer", name), timer)

    return func(ctx *gin.Context) {
        counter.Inc(1)
        start := time.Now()
        ctx.Next()
        timer.UpdateSince(start)
    }
}

func counterMiddleware() gin.HandlerFunc {
    counter := metrics.NewCounter()
    metrics.Register("api.all.counter", counter)

    return func(ctx *gin.Context) {
        counter.Inc(1)
        ctx.Next()
    }
}

func faultyMiddleware() gin.HandlerFunc {
    // Random failure middleware
    return func(ctx *gin.Context) {
        const randMax = 100
        const oneInWhat = 3
        chance := rand.Intn(randMax)
        if chance < randMax / oneInWhat { // Fail 1 in oneInWhat times
            ctx.AbortWithError(http.StatusInternalServerError, errors.New("Random failure"))
        } else {
            ctx.Next()
        }
    }
}
<commit_msg>Updating comments in the webservice<commit_after>package main

import (
    "fmt"
    "flag"
    "time"
    "net/http"
    "log"
    "github.com/gin-gonic/gin" // An http routing library similar to sinatra
    "github.com/Sirupsen/logrus" // A logging library - we could have used the built in logger, but this one has appenders, etc.
    metrics "github.com/rcrowley/go-metrics" // A Go port of the Coda Hale metrics library
    "math/rand"
    "errors"
)

const FLAG_FAULTY = "faulty"

func main() {
    // Parse command line arguments
    arguments := parseCommandLine()

    // setup a logrus logger as a writer for our metrics logging
    logger := logrus.New()
    writer := logger.Writer()
    defer writer.Close()

    // Kick off background metrics logger that will spit out metric info every 5 seconds
    go metrics.Log(metrics.DefaultRegistry, 12 * time.Second, log.New(writer, "metrics", log.Lmicroseconds))

    // Create a router with default middleware
    router := gin.Default()

    // Add middlewares. They are like servlet filters
    router.Use(counterMiddleware())
    if faulty, _ := arguments[FLAG_FAULTY].(bool) ; faulty {
        router.Use(faultyMiddleware())

    }

    // Create rest endpoints
    router.GET("/hello/:name", metricsWrapper("hello"), hello)
    router.GET("/goodbye/:name", metricsWrapper("goodbye"), goodbye)

    // Start listening
    router.Run()
}

func hello(ctx *gin.Context) {
    name := ctx.Param("name")
    ctx.String(http.StatusOK, "Server says, 'Hello, %s!'", name)
}

func goodbye(ctx *gin.Context) {
    name := ctx.Param("name")
    ctx.String(http.StatusOK, "Server says, 'Goodbye, %s.'", name)
}

func parseCommandLine() map[string]interface{} {
    arguments := make(map[string]interface{})
    faulty :=  flag.Bool(FLAG_FAULTY, false, "Should this server randomly 'fail'")

    flag.Parse()

    arguments[FLAG_FAULTY] = *faulty

    return arguments
}

func metricsWrapper(name string) gin.HandlerFunc {
    // Using a closure. This allows us to create middleware scoped objects and register them once.
    counter := metrics.NewCounter()
    timer := metrics.NewTimer()

    metrics.Register(fmt.Sprintf("api.%s.counter", name), counter)
    metrics.Register(fmt.Sprintf("api.%s.timer", name), timer)

    return func(ctx *gin.Context) {
        counter.Inc(1)
        start := time.Now()
        ctx.Next()
        timer.UpdateSince(start)
    }
}

func counterMiddleware() gin.HandlerFunc {
    // Using a closure. This allows us to create middleware scoped objects and register them once.
    counter := metrics.NewCounter()
    metrics.Register("api.all.counter", counter)

    return func(ctx *gin.Context) {
        counter.Inc(1)
        ctx.Next()
    }
}

func faultyMiddleware() gin.HandlerFunc {
    // Random failure middleware
    return func(ctx *gin.Context) {
        const randMax = 100
        const oneInWhat = 3
        chance := rand.Intn(randMax)
        if chance < randMax / oneInWhat { // Fail 1 in oneInWhat times
            ctx.AbortWithError(http.StatusInternalServerError, errors.New("Random failure"))
        } else {
            ctx.Next()
        }
    }
}
<|endoftext|>


<commit_before>package disk

import (
	"bufio"
	"os"
)

type bufferReader struct {
	f      *os.File
	reader *bufio.Reader
}

func newBufferReader(f *os.File) *bufferReader {
	return &bufferReader{
		f:      f,
		reader: bufio.NewReader(f),
	}
}

func (r *bufferReader) Read(b []byte) (n int, err error) {
	return r.reader.Read(b)
}

func (r *bufferReader) Close() error {
	return r.f.Close()
}

func (r *bufferReader) Seek(offset int64, whence int) (ret int64, err error) {
	return r.f.Seek(offset, whence)
}

func (r *bufferReader) Name() string {
	return r.f.Name()
}

type bufferWriter struct {
	f      *os.File
	writer *bufio.Writer
}

func newBufferWriter(f *os.File) *bufferWriter {
	return &bufferWriter{
		f:      f,
		writer: bufio.NewWriter(f),
	}
}

func (w *bufferWriter) Write(p []byte) (nn int, err error) {
	return w.writer.Write(p)
}

func (w *bufferWriter) Sync() error {
	if err := w.writer.Flush(); err != nil { // this will greatly impact perf TODO
		return err
	}
	return w.f.Sync()
}

func (w *bufferWriter) Close() error {
	if err := w.writer.Flush(); err != nil {
		return err
	}
	w.f.Sync()
	return w.f.Close()
}

func (w *bufferWriter) Name() string {
	return w.f.Name()
}
<commit_msg>BUG FIX: bufio reader conflicts with file Seek<commit_after>package disk

import (
	"bufio"
	"os"
)

type bufferReader struct {
	f      *os.File
	reader *bufio.Reader
}

func newBufferReader(f *os.File) *bufferReader {
	return &bufferReader{
		f:      f,
		reader: bufio.NewReader(f),
	}
}

func (r *bufferReader) Read(b []byte) (n int, err error) {
	return r.reader.Read(b)
}

func (r *bufferReader) Close() error {
	return r.f.Close()
}

func (r *bufferReader) Seek(offset int64, whence int) (ret int64, err error) {
	if ret, err = r.f.Seek(offset, whence); err != nil {
		return
	}

	r.reader.Reset(r.f)
	return
}

func (r *bufferReader) Name() string {
	return r.f.Name()
}

type bufferWriter struct {
	f      *os.File
	writer *bufio.Writer
}

func newBufferWriter(f *os.File) *bufferWriter {
	return &bufferWriter{
		f:      f,
		writer: bufio.NewWriter(f),
	}
}

func (w *bufferWriter) Write(p []byte) (nn int, err error) {
	return w.writer.Write(p)
}

func (w *bufferWriter) Sync() error {
	if err := w.writer.Flush(); err != nil { // this will greatly impact perf TODO
		return err
	}
	return w.f.Sync()
}

func (w *bufferWriter) Close() error {
	if err := w.writer.Flush(); err != nil {
		return err
	}
	w.f.Sync()
	return w.f.Close()
}

func (w *bufferWriter) Name() string {
	return w.f.Name()
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/codegangsta/cli"
	. "github.com/tendermint/go-common"
	"github.com/tendermint/tmsp/server"
	"os"

	application "github.com/tendermint/merkleeyes/app"
)

func main() {
	app := cli.NewApp()
	app.Name = "cli"
	app.Usage = "cli [command] [args...]"
	app.Commands = []cli.Command{
		{
			Name:  "server",
			Usage: "Run the MerkleEyes server",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "address",
					Value: "unix://test.sock",
					Usage: "MerkleEyes server listen address",
				},
			},
			Action: func(c *cli.Context) {
				cmdServer(app, c)
			},
		},
	}
	app.Run(os.Args)

}

//--------------------------------------------------------------------------------

func cmdServer(app *cli.App, c *cli.Context) {
	addr := c.String("address")
	mApp := application.NewMerkleEyesApp()

	// Start the listener
	_, err := server.StartListener(addr, mApp)
	if err != nil {
		Exit(err.Error())
	}

	// Wait forever
	TrapSignal(func() {
		// Cleanup
	})
}
<commit_msg>Connect to unix://data.sock by default<commit_after>package main

import (
	"github.com/codegangsta/cli"
	. "github.com/tendermint/go-common"
	"github.com/tendermint/tmsp/server"
	"os"

	application "github.com/tendermint/merkleeyes/app"
)

func main() {
	app := cli.NewApp()
	app.Name = "cli"
	app.Usage = "cli [command] [args...]"
	app.Commands = []cli.Command{
		{
			Name:  "server",
			Usage: "Run the MerkleEyes server",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "address",
					Value: "unix://data.sock",
					Usage: "MerkleEyes server listen address",
				},
			},
			Action: func(c *cli.Context) {
				cmdServer(app, c)
			},
		},
	}
	app.Run(os.Args)

}

//--------------------------------------------------------------------------------

func cmdServer(app *cli.App, c *cli.Context) {
	addr := c.String("address")
	mApp := application.NewMerkleEyesApp()

	// Start the listener
	_, err := server.StartListener(addr, mApp)
	if err != nil {
		Exit(err.Error())
	}

	// Wait forever
	TrapSignal(func() {
		// Cleanup
	})
}
<|endoftext|>


<commit_before>package lint

import (
	"github.com/forseti-security/config-validator/pkg/gcv"
	"github.com/spf13/cobra"
)

var Cmd = &cobra.Command{
	Use:     "lint",
	Short:   "Lint a directory containing ConstraintTemplates and/or Constraints.",
	Example: `policy-tool status --policies ./forseti-security/policy-library/policies --libs ./forseti-security/policy-library/libs`,
	RunE:    lintCmd,
}

var (
	flags struct {
		policies []string
		libs     string
	}
)

func init() {
	Cmd.Flags().StringSliceVar(&flags.policies, "policies", nil, "Path to one or more policies directories.")
	Cmd.Flags().StringVar(&flags.libs, "libs", "", "Path to the libs directory.")
	if err := Cmd.MarkFlagRequired("policies"); err != nil {
		panic(err)
	}
}

func lintCmd(cmd *cobra.Command, args []string) error {
	_, err := gcv.NewValidator(make(chan struct{}), flags.policies, flags.libs)
	return err
}
<commit_msg>Fix linter output.<commit_after>package lint

import (
	"fmt"
	"os"

	"github.com/forseti-security/config-validator/pkg/gcv"
	"github.com/spf13/cobra"
)

var Cmd = &cobra.Command{
	Use:     "lint",
	Short:   "Lint a directory containing ConstraintTemplates and/or Constraints.",
	Example: `policy-tool status --policies ./forseti-security/policy-library/policies --libs ./forseti-security/policy-library/libs`,
	RunE:    lintCmd,
}

var (
	flags struct {
		policies []string
		libs     string
	}
)

func init() {
	Cmd.Flags().StringSliceVar(&flags.policies, "policies", nil, "Path to one or more policies directories.")
	Cmd.Flags().StringVar(&flags.libs, "libs", "", "Path to the libs directory.")
	if err := Cmd.MarkFlagRequired("policies"); err != nil {
		panic(err)
	}
}

func lintCmd(cmd *cobra.Command, args []string) error {
	_, err := gcv.NewValidator(make(chan struct{}), flags.policies, flags.libs)
	if err != nil {
		fmt.Printf("linter errors:\n%s\n", err)
		os.Exit(1)
	}
	fmt.Printf("No lint errors found.\n")
	return nil
}
<|endoftext|>