<commit_before>package aws

import (
	"fmt"
	"regexp"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/wafv2"
	"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccAwsWafv2RegexPatternSet_basic(t *testing.T) {
	var v wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfig(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "2"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.1641128102.regex_string", "one"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.265355341.regex_string", "two"),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "2"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"),
				),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfigUpdate(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", "Updated"),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "3"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.1641128102.regex_string", "one"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.265355341.regex_string", "two"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.2339296779.regex_string", "three"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
				ImportStateIdFunc: testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName),
			},
		},
	})
}

func TestAccAwsWafv2RegexPatternSet_minimal(t *testing.T) {
	var v wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfigMinimal(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", ""),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "1"),
				),
			},
		},
	})
}

func TestAccAwsWafv2RegexPatternSet_changeNameForceNew(t *testing.T) {
	var before, after wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	regexPatternSetNewName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfig(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &before),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "2"),
				),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfig(regexPatternSetNewName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &after),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetNewName),
					resource.TestCheckResourceAttr(resourceName, "description", regexPatternSetNewName),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "2"),
				),
			},
		},
	})
}

func TestAccAwsWafv2RegexPatternSet_tags(t *testing.T) {
	var v wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfigOneTag(regexPatternSetName, "Tag1", "Value1"),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
				ImportStateIdFunc: testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfigTwoTags(regexPatternSetName, "Tag1", "Value1Updated", "Tag2", "Value2"),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "2"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1Updated"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"),
				),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfigOneTag(regexPatternSetName, "Tag2", "Value2"),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"),
				),
			},
		},
	})
}

func testAccCheckAWSWafv2RegexPatternSetDestroy(s *terraform.State) error {
	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_wafv2_regex_pattern_set" {
			continue
		}

		conn := testAccProvider.Meta().(*AWSClient).wafv2conn
		resp, err := conn.GetRegexPatternSet(
			&wafv2.GetRegexPatternSetInput{
				Id:    aws.String(rs.Primary.ID),
				Name:  aws.String(rs.Primary.Attributes["name"]),
				Scope: aws.String(rs.Primary.Attributes["scope"]),
			})

		if err == nil {
			if *resp.RegexPatternSet.Id == rs.Primary.ID {
				return fmt.Errorf("WAFV2 RegexPatternSet %s still exists", rs.Primary.ID)
			}
		}

		// Return nil if the RegexPatternSet is already destroyed
		if awsErr, ok := err.(awserr.Error); ok {
			if awsErr.Code() == wafv2.ErrCodeWAFNonexistentItemException {
				return nil
			}
		}

		return err
	}

	return nil
}

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

		if rs.Primary.ID == "" {
			return fmt.Errorf("No WAFV2 RegexPatternSet ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).wafv2conn
		resp, err := conn.GetRegexPatternSet(&wafv2.GetRegexPatternSetInput{
			Id:    aws.String(rs.Primary.ID),
			Name:  aws.String(rs.Primary.Attributes["name"]),
			Scope: aws.String(rs.Primary.Attributes["scope"]),
		})

		if err != nil {
			return err
		}

		if *resp.RegexPatternSet.Id == rs.Primary.ID {
			*v = *resp.RegexPatternSet
			return nil
		}

		return fmt.Errorf("WAFV2 RegexPatternSet (%s) not found", rs.Primary.ID)
	}
}

func testAccAwsWafv2RegexPatternSetConfig(name string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name = "%s"
  description = "%s"
  scope = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  regular_expression_list {
    regex_string = "two"
  }

  tags = {
    Tag1 = "Value1"
    Tag2 = "Value2"
  }
}
`, name, name)
}

func testAccAwsWafv2RegexPatternSetConfigUpdate(name string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name = "%s"
  description = "Updated"
  scope = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  regular_expression_list {
    regex_string = "two"
  }

  regular_expression_list {
    regex_string = "three"
  }
}
`, name)
}

func testAccAwsWafv2RegexPatternSetConfigMinimal(name string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name = "%s"
  scope = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }
}
`, name)
}

func testAccAwsWafv2RegexPatternSetConfigOneTag(name, tagKey, tagValue string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name = "%s"
  description = "%s"
  scope = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  regular_expression_list {
    regex_string = "two"
  }

  tags = {
    %q = %q
  }
}
`, name, name, tagKey, tagValue)
}

func testAccAwsWafv2RegexPatternSetConfigTwoTags(name, tag1Key, tag1Value, tag2Key, tag2Value string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name = "%s"
  description = "%s"
  scope = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  tags = {
    %q = %q
    %q = %q
  }
}
`, name, name, tag1Key, tag1Value, tag2Key, tag2Value)
}

func testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName string) resource.ImportStateIdFunc {
	return func(s *terraform.State) (string, error) {
		rs, ok := s.RootModule().Resources[resourceName]
		if !ok {
			return "", fmt.Errorf("Not found: %s", resourceName)
		}

		return fmt.Sprintf("%s/%s/%s", rs.Primary.ID, rs.Primary.Attributes["name"], rs.Primary.Attributes["scope"]), nil
	}
}
<commit_msg>Format config code<commit_after>package aws

import (
	"fmt"
	"regexp"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/wafv2"
	"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccAwsWafv2RegexPatternSet_basic(t *testing.T) {
	var v wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfig(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "2"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.1641128102.regex_string", "one"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.265355341.regex_string", "two"),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "2"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"),
				),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfigUpdate(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", "Updated"),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "3"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.1641128102.regex_string", "one"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.265355341.regex_string", "two"),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.2339296779.regex_string", "three"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
				ImportStateIdFunc: testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName),
			},
		},
	})
}

func TestAccAwsWafv2RegexPatternSet_minimal(t *testing.T) {
	var v wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfigMinimal(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", ""),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "1"),
				),
			},
		},
	})
}

func TestAccAwsWafv2RegexPatternSet_changeNameForceNew(t *testing.T) {
	var before, after wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	regexPatternSetNewName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfig(regexPatternSetName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &before),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "description", regexPatternSetName),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "2"),
				),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfig(regexPatternSetNewName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &after),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "name", regexPatternSetNewName),
					resource.TestCheckResourceAttr(resourceName, "description", regexPatternSetNewName),
					resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional),
					resource.TestCheckResourceAttr(resourceName, "regular_expression_list.#", "2"),
				),
			},
		},
	})
}

func TestAccAwsWafv2RegexPatternSet_tags(t *testing.T) {
	var v wafv2.RegexPatternSet
	regexPatternSetName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5))
	resourceName := "aws_wafv2_regex_pattern_set.test"

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccAwsWafv2RegexPatternSetConfigOneTag(regexPatternSetName, "Tag1", "Value1"),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"),
				),
			},
			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
				ImportStateIdFunc: testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfigTwoTags(regexPatternSetName, "Tag1", "Value1Updated", "Tag2", "Value2"),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "2"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1Updated"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"),
				),
			},
			{
				Config: testAccAwsWafv2RegexPatternSetConfigOneTag(regexPatternSetName, "Tag2", "Value2"),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSWafv2RegexPatternSetExists("aws_wafv2_regex_pattern_set.test", &v),
					testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)),
					resource.TestCheckResourceAttr(resourceName, "tags.%", "1"),
					resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"),
				),
			},
		},
	})
}

func testAccCheckAWSWafv2RegexPatternSetDestroy(s *terraform.State) error {
	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_wafv2_regex_pattern_set" {
			continue
		}

		conn := testAccProvider.Meta().(*AWSClient).wafv2conn
		resp, err := conn.GetRegexPatternSet(
			&wafv2.GetRegexPatternSetInput{
				Id:    aws.String(rs.Primary.ID),
				Name:  aws.String(rs.Primary.Attributes["name"]),
				Scope: aws.String(rs.Primary.Attributes["scope"]),
			})

		if err == nil {
			if *resp.RegexPatternSet.Id == rs.Primary.ID {
				return fmt.Errorf("WAFV2 RegexPatternSet %s still exists", rs.Primary.ID)
			}
		}

		// Return nil if the RegexPatternSet is already destroyed
		if awsErr, ok := err.(awserr.Error); ok {
			if awsErr.Code() == wafv2.ErrCodeWAFNonexistentItemException {
				return nil
			}
		}

		return err
	}

	return nil
}

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

		if rs.Primary.ID == "" {
			return fmt.Errorf("No WAFV2 RegexPatternSet ID is set")
		}

		conn := testAccProvider.Meta().(*AWSClient).wafv2conn
		resp, err := conn.GetRegexPatternSet(&wafv2.GetRegexPatternSetInput{
			Id:    aws.String(rs.Primary.ID),
			Name:  aws.String(rs.Primary.Attributes["name"]),
			Scope: aws.String(rs.Primary.Attributes["scope"]),
		})

		if err != nil {
			return err
		}

		if *resp.RegexPatternSet.Id == rs.Primary.ID {
			*v = *resp.RegexPatternSet
			return nil
		}

		return fmt.Errorf("WAFV2 RegexPatternSet (%s) not found", rs.Primary.ID)
	}
}

func testAccAwsWafv2RegexPatternSetConfig(name string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name        = "%s"
  description = "%s"
  scope       = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  regular_expression_list {
    regex_string = "two"
  }

  tags = {
    Tag1 = "Value1"
    Tag2 = "Value2"
  }
}
`, name, name)
}

func testAccAwsWafv2RegexPatternSetConfigUpdate(name string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name        = "%s"
  description = "Updated"
  scope       = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  regular_expression_list {
    regex_string = "two"
  }

  regular_expression_list {
    regex_string = "three"
  }
}
`, name)
}

func testAccAwsWafv2RegexPatternSetConfigMinimal(name string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name  = "%s"
  scope = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }
}
`, name)
}

func testAccAwsWafv2RegexPatternSetConfigOneTag(name, tagKey, tagValue string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name        = "%s"
  description = "%s"
  scope       = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  regular_expression_list {
    regex_string = "two"
  }

  tags = {
    "%s" = "%s"
  }
}
`, name, name, tagKey, tagValue)
}

func testAccAwsWafv2RegexPatternSetConfigTwoTags(name, tag1Key, tag1Value, tag2Key, tag2Value string) string {
	return fmt.Sprintf(`
resource "aws_wafv2_regex_pattern_set" "test" {
  name        = "%s"
  description = "%s"
  scope       = "REGIONAL"

  regular_expression_list {
    regex_string = "one"
  }

  tags = {
    "%s" = "%s"
    "%s" = "%s"
  }
}
`, name, name, tag1Key, tag1Value, tag2Key, tag2Value)
}

func testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName string) resource.ImportStateIdFunc {
	return func(s *terraform.State) (string, error) {
		rs, ok := s.RootModule().Resources[resourceName]
		if !ok {
			return "", fmt.Errorf("Not found: %s", resourceName)
		}

		return fmt.Sprintf("%s/%s/%s", rs.Primary.ID, rs.Primary.Attributes["name"], rs.Primary.Attributes["scope"]), nil
	}
}
<|endoftext|>


<commit_before>// (c) 2012 Alexander Solovyov
// under terms of ISC license

// Generating example site

package main

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"unicode"
)

var ExampleConfig = `
TEMPLATES = site.tmpl
SOURCE = src
OUTPUT = site
TITLE = Example Site
URL = http://example.com/
AUTHOR = Your Name

blog/*.md:
	config
	ext .html
	directorify
	tags tags/*.tag
	markdown
	template post
	template page

*.tag: blog/*.md
	ext .html
	directorify
	template tag
	markdown
	template page

blog.atom: blog/*.md
	inner-template

index.html: blog/*.md
	config
	inner-template
	template page
`

var ExampleMakefile = `
GS ?= gostatic

compile:
	$(GS) config

w:
	$(GS) -w config
`

var ExampleTemplate = `
{{ define "header" }}<!doctype html>

  <meta charset="utf-8">
  <meta name="author" content="{{ html .Site.Other.Author }}">
  <link rel="alternate" type="application/atom+xml" title="{{ html .Site.Other.Title }} feed" href="{{ .Rel "blog.atom" }}">
  <title>{{ .Site.Other.Title }}{{ if .Title }}: {{ .Title }}{{ end }}</title>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="{{ .Rel "static/style.css" }}">

{{ end }}

{{ define "footer" }}

{{ end }}

{{define "date"}}
<time datetime="{{ .Format "2006-01-02T15:04:05Z07:00" }}">
  {{ .Format "2006, January 02" }}
</time>
{{end}}

{{ define "page" }}{{ template "header" . }}
  {{ .Content }}
{{ template "footer" . }}{{ end }}

{{ define "post" }}

{{ .Title }}

      {{ template "date" .Date }} —
      {{ range $i, $t := .Tags }}{{if $i}},{{end}}
      {{ $t }}{{ end }}

  {{ .Content }}

{{ end }}

{{define "tag"}}
# Pages tagged with {{ .Title }}
{{ range .Site.Pages.WithTag .Title }}
- [{{ .Title }}](../../{{ .Url }})
{{ end }}
{{ end }}
`

var ExampleIndex = `
title: Main Page
----

{{ range .Site.Pages.Children "blog/" }}

{{ template "date" .Date }} - {{ .Title }}
{{ end }}

`

var ExampleFeed = `
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0">
  <id>{{ .Site.Other.Url }}</id>
  <title>{{ .Site.Other.Title }}</title>
  {{ with .Site.Pages.Children "blog/" }}
  <updated>{{ .First.Date.Format "2006-01-02T15:04:05Z07:00" }}</updated>
  {{ end }}
  <author><name>{{ .Site.Other.Author }}</name></author>
  <link href="{{ .Site.Other.Url }}" rel="alternate"></link>
  <generator uri="http://github.com/piranha/gostatic/">gostatic</generator>

{{ with .Site.Pages.Children "blog/" }}
{{ range .Slice 0 5 }}
<entry>
  <id>{{ .Url }}</id>
  <author><name>{{ or .Other.Author .Site.Other.Author }}</name></author>
  <title type="html">{{ html .Title }}</title>
  <published>{{ .Date.Format "2006-01-02T15:04:05Z07:00" }}</published>
  {{ range .Tags }}
  <category term="{{ . }}"></category>
  {{ end }}
  <link href="{{ .Site.Other.Url }}{{ .Url }}" rel="alternate"></link>
  <content type="html">
    {{/* .Process runs here in case only feed changed */}}
    {{ with cut .Process.Content "
" "
" }}
      {{ html . }}
    {{ end }}
  </content>
</entry>
{{ end }}
{{ end }}
</feed>
`

var ExamplePost = `
title: First Post
date: 2012-12-12
tags: blog
----
My first post with [gostatic](http://github.com/piranha/gostatic/).
`

var ExampleStyle = `
/* put your style rules here */
`

func WriteExample(dir string) error {
	WriteFile(dir, "config", ExampleConfig)
	WriteFile(dir, "Makefile", ExampleMakefile)
	WriteFile(dir, "site.tmpl", ExampleTemplate)
	WriteFile(dir, "src/index.html", ExampleIndex)
	WriteFile(dir, "src/blog/first.md", ExamplePost)
	WriteFile(dir, "src/blog.atom", ExampleFeed)
	WriteFile(dir, "src/static/style.css", ExampleStyle)
	return nil
}

func WriteFile(dir string, fn string, content string) error {
	path := filepath.Join(dir, filepath.FromSlash(fn))
	dir = filepath.Dir(path)

	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}

	towrite := []byte(strings.TrimLeftFunc(content, unicode.IsSpace))
	if err := ioutil.WriteFile(path, towrite, 0644); err != nil {
		return err
	}

	return nil
}
<commit_msg>Update example site feed for 2.x<commit_after>// (c) 2012 Alexander Solovyov
// under terms of ISC license

// Generating example site

package main

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"unicode"
)

var ExampleConfig = `
TEMPLATES = site.tmpl
SOURCE = src
OUTPUT = site
TITLE = Example Site
URL = http://example.com/
AUTHOR = Your Name

blog/*.md:
	config
	ext .html
	directorify
	tags tags/*.tag
	markdown
	template post
	template page

*.tag: blog/*.md
	ext .html
	directorify
	template tag
	markdown
	template page

blog.atom: blog/*.md
	inner-template

index.html: blog/*.md
	config
	inner-template
	template page
`

var ExampleMakefile = `
GS ?= gostatic

compile:
	$(GS) config

w:
	$(GS) -w config
`

var ExampleTemplate = `
{{ define "header" }}<!doctype html>

  <meta charset="utf-8">
  <meta name="author" content="{{ html .Site.Other.Author }}">
  <link rel="alternate" type="application/atom+xml" title="{{ html .Site.Other.Title }} feed" href="{{ .Rel "blog.atom" }}">
  <title>{{ .Site.Other.Title }}{{ if .Title }}: {{ .Title }}{{ end }}</title>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="{{ .Rel "static/style.css" }}">

{{ end }}

{{ define "footer" }}

{{ end }}

{{define "date"}}
<time datetime="{{ .Format "2006-01-02T15:04:05Z07:00" }}">
  {{ .Format "2006, January 02" }}
</time>
{{end}}

{{ define "page" }}{{ template "header" . }}
  {{ .Content }}
{{ template "footer" . }}{{ end }}

{{ define "post" }}

{{ .Title }}

      {{ template "date" .Date }} —
      {{ range $i, $t := .Tags }}{{if $i}},{{end}}
      {{ $t }}{{ end }}

  {{ .Content }}

{{ end }}

{{define "tag"}}
# Pages tagged with {{ .Title }}
{{ range .Site.Pages.WithTag .Title }}
- [{{ .Title }}](../../{{ .Url }})
{{ end }}
{{ end }}
`

var ExampleIndex = `
title: Main Page
----

{{ range .Site.Pages.Children "blog/" }}

{{ template "date" .Date }} - {{ .Title }}
{{ end }}

`

var ExampleFeed = `
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0">
  <id>{{ .Site.Other.Url }}</id>
  <title>{{ .Site.Other.Title }}</title>
  {{ with .Site.Pages.Children "blog/" }}
  <updated>{{ .First.Date.Format "2006-01-02T15:04:05Z07:00" }}</updated>
  {{ end }}
  <author><name>{{ .Site.Other.Author }}</name></author>
  <link href="{{ .Site.Other.Url }}" rel="alternate"></link>
  <generator uri="http://github.com/piranha/gostatic/">gostatic</generator>

{{ with .Site.Pages.Children "blog/" }}
{{ range .Slice 0 5 }}
<entry>
  <id>{{ .Url }}</id>
  <author><name>{{ or .Other.Author .Site.Other.Author }}</name></author>
  <title type="html">{{ html .Title }}</title>
  <published>{{ .Date.Format "2006-01-02T15:04:05Z07:00" }}</published>
  {{ range .Tags }}
  <category term="{{ . }}"></category>
  {{ end }}
  <link href="{{ .Site.Other.Url }}{{ .Url }}" rel="alternate"></link>
  <content type="html">
    {{/* .Process runs here in case only feed changed */}}
    {{ with cut "
" "
" .Process.Content }}
      {{ html . }}
    {{ end }}
  </content>
</entry>
{{ end }}
{{ end }}
</feed>
`

var ExamplePost = `
title: First Post
date: 2012-12-12
tags: blog
----
My first post with [gostatic](http://github.com/piranha/gostatic/).
`

var ExampleStyle = `
/* put your style rules here */
`

func WriteExample(dir string) error {
	WriteFile(dir, "config", ExampleConfig)
	WriteFile(dir, "Makefile", ExampleMakefile)
	WriteFile(dir, "site.tmpl", ExampleTemplate)
	WriteFile(dir, "src/index.html", ExampleIndex)
	WriteFile(dir, "src/blog/first.md", ExamplePost)
	WriteFile(dir, "src/blog.atom", ExampleFeed)
	WriteFile(dir, "src/static/style.css", ExampleStyle)
	return nil
}

func WriteFile(dir string, fn string, content string) error {
	path := filepath.Join(dir, filepath.FromSlash(fn))
	dir = filepath.Dir(path)

	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}

	towrite := []byte(strings.TrimLeftFunc(content, unicode.IsSpace))
	if err := ioutil.WriteFile(path, towrite, 0644); err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>// +build ignore

package main

import (
	"go/build"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/Masterminds/semver"
	"github.com/sdboyer/gps"
)

// This is probably the simplest possible implementation of gps. It does the
// substantive work that `go get` does, except:
//  1. It drops the resulting tree into vendor instead of GOPATH
//  2. It prefers semver tags (if available) over branches
//  3. It removes any vendor directories nested within dependencies
//
//  This will compile and work...and then blow away any vendor directory present
//  in the cwd. Be careful!
func main() {
	// Operate on the current directory
	root, _ := os.Getwd()
	// Assume the current directory is correctly placed on a GOPATH, and derive
	// the ProjectRoot from it
	srcprefix := filepath.Join(build.Default.GOPATH, "src") + string(filepath.Separator)
	importroot := filepath.ToSlash(strings.TrimPrefix(root, srcprefix))

	// Set up params, including tracing
	params := gps.SolveParameters{
		RootDir:     root,
		Trace:       true,
		TraceLogger: log.New(os.Stdout, "", 0),
	}
	params.RootPackageTree, _ = gps.ListPackages(root, importroot)

	// Set up a SourceManager with the NaiveAnalyzer
	sourcemgr, _ := gps.NewSourceManager(NaiveAnalyzer{}, ".repocache")
	defer sourcemgr.Release()

	// Prep and run the solver
	solver, _ := gps.Prepare(params, sourcemgr)
	solution, err := solver.Solve()
	if err == nil {
		// If no failure, blow away the vendor dir and write a new one out,
		// stripping nested vendor directories as we go.
		os.RemoveAll(filepath.Join(root, "vendor"))
		gps.WriteDepTree(filepath.Join(root, "vendor"), solution, sourcemgr, true)
	}
}

type NaiveAnalyzer struct{}

// DeriveManifestAndLock gets called when the solver needs manifest/lock data
// for a particular project (the gps.ProjectRoot parameter) at a particular
// version. That version will be checked out in a directory rooted at path.
func (a NaiveAnalyzer) DeriveManifestAndLock(path string, n gps.ProjectRoot) (gps.Manifest, gps.Lock, error) {
	return nil, nil, nil
}

// Reports the name and version of the analyzer. This is mostly irrelevant.
func (a NaiveAnalyzer) Info() (name string, version *semver.Version) {
	v, _ := semver.NewVersion("v0.0.1")
	return "example-analyzer", v
}
<commit_msg>Touch up some docs<commit_after>// +build ignore

package main

import (
	"go/build"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/Masterminds/semver"
	"github.com/sdboyer/gps"
)

// This is probably the simplest possible implementation of gps. It does the
// substantive work that `go get` does, except:
//  1. It drops the resulting tree into vendor instead of GOPATH
//  2. It prefers semver tags (if available) over branches
//  3. It removes any vendor directories nested within dependencies
//
//  This will compile and work...and then blow away any vendor directory present
//  in the cwd. Be careful!
func main() {
	// Assume the current directory is correctly placed on a GOPATH, and that it's the
	// root of the project.
	root, _ := os.Getwd()
	srcprefix := filepath.Join(build.Default.GOPATH, "src") + string(filepath.Separator)
	importroot := filepath.ToSlash(strings.TrimPrefix(root, srcprefix))

	// Set up params, including tracing
	params := gps.SolveParameters{
		RootDir:     root,
		Trace:       true,
		TraceLogger: log.New(os.Stdout, "", 0),
	}
	// Perform static analysis on the current project to find all of its imports.
	params.RootPackageTree, _ = gps.ListPackages(root, importroot)

	// Set up a SourceManager. This manages interaction with sources (repositories).
	sourcemgr, _ := gps.NewSourceManager(NaiveAnalyzer{}, ".repocache")
	defer sourcemgr.Release()

	// Prep and run the solver
	solver, _ := gps.Prepare(params, sourcemgr)
	solution, err := solver.Solve()
	if err == nil {
		// If no failure, blow away the vendor dir and write a new one out,
		// stripping nested vendor directories as we go.
		os.RemoveAll(filepath.Join(root, "vendor"))
		gps.WriteDepTree(filepath.Join(root, "vendor"), solution, sourcemgr, true)
	}
}

type NaiveAnalyzer struct{}

// DeriveManifestAndLock is called when the solver needs manifest/lock data
// for a particular dependency project (identified by the gps.ProjectRoot
// parameter) at a particular version. That version will be checked out in a
// directory rooted at path.
func (a NaiveAnalyzer) DeriveManifestAndLock(path string, n gps.ProjectRoot) (gps.Manifest, gps.Lock, error) {
	return nil, nil, nil
}

// Reports the name and version of the analyzer. This is used internally as part
// of gps' hashing memoization scheme.
func (a NaiveAnalyzer) Info() (name string, version *semver.Version) {
	v, _ := semver.NewVersion("v0.0.1")
	return "example-analyzer", v
}
<|endoftext|>


<commit_before>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

package main

import (
	"fmt"
	"os"
	"sort"
	"strconv"
	"io/ioutil"
	"encoding/json"
)

type Node struct {
	value string
	pattern string
	key uint8
	nodes map[uint8] *Node
}

func NewNode() *Node {
	return &Node{
		nodes: make(map[uint8] *Node),
	}
}

func BuildGraph(mapping map[string]string) (*Node) {

	var keys []string
	for k := range mapping {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	root := NewNode()
	for _, k := range keys {
		var tree = root
		for i := 0; i < len(k); i++ {
			key := k[i]
			sub, ok := tree.nodes[key];
			if !ok {
				sub = NewNode()
				tree.nodes[key] = sub
			}
			sub.key = key
			tree = sub
		}
		tree.value = mapping[k]
		tree.pattern = k
	}
	return root
}

func WriteSwitch(root *Node, depth int, indent string)  {

	indent += "  "

	if len(root.nodes) == 0 {
		fmt.Println(indent + "return QPair<int, int>(0, 0); // no deeper pattern")
		return
	}

	if (depth == 0) {
		fmt.Println(indent + "if (i >= length)")
		fmt.Println(indent + "  return QPair<int, int>(0, 0);")
		fmt.Println(indent + "switch (text[i].unicode()) {")
	} else {
		fmt.Println(indent + "if (i + " + strconv.Itoa(depth) + " >= length)")
		fmt.Println(indent + "  return QPair<int, int>(0, 0);")
		fmt.Println(indent + "switch (text[i + " + strconv.Itoa(depth) + "].unicode()) {")
	}

	for key := range root.nodes {
		sub, _ := root.nodes[key]
		if len(sub.value) > 0 { // we have a match
			fmt.Println(indent + "  case " + strconv.Itoa(int(key)) + ":")
			fmt.Println(indent + "    if (i + " + strconv.Itoa(depth + 1) + " >= length || text[i + " + strconv.Itoa(depth + 1) + "].isSpace() || text[i + " + strconv.Itoa(depth + 1) + "].isPunct())")
			fmt.Println(indent + "      return QPair<int, int>(0x" + sub.value + ", " + strconv.Itoa(depth + 1 ) + ");" + " // " + sub.pattern + " found")
			WriteSwitch(sub, depth + 1, indent + "  ")

		} else { // continue searching
			fmt.Println(indent + "  case " + strconv.Itoa(int(key)) + ": ")
			WriteSwitch(sub, depth + 1, indent + "  ")
		}
	}
	fmt.Println(indent + "  default: return QPair<int, int>(0, 0);");
	fmt.Println(indent + "}")
}

func WriteFunc(root *Node) {
	fmt.Println("// Generated by the CDAWG tool by Cutehacks AS.")
	fmt.Println("// See https://github.com/Cutehacks/cdawg\n")
	fmt.Println("#include <QPair>")
	fmt.Println("#include <QString>\n")
	fmt.Println("QPair<int, int> cdawg_match(const QString &text, int length, int i)\n{")
	WriteSwitch(root, 0, "")
	fmt.Println("  return QPair<int, int>(0, 0);")
	fmt.Println("}")
}

func main() {

	data, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println(err)
		return
	}

	var mapping map[string]string
	err = json.Unmarshal([]byte(data), &mapping)
	if err != nil {
		fmt.Println(err)
		return
	}

	WriteFunc(BuildGraph(mapping))
}<commit_msg>Support multi-codepoint emojis<commit_after>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

package main

import (
	"fmt"
	"os"
	"sort"
	"strconv"
        "strings"
	"io/ioutil"
	"encoding/json"
)

type Node struct {
	value string
	pattern string
	key uint8
	nodes map[uint8] *Node
}

func NewNode() *Node {
	return &Node{
		nodes: make(map[uint8] *Node),
	}
}

func BuildGraph(mapping map[string]string) (*Node) {

	var keys []string
	for k := range mapping {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	root := NewNode()
	for _, k := range keys {
		var tree = root
		for i := 0; i < len(k); i++ {
			key := k[i]
			sub, ok := tree.nodes[key];
			if !ok {
				sub = NewNode()
				tree.nodes[key] = sub
			}
			sub.key = key
			tree = sub
		}
		tree.value = mapping[k]
		tree.pattern = k
	}
	return root
}

func WriteSwitch(root *Node, depth int, indent string)  {

	indent += "  "

	if len(root.nodes) == 0 {
		fmt.Println(indent + "return QPair<const uint *, int>(0, 0); // no deeper pattern")
		return
	}

	if (depth == 0) {
		fmt.Println(indent + "if (i >= length)")
		fmt.Println(indent + "  return QPair<const uint *, int>(0, 0);")
		fmt.Println(indent + "switch (text[i].unicode()) {")
	} else {
		fmt.Println(indent + "if (i + " + strconv.Itoa(depth) + " >= length)")
		fmt.Println(indent + "  return QPair<const uint *, int>(0, 0);")
		fmt.Println(indent + "switch (text[i + " + strconv.Itoa(depth) + "].unicode()) {")
	}

	for key := range root.nodes {
		sub, _ := root.nodes[key]
		if len(sub.value) > 0 { // we have a match
			fmt.Println(indent + "  case " + strconv.Itoa(int(key)) + ":")
			fmt.Println(indent + "    if (i + " + strconv.Itoa(depth + 1) + " >= length || text[i + " + strconv.Itoa(depth + 1) + "].isSpace() || text[i + " + strconv.Itoa(depth + 1) + "].isPunct()) {")
			fmt.Println(indent + "      static const uint unicode[] = { 0x" + strings.Replace(sub.value, "-", ", 0x", -1) + ", 0 };")
			fmt.Println(indent + "      return QPair<const uint *, int>(unicode, " + strconv.Itoa(depth + 1 ) + ");" + " // " + sub.pattern + " found")
			fmt.Println(indent + "    }")
			WriteSwitch(sub, depth + 1, indent + "  ")

		} else { // continue searching
			fmt.Println(indent + "  case " + strconv.Itoa(int(key)) + ": ")
			WriteSwitch(sub, depth + 1, indent + "  ")
		}
	}
	fmt.Println(indent + "  default: return QPair<const uint *, int>(0, 0);");
	fmt.Println(indent + "}")
}

func WriteFunc(root *Node) {
	fmt.Println("// Generated by the CDAWG tool by Cutehacks AS.")
	fmt.Println("// See https://github.com/Cutehacks/cdawg\n")
	fmt.Println("#include <QPair>")
	fmt.Println("#include <QString>\n")
	fmt.Println("QPair<const uint *, int> cdawg_match(const QString &text, int length, int i)\n{")
	WriteSwitch(root, 0, "")
	fmt.Println("  return QPair<const uint *, int>(0, 0);")
	fmt.Println("}")
}

func main() {

	data, err := ioutil.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println(err)
		return
	}

	var mapping map[string]string
	err = json.Unmarshal([]byte(data), &mapping)
	if err != nil {
		fmt.Println(err)
		return
	}

	WriteFunc(BuildGraph(mapping))
}
<|endoftext|>


<commit_before>
package main

import (
    "fmt"
    "log"
    "time"
    "errors"
    "strings"
    "strconv"
    "net"
    "net/http"
)

const (
    // The HTTP method used for each test
    HTTP_METHOD = "HEAD"
    // Check the URL every 3 seconds
    CHECK_INTERVAL = 3
    // If the test keeps the same state for 1 week, stop it
    CHECK_DURATION = 604800
    // Check every 1 minute if we break the check
    CHECK_BREAK_INTERVAL = 60
    // Connection timeout is 3 seconds by default
    CONNECTION_TIMEOUT = 3
    // IO timeout applies after the connection
    IO_TIMEOUT = 3
    // User-Agent for all tests
    USER_AGENT = "dotCloud-HealthCheck/1.0 go/1.0.3"
)

var (
    httpClient *http.Client
    httpMethod string
    checkInterval time.Duration
    checkDuration = time.Duration(CHECK_DURATION) * time.Second
    checkBreakInterval = time.Duration(CHECK_BREAK_INTERVAL) * time.Second
    connectionTimeout time.Duration
    ioTimeout time.Duration
    userAgent string
)

type Check struct {
    BackendUrl string
    BackendId int
    BackendGroupLength int
    FrontendKey string

    // Map string used to store meta-data related to the check
    MetaDataStore map[string]string

    // Called when backend dies
    deadCallback func ()
    // Called when the backend comes back to life
    aliveCallback func ()
    // Called every CHECK_BREAK_INTERVAL to stop the routine if returned true
    checkIfBreakCallback func () bool
    // Called when the check exits
    exitCallback func ()
}

func NewCheck(line string) (*Check, error) {
    parts := strings.Split(strings.TrimSpace(line), ";")
    if len(parts) != 4 {
        return nil, errors.New("Invalid check line")
    }
    backendId, _ := strconv.Atoi(parts[2])
    backendGroupLength, _ := strconv.Atoi(parts[3])
    c := &Check{BackendUrl: parts[1], BackendId: backendId,
        BackendGroupLength: backendGroupLength, FrontendKey: parts[0]}
    c.MetaDataStore = make(map[string]string)
    return c, nil
}

func createHttpTransport() (*http.Transport) {
    httpDial := func (proto string, addr string) (net.Conn, error) {
        conn, err := net.DialTimeout(proto, addr, connectionTimeout)
        if err != nil {
            return nil, err
        }
        conn.SetDeadline(time.Now().Add(ioTimeout))
        return conn, nil
    }
    return &http.Transport{
        DisableKeepAlives: true,
        Dial: httpDial,
    }
}

func (c *Check) SetDeadCallback(callback func ()) {
    c.deadCallback = callback
}

func (c *Check) SetAliveCallback(callback func ()) {
    c.aliveCallback = callback
}

func (c *Check) SetCheckIfBreakCallback(callback func () bool) {
    c.checkIfBreakCallback = callback
}

func (c *Check) SetExitCallback(callback func ()) {
    c.exitCallback = callback
}

func (c* Check) PingUrl() {
    // Current status, true for alive, false for dead
    var (
        testError string
        lastDeadCall time.Time
        lastStateChange = time.Now()
        status = true
        newStatus = true
        i = time.Duration(0)
        )
    if httpClient == nil {
        httpClient = &http.Client{Transport: createHttpTransport()}
    }
    for {
        req, _ := http.NewRequest(httpMethod, c.BackendUrl, nil)
        req.Header.Add("User-Agent", userAgent)
        resp, err := httpClient.Do(req)
        if err != nil {
            // TCP error
            newStatus = false
            testError = fmt.Sprintf("TCP error on %s: %#v",
                c.BackendUrl, err.Error())
        } else {
            // No TCP error, checking HTTP code
            if resp.StatusCode > 500 && resp.StatusCode < 600 &&
                resp.StatusCode != 503 {
                    newStatus = false
                    testError = fmt.Sprintf("HTTP error on %s: %#v",
                        c.BackendUrl, resp.StatusCode)
                } else {
                    newStatus = true
                }
        }
        // Check if the status changed before updating Redis
        if newStatus != status {
            lastStateChange = time.Now()
            if newStatus == true {
                log.Printf("%s is back online\n", c.BackendUrl)
                if c.aliveCallback != nil {
                    c.aliveCallback()
                }
                lastDeadCall = time.Time{}
            } else {
                log.Println(testError)
                if c.deadCallback != nil {
                    c.deadCallback()
                }
                lastDeadCall = time.Now()
            }
        } else if newStatus == false {
            // Backend is still dead. Mark it as dead every 30 seconds to keep
            // it dead despite the Redis TTL
            if lastDeadCall.IsZero() == false &&
                time.Since(lastDeadCall) >=
                (time.Duration(30) * time.Second) {
                    if c.deadCallback != nil {
                        c.deadCallback()
                    }
                    lastDeadCall = time.Now()
                }
        }
        status = newStatus
        time.Sleep(checkInterval)
        i += checkInterval
        // At longer interval, we check if still have the lock on the backend
        if i >= checkBreakInterval {
            if c.checkIfBreakCallback != nil &&
                c.checkIfBreakCallback() == true {
                    log.Printf("Lost the lock for %s\n", c.BackendUrl)
                    break
            }
            // Let's see if the check is in the same state for a while
            if time.Since(lastStateChange) >= checkDuration {
                log.Printf("%s stayed in the same state for a long time\n",
                    c.BackendUrl)
                break
            }
            i = time.Duration(0)
        }
    }
    if c.exitCallback != nil {
        c.exitCallback()
    }
}
<commit_msg>Updated the default CHECK_DURATION to 1 hour<commit_after>
package main

import (
    "fmt"
    "log"
    "time"
    "errors"
    "strings"
    "strconv"
    "net"
    "net/http"
)

const (
    // The HTTP method used for each test
    HTTP_METHOD = "HEAD"
    // Check the URL every 3 seconds
    CHECK_INTERVAL = 3
    // If the test keeps the same state for 1 hour, stop it
    CHECK_DURATION = 3600
    // Check every 1 minute if we break the check
    CHECK_BREAK_INTERVAL = 60
    // Connection timeout is 3 seconds by default
    CONNECTION_TIMEOUT = 3
    // IO timeout applies after the connection
    IO_TIMEOUT = 3
    // User-Agent for all tests
    USER_AGENT = "dotCloud-HealthCheck/1.0 go/1.0.3"
)

var (
    httpClient *http.Client
    httpMethod string
    checkInterval time.Duration
    checkDuration = time.Duration(CHECK_DURATION) * time.Second
    checkBreakInterval = time.Duration(CHECK_BREAK_INTERVAL) * time.Second
    connectionTimeout time.Duration
    ioTimeout time.Duration
    userAgent string
)

type Check struct {
    BackendUrl string
    BackendId int
    BackendGroupLength int
    FrontendKey string

    // Map string used to store meta-data related to the check
    MetaDataStore map[string]string

    // Called when backend dies
    deadCallback func ()
    // Called when the backend comes back to life
    aliveCallback func ()
    // Called every CHECK_BREAK_INTERVAL to stop the routine if returned true
    checkIfBreakCallback func () bool
    // Called when the check exits
    exitCallback func ()
}

func NewCheck(line string) (*Check, error) {
    parts := strings.Split(strings.TrimSpace(line), ";")
    if len(parts) != 4 {
        return nil, errors.New("Invalid check line")
    }
    backendId, _ := strconv.Atoi(parts[2])
    backendGroupLength, _ := strconv.Atoi(parts[3])
    c := &Check{BackendUrl: parts[1], BackendId: backendId,
        BackendGroupLength: backendGroupLength, FrontendKey: parts[0]}
    c.MetaDataStore = make(map[string]string)
    return c, nil
}

func createHttpTransport() (*http.Transport) {
    httpDial := func (proto string, addr string) (net.Conn, error) {
        conn, err := net.DialTimeout(proto, addr, connectionTimeout)
        if err != nil {
            return nil, err
        }
        conn.SetDeadline(time.Now().Add(ioTimeout))
        return conn, nil
    }
    return &http.Transport{
        DisableKeepAlives: true,
        Dial: httpDial,
    }
}

func (c *Check) SetDeadCallback(callback func ()) {
    c.deadCallback = callback
}

func (c *Check) SetAliveCallback(callback func ()) {
    c.aliveCallback = callback
}

func (c *Check) SetCheckIfBreakCallback(callback func () bool) {
    c.checkIfBreakCallback = callback
}

func (c *Check) SetExitCallback(callback func ()) {
    c.exitCallback = callback
}

func (c* Check) PingUrl() {
    // Current status, true for alive, false for dead
    var (
        testError string
        lastDeadCall time.Time
        lastStateChange = time.Now()
        status = true
        newStatus = true
        i = time.Duration(0)
        )
    if httpClient == nil {
        httpClient = &http.Client{Transport: createHttpTransport()}
    }
    for {
        req, _ := http.NewRequest(httpMethod, c.BackendUrl, nil)
        req.Header.Add("User-Agent", userAgent)
        resp, err := httpClient.Do(req)
        if err != nil {
            // TCP error
            newStatus = false
            testError = fmt.Sprintf("TCP error on %s: %#v",
                c.BackendUrl, err.Error())
        } else {
            // No TCP error, checking HTTP code
            if resp.StatusCode > 500 && resp.StatusCode < 600 &&
                resp.StatusCode != 503 {
                    newStatus = false
                    testError = fmt.Sprintf("HTTP error on %s: %#v",
                        c.BackendUrl, resp.StatusCode)
                } else {
                    newStatus = true
                }
        }
        // Check if the status changed before updating Redis
        if newStatus != status {
            lastStateChange = time.Now()
            if newStatus == true {
                log.Printf("%s is back online\n", c.BackendUrl)
                if c.aliveCallback != nil {
                    c.aliveCallback()
                }
                lastDeadCall = time.Time{}
            } else {
                log.Println(testError)
                if c.deadCallback != nil {
                    c.deadCallback()
                }
                lastDeadCall = time.Now()
            }
        } else if newStatus == false {
            // Backend is still dead. Mark it as dead every 30 seconds to keep
            // it dead despite the Redis TTL
            if lastDeadCall.IsZero() == false &&
                time.Since(lastDeadCall) >=
                (time.Duration(30) * time.Second) {
                    if c.deadCallback != nil {
                        c.deadCallback()
                    }
                    lastDeadCall = time.Now()
                }
        }
        status = newStatus
        time.Sleep(checkInterval)
        i += checkInterval
        // At longer interval, we check if still have the lock on the backend
        if i >= checkBreakInterval {
            if c.checkIfBreakCallback != nil &&
                c.checkIfBreakCallback() == true {
                    log.Printf("Lost the lock for %s\n", c.BackendUrl)
                    break
            }
            // Let's see if the check is in the same state for a while
            if time.Since(lastStateChange) >= checkDuration {
                log.Printf("%s stayed in the same state for a long time\n",
                    c.BackendUrl)
                break
            }
            i = time.Duration(0)
        }
    }
    if c.exitCallback != nil {
        c.exitCallback()
    }
}
<|endoftext|>


<commit_before>package mtree

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"
)

// Result of a Check
type Result struct {
	Failures []Failure // list of any failures in the Check
}

// Failure of a particular keyword for a path
type Failure struct {
	Path     string
	Keyword  string
	Expected string
	Got      string
}

// String returns a "pretty" formatting for a Failure
func (f Failure) String() string {
	return fmt.Sprintf("%q: keyword %q: expected %s; got %s", f.Path, f.Keyword, f.Expected, f.Got)
}

// Check a root directory path against the DirectoryHierarchy, regarding only
// the available keywords from the list and each entry in the hierarchy.
// If keywords is nil, the check all present in the DirectoryHierarchy
func Check(root string, dh *DirectoryHierarchy, keywords []string) (*Result, error) {
	creator := dhCreator{DH: dh}
	curDir, err := os.Getwd()
	if err == nil {
		defer os.Chdir(curDir)
	}

	if err := os.Chdir(root); err != nil {
		return nil, err
	}
	sort.Sort(byPos(creator.DH.Entries))

	var result Result
	for _, e := range creator.DH.Entries {
		switch e.Type {
		case SpecialType:
			if e.Name == "/set" {
				creator.curSet = &e
			} else if e.Name == "/unset" {
				creator.curSet = nil
			}
		case RelativeType, FullType:
			info, err := os.Lstat(filepath.Join(root, e.Path()))
			if err != nil {
				return nil, err
			}

			var kvs KeyVals
			if creator.curSet != nil {
				kvs = MergeSet(creator.curSet.Keywords, e.Keywords)
			} else {
				kvs = NewKeyVals(e.Keywords)
			}

			for _, kv := range kvs {
				if keywords != nil && !inSlice(kv.Keyword(), keywords) {
					continue
				}
				keywordFunc, ok := KeywordFuncs[kv.Keyword()]
				if !ok {
					return nil, fmt.Errorf("Unknown keyword %q for file %q", kv.Keyword(), e.Path())
				}
				curKeyVal, err := keywordFunc(filepath.Join(root, e.Path()), info)
				if err != nil {
					return nil, err
				}
				if string(kv) != curKeyVal {
					failure := Failure{Path: e.Path(), Keyword: kv.Keyword(), Expected: kv.Value(), Got: KeyVal(curKeyVal).Value()}
					result.Failures = append(result.Failures, failure)
				}
			}
		}
	}
	return &result, nil
}
<commit_msg>check: recognize correct path<commit_after>package mtree

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"
)

// Result of a Check
type Result struct {
	Failures []Failure // list of any failures in the Check
}

// Failure of a particular keyword for a path
type Failure struct {
	Path     string
	Keyword  string
	Expected string
	Got      string
}

// String returns a "pretty" formatting for a Failure
func (f Failure) String() string {
	return fmt.Sprintf("%q: keyword %q: expected %s; got %s", f.Path, f.Keyword, f.Expected, f.Got)
}

// Check a root directory path against the DirectoryHierarchy, regarding only
// the available keywords from the list and each entry in the hierarchy.
// If keywords is nil, the check all present in the DirectoryHierarchy
func Check(root string, dh *DirectoryHierarchy, keywords []string) (*Result, error) {
	creator := dhCreator{DH: dh}
	curDir, err := os.Getwd()
	if err == nil {
		defer os.Chdir(curDir)
	}

	if err := os.Chdir(root); err != nil {
		return nil, err
	}
	sort.Sort(byPos(creator.DH.Entries))

	var result Result
	for _, e := range creator.DH.Entries {
		switch e.Type {
		case SpecialType:
			if e.Name == "/set" {
				creator.curSet = &e
			} else if e.Name == "/unset" {
				creator.curSet = nil
			}
		case RelativeType, FullType:
			info, err := os.Lstat(e.Path())
			if err != nil {
				return nil, err
			}

			var kvs KeyVals
			if creator.curSet != nil {
				kvs = MergeSet(creator.curSet.Keywords, e.Keywords)
			} else {
				kvs = NewKeyVals(e.Keywords)
			}

			for _, kv := range kvs {
				if keywords != nil && !inSlice(kv.Keyword(), keywords) {
					continue
				}
				keywordFunc, ok := KeywordFuncs[kv.Keyword()]
				if !ok {
					return nil, fmt.Errorf("Unknown keyword %q for file %q", kv.Keyword(), e.Path())
				}
				curKeyVal, err := keywordFunc(filepath.Join(root, e.Path()), info)
				if err != nil {
					return nil, err
				}
				if string(kv) != curKeyVal {
					failure := Failure{Path: e.Path(), Keyword: kv.Keyword(), Expected: kv.Value(), Got: KeyVal(curKeyVal).Value()}
					result.Failures = append(result.Failures, failure)
				}
			}
		}
	}
	return &result, nil
}
<|endoftext|>


<commit_before>// +build !lambdabinary

package sparta

import (
	"fmt"

	"github.com/Sirupsen/logrus"
)

// Explore supports interactive command line invocation of the previously
// provisioned Sparta service
func Explore(lambdaAWSInfos []*LambdaAWSInfo, port int, logger *logrus.Logger) error {
	if 0 == port {
		port = 9999
	}
	urlHost := fmt.Sprintf("http://localhost:%d", port)
	logger.Info("The following URLs are available for testing.")

	msgText := ""

	// Get unique paths
	lambdaPaths := make(map[string]*LambdaAWSInfo, 0)
	for _, eachLambdaInfo := range lambdaAWSInfos {
		lambdaPaths[eachLambdaInfo.lambdaFnName] = eachLambdaInfo
	}

	for _, eachLambdaInfo := range lambdaPaths {
		functionPath := fmt.Sprintf("%s/%s", urlHost, eachLambdaInfo.lambdaFnName)
		logger.WithFields(logrus.Fields{
			"Path": functionPath,
		}).Info(eachLambdaInfo.lambdaFnName)

		if msgText == "" {
			msgText = fmt.Sprintf("\tcurl -vs -X POST -H \"Content-Type: application/json\" --data @testEvent.json %s", functionPath)
		}
	}
	logger.Info("Functions can be invoked via application/json over POST")
	logger.Info(msgText)
	logger.Info("Where @testEvent.json is a local file with top level `context` and `event` keys")
	// Start up the localhost server and publish the info
	return Execute(lambdaAWSInfos, port, 0, logger)
}
<commit_msg>Update `explore` CLI docs<commit_after>// +build !lambdabinary

package sparta

import (
	"fmt"

	"github.com/Sirupsen/logrus"
)

// Explore supports interactive command line invocation of the previously
// provisioned Sparta service
func Explore(lambdaAWSInfos []*LambdaAWSInfo, port int, logger *logrus.Logger) error {
	if 0 == port {
		port = 9999
	}
	urlHost := fmt.Sprintf("http://localhost:%d", port)
	logger.Info("The following URLs are available for testing.")

	msgText := ""

	// Get unique paths
	lambdaPaths := make(map[string]*LambdaAWSInfo, 0)
	for _, eachLambdaInfo := range lambdaAWSInfos {
		lambdaPaths[eachLambdaInfo.lambdaFnName] = eachLambdaInfo
	}

	for _, eachLambdaInfo := range lambdaPaths {
		functionURL := fmt.Sprintf("%s/%s", urlHost, eachLambdaInfo.lambdaFnName)
		logger.WithFields(logrus.Fields{
			"URL": functionURL,
		}).Info(eachLambdaInfo.lambdaFnName)

		if msgText == "" {
			msgText = fmt.Sprintf("\tcurl -vs -X POST -H \"Content-Type: application/json\" --data @testEvent.json %s", functionURL)
		}
	}
	logger.Info("Functions can be invoked via application/json over POST")
	logger.Info(msgText)
	logger.Info("Where @testEvent.json is a local file with top level `context` and `event` properties:")
	logger.Info("\t{context: {}, event: {}}")
	// Start up the localhost server and publish the info
	return Execute(lambdaAWSInfos, port, 0, logger)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/hyperkit/go"
	"github.com/rneugeba/iso9660wrap"
)

// Process the run arguments and execute run
func runHyperKit(args []string) {
	hyperkitCmd := flag.NewFlagSet("hyperkit", flag.ExitOnError)
	hyperkitCmd.Usage = func() {
		fmt.Printf("USAGE: %s run hyperkit [options] prefix\n\n", os.Args[0])
		fmt.Printf("'prefix' specifies the path to the VM image.\n")
		fmt.Printf("\n")
		fmt.Printf("Options:\n")
		hyperkitCmd.PrintDefaults()
	}
	hyperkitPath := hyperkitCmd.String("hyperkit", "", "Path to hyperkit binary (if not in default location)")
	cpus := hyperkitCmd.Int("cpus", 1, "Number of CPUs")
	mem := hyperkitCmd.Int("mem", 1024, "Amount of memory in MB")
	diskSz := hyperkitCmd.Int("disk-size", 0, "Size of Disk in MB")
	disk := hyperkitCmd.String("disk", "", "Path to disk image to used")
	data := hyperkitCmd.String("data", "", "Metadata to pass to VM (either a path to a file or a string)")
	ipStr := hyperkitCmd.String("ip", "", "IP address for the VM")

	hyperkitCmd.Parse(args)
	remArgs := hyperkitCmd.Args()
	if len(remArgs) == 0 {
		fmt.Println("Please specify the prefix to the image to boot\n")
		hyperkitCmd.Usage()
		os.Exit(1)
	}
	prefix := remArgs[0]

	isoPath := ""
	if *data != "" {
		var d []byte
		if _, err := os.Stat(*data); os.IsNotExist(err) {
			d = []byte(*data)
		} else {
			d, err = ioutil.ReadFile(*data)
			if err != nil {
				log.Fatalf("Cannot read user data: %v", err)
			}
		}
		isoPath = prefix + "-data.iso"
		outfh, err := os.OpenFile(isoPath, os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			log.Fatalf("Cannot create user data ISO: %v", err)
		}
		err = iso9660wrap.WriteBuffer(outfh, d, "config")
		if err != nil {
			log.Fatalf("Cannot write user data ISO: %v", err)
		}
		outfh.Close()
	}

	uuidStr := ""
	if *ipStr != "" {
		// If an IP address was requested construct a "special" UUID
		// for the VM.
		if ip := net.ParseIP(*ipStr); len(ip) > 0 {
			uuid := make([]byte, 16)
			uuid[12] = ip.To4()[0]
			uuid[13] = ip.To4()[1]
			uuid[14] = ip.To4()[2]
			uuid[15] = ip.To4()[3]
			uuidStr = fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:])
		}
	}

	// Run
	cmdline, err := ioutil.ReadFile(prefix + "-cmdline")
	if err != nil {
		log.Fatalf("Cannot open cmdline file: %v", err)
	}

	if *diskSz != 0 && *disk == "" {
		*disk = prefix + "-disk.img"
	}

	h, err := hyperkit.New(*hyperkitPath, "", "auto", *disk)
	if err != nil {
		log.Fatalln("Error creating hyperkit: ", err)
	}

	h.Kernel = prefix + "-bzImage"
	h.Initrd = prefix + "-initrd.img"
	h.ISOImage = isoPath
	h.CPUs = *cpus
	h.Memory = *mem
	h.DiskSize = *diskSz
	h.UUID = uuidStr

	err = h.Run(string(cmdline))
	if err != nil {
		log.Fatalf("Cannot run hyperkit: %v", err)
	}
}
<commit_msg>cli: Adjust run_hyperkit to changed API<commit_after>package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/hyperkit/go"
	"github.com/rneugeba/iso9660wrap"
)

// Process the run arguments and execute run
func runHyperKit(args []string) {
	hyperkitCmd := flag.NewFlagSet("hyperkit", flag.ExitOnError)
	hyperkitCmd.Usage = func() {
		fmt.Printf("USAGE: %s run hyperkit [options] prefix\n\n", os.Args[0])
		fmt.Printf("'prefix' specifies the path to the VM image.\n")
		fmt.Printf("\n")
		fmt.Printf("Options:\n")
		hyperkitCmd.PrintDefaults()
	}
	hyperkitPath := hyperkitCmd.String("hyperkit", "", "Path to hyperkit binary (if not in default location)")
	cpus := hyperkitCmd.Int("cpus", 1, "Number of CPUs")
	mem := hyperkitCmd.Int("mem", 1024, "Amount of memory in MB")
	diskSz := hyperkitCmd.Int("disk-size", 0, "Size of Disk in MB")
	disk := hyperkitCmd.String("disk", "", "Path to disk image to used")
	data := hyperkitCmd.String("data", "", "Metadata to pass to VM (either a path to a file or a string)")
	ipStr := hyperkitCmd.String("ip", "", "IP address for the VM")

	hyperkitCmd.Parse(args)
	remArgs := hyperkitCmd.Args()
	if len(remArgs) == 0 {
		fmt.Println("Please specify the prefix to the image to boot\n")
		hyperkitCmd.Usage()
		os.Exit(1)
	}
	prefix := remArgs[0]

	isoPath := ""
	if *data != "" {
		var d []byte
		if _, err := os.Stat(*data); os.IsNotExist(err) {
			d = []byte(*data)
		} else {
			d, err = ioutil.ReadFile(*data)
			if err != nil {
				log.Fatalf("Cannot read user data: %v", err)
			}
		}
		isoPath = prefix + "-data.iso"
		outfh, err := os.OpenFile(isoPath, os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			log.Fatalf("Cannot create user data ISO: %v", err)
		}
		err = iso9660wrap.WriteBuffer(outfh, d, "config")
		if err != nil {
			log.Fatalf("Cannot write user data ISO: %v", err)
		}
		outfh.Close()
	}

	uuidStr := ""
	if *ipStr != "" {
		// If an IP address was requested construct a "special" UUID
		// for the VM.
		if ip := net.ParseIP(*ipStr); len(ip) > 0 {
			uuid := make([]byte, 16)
			uuid[12] = ip.To4()[0]
			uuid[13] = ip.To4()[1]
			uuid[14] = ip.To4()[2]
			uuid[15] = ip.To4()[3]
			uuidStr = fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:])
		}
	}

	// Run
	cmdline, err := ioutil.ReadFile(prefix + "-cmdline")
	if err != nil {
		log.Fatalf("Cannot open cmdline file: %v", err)
	}

	if *diskSz != 0 && *disk == "" {
		*disk = prefix + "-disk.img"
	}

	h, err := hyperkit.New(*hyperkitPath, "auto", "")
	if err != nil {
		log.Fatalln("Error creating hyperkit: ", err)
	}

	h.Kernel = prefix + "-bzImage"
	h.Initrd = prefix + "-initrd.img"
	h.UUID = uuidStr
	h.DiskImage = *disk
	h.ISOImage = isoPath
	h.CPUs = *cpus
	h.Memory = *mem
	h.DiskSize = *diskSz

	err = h.Run(string(cmdline))
	if err != nil {
		log.Fatalf("Cannot run hyperkit: %v", err)
	}
}
<|endoftext|>


<commit_before>package blobstore

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"errors"
	"io"
)

var (
	ErrInsufficientKeySource = errors.New("Not enough data to create a proper encryption key")
)

func createEncryptor(keySource, ivSource []byte, output io.Writer) (writer io.Writer, key string, err error) {

	// Need at least 32 bytes of the key source
	if len(keySource) < 32 {
		err = ErrInsufficientKeySource
		return
	}

	// Create the iv
	var iv [16]byte
	for i, b := range ivSource {
		iv[i] = b
		if i >= 15 {
			break
		}
	}

	keyRaw := keySource[:32]
	key = cipherAES256Hex + hex.EncodeToString(keyRaw)

	// Generate the encrypted content
	blobCipher, err := aes.NewCipher(keyRaw)
	if err != nil {
		return
	}

	// Generate the writer
	writer = &cipher.StreamWriter{
		S: cipher.NewCFBEncrypter(
			blobCipher,
			iv[:]),
		W: output}

	return
}
<commit_msg>Add decryptor generation code<commit_after>package blobstore

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"errors"
	"io"
)

var (
	ErrInsufficientKeySource = errors.New("Not enough data to create a proper encryption key")
	ErrInvalidKey            = errors.New("Invalid key")
	ErrUnknownKeyType        = errors.New("Unknown key type")
)

func createEncryptor(keySource, ivSource []byte, output io.Writer) (writer io.Writer, key string, err error) {

	// Need at least 32 bytes of the key source
	if len(keySource) < 32 {
		err = ErrInsufficientKeySource
		return
	}

	// Create the iv
	var iv [16]byte
	for i, b := range ivSource {
		iv[i] = b
		if i >= 15 {
			break
		}
	}

	keyRaw := keySource[:32]
	key = cipherAES256Hex + hex.EncodeToString(keyRaw)

	// Generate the encrypted content
	blobCipher, err := aes.NewCipher(keyRaw)
	if err != nil {
		return
	}

	// Generate the writer
	writer = &cipher.StreamWriter{
		S: cipher.NewCFBEncrypter(
			blobCipher,
			iv[:]),
		W: output}

	return
}

func createDecryptor(key string, ivSource []byte, input io.Reader) (reader io.Reader, err error) {
	keyRaw, err := hex.DecodeString(key)
	if err != nil || len(keyRaw) < 1 {
		return nil, ErrInvalidKey
	}

	switch keyRaw[0] {
	case cipherAES256:
		return createDecryptorAES256(keyRaw[1:], ivSource, input)
	}

	return nil, ErrUnknownKeyType
}

func createDecryptorAES256(key []byte, ivSource []byte, input io.Reader) (reader io.Reader, err error) {

	if len(key) != 32 {
		return nil, ErrInvalidKey
	}

	// Normalize the iv
	var iv [16]byte
	for i, b := range ivSource {
		iv[i] = b
		if i >= 15 {
			break
		}
	}

	// Create new base cipher
	blobCipher, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	// Generate the reader in CFB mode
	return &cipher.StreamReader{
			S: cipher.NewCFBDecrypter(
				blobCipher,
				iv[:]),
			R: input},
		nil
}
<|endoftext|>


<commit_before>package shell

import (
	"fmt"
	"io"

	"github.com/chrislusf/seaweedfs/weed/filer"
	"github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
	"github.com/chrislusf/seaweedfs/weed/util"
)

func init() {
	Commands = append(Commands, &commandFsDu{})
}

type commandFsDu struct {
}

func (c *commandFsDu) Name() string {
	return "fs.du"
}

func (c *commandFsDu) Help() string {
	return `show disk usage

	fs.du /dir
	fs.du /dir/file_name
	fs.du /dir/file_prefix
`
}

func (c *commandFsDu) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {

	path, err := commandEnv.parseUrl(findInputDirectory(args))
	if err != nil {
		return err
	}

	if commandEnv.isDirectory(path) {
		path = path + "/"
	}

	var blockCount, byteCount uint64
	dir, name := util.FullPath(path).DirAndName()
	blockCount, byteCount, err = duTraverseDirectory(writer, commandEnv, dir, name)

	if name == "" && err == nil {
		fmt.Fprintf(writer, "block:%4d\tbyte:%10d\t%s\n", blockCount, byteCount, dir)
	}

	return

}

func duTraverseDirectory(writer io.Writer, filerClient filer_pb.FilerClient, dir, name string) (blockCount, byteCount uint64, err error) {

	err = filer_pb.ReadDirAllEntries(filerClient, util.FullPath(dir), name, func(entry *filer_pb.Entry, isLast bool) error {

		var fileBlockCount, fileByteCount uint64

		if entry.IsDirectory {
			subDir := fmt.Sprintf("%s/%s", dir, entry.Name)
			if dir == "/" {
				subDir = "/" + entry.Name
			}
			numBlock, numByte, err := duTraverseDirectory(writer, filerClient, subDir, "")
			if err == nil {
				blockCount += numBlock
				byteCount += numByte
			}
		} else {
			fileBlockCount = uint64(len(entry.Chunks))
			fileByteCount = filer.FileSize(entry)
			blockCount += fileBlockCount
			byteCount += fileByteCount
		}

		if name != "" && !entry.IsDirectory {
			fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s/%s\n", fileBlockCount, fileByteCount, dir, entry.Name)
		}
		return nil
	})
	return
}
<commit_msg>adjust used size reporting<commit_after>package shell

import (
	"fmt"
	"io"

	"github.com/chrislusf/seaweedfs/weed/filer"
	"github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
	"github.com/chrislusf/seaweedfs/weed/util"
)

func init() {
	Commands = append(Commands, &commandFsDu{})
}

type commandFsDu struct {
}

func (c *commandFsDu) Name() string {
	return "fs.du"
}

func (c *commandFsDu) Help() string {
	return `show disk usage

	fs.du /dir
	fs.du /dir/file_name
	fs.du /dir/file_prefix
`
}

func (c *commandFsDu) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {

	path, err := commandEnv.parseUrl(findInputDirectory(args))
	if err != nil {
		return err
	}

	if commandEnv.isDirectory(path) {
		path = path + "/"
	}

	var blockCount, byteCount uint64
	dir, name := util.FullPath(path).DirAndName()
	blockCount, byteCount, err = duTraverseDirectory(writer, commandEnv, dir, name)

	if name == "" && err == nil {
		fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s\n", blockCount, byteCount, dir)
	}

	return

}

func duTraverseDirectory(writer io.Writer, filerClient filer_pb.FilerClient, dir, name string) (blockCount, byteCount uint64, err error) {

	err = filer_pb.ReadDirAllEntries(filerClient, util.FullPath(dir), name, func(entry *filer_pb.Entry, isLast bool) error {

		var fileBlockCount, fileByteCount uint64

		if entry.IsDirectory {
			subDir := fmt.Sprintf("%s/%s", dir, entry.Name)
			if dir == "/" {
				subDir = "/" + entry.Name
			}
			numBlock, numByte, err := duTraverseDirectory(writer, filerClient, subDir, "")
			if err == nil {
				blockCount += numBlock
				byteCount += numByte
			}
		} else {
			fileBlockCount = uint64(len(entry.Chunks))
			fileByteCount = filer.FileSize(entry)
			blockCount += fileBlockCount
			byteCount += fileByteCount
		}

		if name != "" && !entry.IsDirectory {
			fmt.Fprintf(writer, "block:%4d\tlogical size:%10d\t%s/%s\n", fileBlockCount, fileByteCount, dir, entry.Name)
		}
		return nil
	})
	return
}
<|endoftext|>


<commit_before>package http

import (
	"bytes"
	"io"
	"log"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/sparrowdb/db"
	"github.com/sparrowdb/model"
	"github.com/sparrowdb/monitor"
	"github.com/sparrowdb/spql"
)

// ServeHandler holds main http methods
type ServeHandler struct {
	dbManager     *db.DBManager
	queryExecutor *spql.QueryExecutor
}

func (sh *ServeHandler) writeResponse(request *RequestData, result *spql.QueryResult) {
	request.responseWriter.Write(result.Value())
}

func (sh *ServeHandler) writeError(request *RequestData, query string, errs ...error) {
	result := &spql.QueryResult{}
	for _, v := range errs {
		result.AddErrorStr(v.Error())
	}
	result.AddValue(strings.Replace(query, "\n", "", -1))
	request.responseWriter.Write(result.Value())
}

func (sh *ServeHandler) serveQuery(request *RequestData) {
	body := request.request.Body

	buf := new(bytes.Buffer)
	buf.ReadFrom(body)
	qStr := buf.String()

	p := spql.NewParser(qStr)
	q, err := p.ParseQuery()
	if err != nil {
		sh.writeError(request, qStr, err)
		return
	}

	results := <-sh.queryExecutor.ExecuteQuery(q)

	if results == nil {
		log.Fatalf("ERROR: Nil query result")
		return
	}

	monitor.IncHTTPQueries()
	request.responseWriter.Header().Set("Content-Type", "application/json")
	sh.writeResponse(request, results)
}

func (sh *ServeHandler) get(request *RequestData) {
	if len(request.params) != 2 {
		request.responseWriter.WriteHeader(404)
		return
	}

	dbname := request.params[0]
	key := request.params[1]

	result := <-sh.dbManager.GetData(dbname, key)

	if result == nil {
		request.responseWriter.WriteHeader(404)
		request.responseWriter.Write([]byte("ERROOOOOOOOOOOOOOOOOOOOOOOOO"))
		return
	}

	request.responseWriter.Header().Set("Content-Type", "image/"+result.Ext)
	request.responseWriter.Header().Set("Content-Length", strconv.Itoa(int(result.Size)))
	request.responseWriter.Write(result.Buf)
}

func (sh *ServeHandler) upload(request *RequestData) {
	file, fhandler, err := request.request.FormFile("uploadfile")
	if err != nil {
		log.Println(err)
		return
	}
	defer file.Close()

	buf := new(bytes.Buffer)
	io.Copy(buf, file)

	dbname := request.request.FormValue("dbname")
	sto, ok := sh.dbManager.GetDatabase(dbname)

	if ok {
		sto.InsertData(&model.DataDefinition{
			Key: request.request.FormValue("key"),

			// get file extension and remove dot before ext name
			Ext: filepath.Ext(fhandler.Filename)[1:],

			Size: uint32(len(buf.Bytes())),
			Buf:  buf.Bytes(),
		})

		monitor.IncHTTPUploads()
	}
}

// NewServeHandler returns new ServeHandler
func NewServeHandler(dbm *db.DBManager, queryExecutor *spql.QueryExecutor) *ServeHandler {
	return &ServeHandler{
		dbManager:     dbm,
		queryExecutor: queryExecutor,
	}
}
<commit_msg>http request error message<commit_after>package http

import (
	"bytes"
	"errors"
	"io"
	"log"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/sparrowdb/db"
	"github.com/sparrowdb/model"
	"github.com/sparrowdb/monitor"
	"github.com/sparrowdb/spql"
)

// ServeHandler holds main http methods
type ServeHandler struct {
	dbManager     *db.DBManager
	queryExecutor *spql.QueryExecutor
}

var (
	errDatabaseNotFound = errors.New("Could not find resquested key")
	errWrongRequest     = errors.New("Wrong HTTP request")
	errEmptyQueryResult = errors.New("Empty query result")
)

func (sh *ServeHandler) writeResponse(request *RequestData, result *spql.QueryResult) {
	request.responseWriter.Write(result.Value())
}

func (sh *ServeHandler) writeError(request *RequestData, query string, errs ...error) {
	result := &spql.QueryResult{}
	for _, v := range errs {
		result.AddErrorStr(v.Error())
	}

	result.AddValue(strings.Replace(query, "\n", "", -1))
	request.responseWriter.WriteHeader(404)
	request.responseWriter.Write(result.Value())
}

func (sh *ServeHandler) serveQuery(request *RequestData) {
	body := request.request.Body

	buf := new(bytes.Buffer)
	buf.ReadFrom(body)
	qStr := buf.String()

	p := spql.NewParser(qStr)
	q, err := p.ParseQuery()
	if err != nil {
		sh.writeError(request, qStr, err)
		return
	}

	results := <-sh.queryExecutor.ExecuteQuery(q)

	if results == nil {
		sh.writeError(request, qStr, errEmptyQueryResult)
		return
	}

	monitor.IncHTTPQueries()
	request.responseWriter.Header().Set("Content-Type", "application/json")
	sh.writeResponse(request, results)
}

func (sh *ServeHandler) get(request *RequestData) {
	if len(request.params) != 2 {
		sh.writeError(request, "{}", errWrongRequest)
		return
	}

	dbname := request.params[0]
	key := request.params[1]

	result := <-sh.dbManager.GetData(dbname, key)

	if result == nil {
		sh.writeError(request, "{}", errDatabaseNotFound)
		return
	}

	request.responseWriter.Header().Set("Content-Type", "image/"+result.Ext)
	request.responseWriter.Header().Set("Content-Length", strconv.Itoa(int(result.Size)))
	request.responseWriter.Write(result.Buf)
}

func (sh *ServeHandler) upload(request *RequestData) {
	file, fhandler, err := request.request.FormFile("uploadfile")
	if err != nil {
		log.Println(err)
		return
	}
	defer file.Close()

	buf := new(bytes.Buffer)
	io.Copy(buf, file)

	dbname := request.request.FormValue("dbname")
	sto, ok := sh.dbManager.GetDatabase(dbname)

	if ok {
		sto.InsertData(&model.DataDefinition{
			Key: request.request.FormValue("key"),

			// get file extension and remove dot before ext name
			Ext: filepath.Ext(fhandler.Filename)[1:],

			Size: uint32(len(buf.Bytes())),
			Buf:  buf.Bytes(),
		})

		monitor.IncHTTPUploads()
	}
}

// NewServeHandler returns new ServeHandler
func NewServeHandler(dbm *db.DBManager, queryExecutor *spql.QueryExecutor) *ServeHandler {
	return &ServeHandler{
		dbManager:     dbm,
		queryExecutor: queryExecutor,
	}
}
<|endoftext|>