コード例 #1
0
ファイル: help_test.go プロジェクト: matthieugrieger/mumbledj
func (suite *HelpCommandTestSuite) SetupSuite() {
	DJ = bot.NewMumbleDJ()

	viper.Set("commands.help.aliases", []string{"help", "h"})
	viper.Set("commands.help.description", "help")
	viper.Set("commands.help.is_admin", false)
}
コード例 #2
0
func (suite *CacheSizeCommandTestSuite) SetupSuite() {
	DJ = bot.NewMumbleDJ()

	viper.Set("commands.cachesize.aliases", []string{"cachesize", "cs"})
	viper.Set("commands.cachesize.description", "cachesize")
	viper.Set("commands.cachesize.is_admin", true)
}
コード例 #3
0
ファイル: server.go プロジェクト: heidthecamp/hugo
func server(cmd *cobra.Command, args []string) {
	InitializeConfig()

	if cmd.Flags().Lookup("disableLiveReload").Changed {
		viper.Set("DisableLiveReload", disableLiveReload)
	}

	if serverWatch {
		viper.Set("Watch", true)
	}

	if viper.GetBool("watch") {
		serverWatch = true
	}

	l, err := net.Listen("tcp", net.JoinHostPort(serverInterface, strconv.Itoa(serverPort)))
	if err == nil {
		l.Close()
	} else {
		jww.ERROR.Println("port", serverPort, "already in use, attempting to use an available port")
		sp, err := helpers.FindAvailablePort()
		if err != nil {
			jww.ERROR.Println("Unable to find alternative port to use")
			jww.ERROR.Fatalln(err)
		}
		serverPort = sp.Port
	}

	viper.Set("port", serverPort)

	BaseURL, err := fixURL(BaseURL)
	if err != nil {
		jww.ERROR.Fatal(err)
	}
	viper.Set("BaseURL", BaseURL)

	if err := memStats(); err != nil {
		jww.ERROR.Println("memstats error:", err)
	}

	build(serverWatch)

	// Watch runs its own server as part of the routine
	if serverWatch {
		watched := getDirList()
		workingDir := helpers.AbsPathify(viper.GetString("WorkingDir"))
		for i, dir := range watched {
			watched[i], _ = helpers.GetRelativePath(dir, workingDir)
		}
		unique := strings.Join(helpers.RemoveSubpaths(watched), ",")

		jww.FEEDBACK.Printf("Watching for changes in %s/{%s}\n", workingDir, unique)
		err := NewWatcher(serverPort)
		if err != nil {
			fmt.Println(err)
		}
	}

	serve(serverPort)
}
コード例 #4
0
ファイル: root.go プロジェクト: lursu/skelly
// initConfig reads in config file and ENV variables if set.
func initConfig(cmd *cobra.Command) {
	viper.SetConfigName(".skelly") // name of config file (without extension)
	viper.AddConfigPath("$HOME")   // adding home directory as first search path
	viper.SetConfigType("json")
	viper.AutomaticEnv() // read in environment variables that match

	fmt.Println("got here")
	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	// Make sure that go src var is set
	gopath = viper.GetString("gopath")
	if len(gopath) <= 0 {
		gopath = joinPath(os.Getenv("GOPATH"), "src")
		viper.Set("gopath", gopath)
	}

	if cmd.Flags().Lookup("project-root").Changed {
		viper.Set("project-root", basePath)
	}
	if cmd.Flags().Lookup("author").Changed {
		fmt.Println("adding author")
		viper.Set("author", author)
	}
	if cmd.Flags().Lookup("email").Changed {
		viper.Set("email", email)
	}
	fmt.Println(email)
	if cmd.Flags().Lookup("license").Changed {
		viper.Set("license", license)
	}
}
コード例 #5
0
func TestPageCount(t *testing.T) {
	testCommonResetState()
	hugofs.InitMemFs()

	viper.Set("uglyURLs", false)
	viper.Set("paginate", 10)
	s := &Site{
		Source:   &source.InMemorySource{ByteSource: urlFakeSource},
		Language: helpers.NewDefaultLanguage(),
	}

	if err := buildAndRenderSite(s, "indexes/blue.html", indexTemplate); err != nil {
		t.Fatalf("Failed to build site: %s", err)
	}
	_, err := hugofs.Destination().Open("public/blue")
	if err != nil {
		t.Errorf("No indexed rendered.")
	}

	for _, s := range []string{
		"public/sd1/foo/index.html",
		"public/sd2/index.html",
		"public/sd3/index.html",
		"public/sd4.html",
	} {
		if _, err := hugofs.Destination().Open(filepath.FromSlash(s)); err != nil {
			t.Errorf("No alias rendered: %s", s)
		}
	}
}
コード例 #6
0
ファイル: main.go プロジェクト: romana/core
// setRomanaRootURL sanitizes rootURL and rootPort and also
// sets baseURL which is needed to connect to other romana
// services.
func setRomanaRootURL() {
	// Variables used for configuration and flags.
	var baseURL string
	var rootURL string
	var rootPort string

	// Add port details to rootURL else try localhost
	// if nothing is given on command line or config.
	rootURL = config.GetString("RootURL")
	rootPort = config.GetString("RootPort")
	if rootPort == "" {
		re, _ := regexp.Compile(`:\d+/?`)
		port := re.FindString(rootURL)
		port = strings.TrimPrefix(port, ":")
		port = strings.TrimSuffix(port, "/")
		if port != "" {
			rootPort = port
		} else {
			rootPort = "9600"
		}
	}
	config.Set("RootPort", rootPort)
	if rootURL != "" {
		baseURL = strings.TrimSuffix(rootURL, "/")
		baseURL = strings.TrimSuffix(baseURL, ":9600")
		baseURL = strings.TrimSuffix(baseURL, ":"+rootPort)
	} else {
		baseURL = "http://localhost"
	}
	config.Set("BaseURL", baseURL)
	rootURL = baseURL + ":" + rootPort + "/"
	config.Set("RootURL", rootURL)
}
コード例 #7
0
ファイル: url_test.go プロジェクト: CODECOMMUNITY/hugo
func TestRelURL(t *testing.T) {
	defer viper.Reset()
	//defer viper.Set("canonifyURLs", viper.GetBool("canonifyURLs"))
	tests := []struct {
		input    string
		baseURL  string
		canonify bool
		expected string
	}{
		{"/test/foo", "http://base/", false, "/test/foo"},
		{"test.css", "http://base/sub", false, "/sub/test.css"},
		{"test.css", "http://base/sub", true, "/test.css"},
		{"/test/", "http://base/", false, "/test/"},
		{"/test/", "http://base/sub/", false, "/sub/test/"},
		{"/test/", "http://base/sub/", true, "/test/"},
		{"", "http://base/ace/", false, "/ace/"},
		{"", "http://base/ace", false, "/ace"},
		{"http://abs", "http://base/", false, "http://abs"},
		{"//schemaless", "http://base/", false, "//schemaless"},
	}

	for i, test := range tests {
		viper.Reset()
		viper.Set("BaseURL", test.baseURL)
		viper.Set("canonifyURLs", test.canonify)

		output := RelURL(test.input)
		if output != test.expected {
			t.Errorf("[%d][%t] Expected %#v, got %#v\n", i, test.canonify, test.expected, output)
		}
	}
}
コード例 #8
0
ファイル: site_test.go プロジェクト: nitoyon/hugo
// Issue #1797
func TestReadPagesFromSourceWithEmptySource(t *testing.T) {
	viper.Reset()
	defer viper.Reset()

	viper.Set("DefaultExtension", "html")
	viper.Set("verbose", true)
	viper.Set("baseurl", "http://auth/bub")

	sources := []source.ByteSource{}

	s := &Site{
		Source:  &source.InMemorySource{ByteSource: sources},
		targets: targetList{page: &target.PagePub{UglyURLs: true}},
	}

	var err error
	d := time.Second * 2
	ticker := time.NewTicker(d)
	select {
	case err = <-s.ReadPagesFromSource():
		break
	case <-ticker.C:
		err = fmt.Errorf("ReadPagesFromSource() never returns in %s", d.String())
	}
	ticker.Stop()
	if err != nil {
		t.Fatalf("Unable to read source: %s", err)
	}
}
コード例 #9
0
func (suite *ToggleShuffleCommandTestSuite) SetupSuite() {
	DJ = bot.NewMumbleDJ()

	viper.Set("commands.toggleshuffle.aliases", []string{"toggleshuffle", "ts"})
	viper.Set("commands.toggleshuffle.description", "toggleshuffle")
	viper.Set("commands.toggleshuffle.is_admin", true)
}
コード例 #10
0
ファイル: setup.go プロジェクト: uetchy/alfred-qiita-workflow
func cmdSetup(c *cli.Context) {
	token := c.Args().First()

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := qiita.NewClient(tc)
	user, err := client.AuthenticatedUser.Show()
	if err != nil {
		fmt.Println("Auth failed")
		os.Exit(1)
	}

	loadConfig()
	viper.Set("accessToken", token)
	viper.Set("id", user.Id)

	err = saveConfig()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println("Token saved")
}
コード例 #11
0
ファイル: robotstxt_test.go プロジェクト: tarsisazevedo/hugo
func TestRobotsTXTOutput(t *testing.T) {
	testCommonResetState()

	hugofs.InitMemFs()

	viper.Set("baseurl", "http://auth/bub/")
	viper.Set("enableRobotsTXT", true)

	s := &Site{
		Source:   &source.InMemorySource{ByteSource: weightedSources},
		Language: helpers.NewDefaultLanguage(),
	}

	if err := buildAndRenderSite(s, "robots.txt", robotTxtTemplate); err != nil {
		t.Fatalf("Failed to build site: %s", err)
	}

	robotsFile, err := hugofs.Destination().Open("public/robots.txt")

	if err != nil {
		t.Fatalf("Unable to locate: robots.txt")
	}

	robots := helpers.ReaderToBytes(robotsFile)
	if !bytes.HasPrefix(robots, []byte("User-agent: Googlebot")) {
		t.Errorf("Robots file should start with 'User-agentL Googlebot'. %s", robots)
	}
}
コード例 #12
0
ファイル: grasshopper.go プロジェクト: vpavlin/grasshopper
// InitializeConfig initializes a config file with sensible default configuration flags.
func InitializeConfig() {
	viper.SetConfigName("grasshopper")          // name of config file (without extension)
	viper.AddConfigPath("/etc/grasshopper.d/")  // path to look for the config file
	viper.AddConfigPath("$HOME/.grasshopper.d") // call multiple times to add many search paths
	viper.AddConfigPath(".")                    // optionally look for config in the working directory

	// read config from storage
	err := viper.ReadInConfig() // FIXME
	if err != nil {
		jww.INFO.Println("Unable to locate Config file. I will fall back to my defaults...")
	}

	// default settings
	viper.SetDefault("Verbose", false)
	viper.SetDefault("DryRun", false)
	viper.SetDefault("DoLog", true)

	// bind config to command flags
	if grasshopperCmdV.PersistentFlags().Lookup("verbose").Changed {
		viper.Set("Verbose", Verbose)
	}
	if grasshopperCmdV.PersistentFlags().Lookup("log").Changed {
		viper.Set("DoLog", DoLog)
	}
}
コード例 #13
0
ファイル: main.go プロジェクト: TheThingsNetwork/ttn
func main() {
	viper.Set("version", version)
	viper.Set("gitBranch", gitBranch)
	viper.Set("gitCommit", gitCommit)
	viper.Set("buildDate", buildDate)
	cmd.Execute()
}
コード例 #14
0
ファイル: main.go プロジェクト: SeleneSoftware/Hermes
func msgBuffer() {
	params := &sqs.ReceiveMessageInput{
		QueueUrl: aws.String(viper.GetString("URL") + ID),
		AttributeNames: []*string{
			aws.String("All"),
		},
		MaxNumberOfMessages: aws.Int64(10),
		MessageAttributeNames: []*string{
			aws.String("Dest." + ID),
		},
		VisibilityTimeout: aws.Int64(1),
	}

	resp, err := svc.ReceiveMessage(params)
	errHandle(err)
	for _, element := range resp.Messages {
		var m Message
		data, _ := strconv.Unquote(awsutil.Prettify(element.Body))
		b := []byte(data)
		err := json.Unmarshal(b, &m)
		errHandle(err)
		//This is where we will send the message to the queue for the service
		viper.Set("Dest", m.Dest)
		viper.Set("Sender", m.Sender)
		go execute(m)
		//If all goes well, the message has been forwarded to the responsible queue
		deleteMsg(element)
	}
}
コード例 #15
0
ファイル: init-ca.go プロジェクト: blacklabeldata/kappa
// InitializeCertAuthConfig sets up the command line options for creating a CA
func InitializeCertAuthConfig(logger log.Logger) error {

	viper.SetDefault("Bits", "4096")
	viper.SetDefault("Years", "10")
	viper.SetDefault("Organization", "kappa-ca")
	viper.SetDefault("Country", "USA")

	if initCmd.PersistentFlags().Lookup("bits").Changed {
		logger.Info("", "Bits", KeyBits)
		viper.Set("Bits", KeyBits)
	}
	if initCmd.PersistentFlags().Lookup("years").Changed {
		logger.Info("", "Years", Years)
		viper.Set("Years", Years)
	}
	if initCmd.PersistentFlags().Lookup("organization").Changed {
		logger.Info("", "Organization", Organization)
		viper.Set("Organization", Organization)
	}
	if initCmd.PersistentFlags().Lookup("country").Changed {
		logger.Info("", "Country", Country)
		viper.Set("Country", Country)
	}
	if initCmd.PersistentFlags().Lookup("hosts").Changed {
		logger.Info("", "Hosts", Hosts)
		viper.Set("Hosts", Hosts)
	}

	return nil
}
コード例 #16
0
ファイル: root.go プロジェクト: goern/gogetgithubstats
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".gogetgithubstats") // name of config file (without extension)
	viper.AddConfigPath("$HOME")             // adding home directory as first search path
	viper.AutomaticEnv()                     // read in environment variables that match

	// This is the defaults
	viper.SetDefault("Verbose", true)

	// If a config file is found, read it in.
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigParseError); ok {
			jww.ERROR.Println(err)
		} else {
			jww.ERROR.Println("Unable to locate Config file.", err)
		}
	}

	if rootCmdV.PersistentFlags().Lookup("verbose").Changed {
		viper.Set("Verbose", Verbose)
	}

	if rootCmdV.PersistentFlags().Lookup("access-token").Changed {
		viper.Set("access-token", accessToken)
	}

	if viper.GetBool("verbose") {
		jww.SetStdoutThreshold(jww.LevelDebug)
	}
}
コード例 #17
0
ファイル: handler_test.go プロジェクト: tarsisazevedo/hugo
func TestDefaultHandler(t *testing.T) {
	testCommonResetState()

	hugofs.InitMemFs()
	sources := []source.ByteSource{
		{Name: filepath.FromSlash("sect/doc1.html"), Content: []byte("---\nmarkup: markdown\n---\n# title\nsome *content*")},
		{Name: filepath.FromSlash("sect/doc2.html"), Content: []byte("<!doctype html><html><body>more content</body></html>")},
		{Name: filepath.FromSlash("sect/doc3.md"), Content: []byte("# doc3\n*some* content")},
		{Name: filepath.FromSlash("sect/doc4.md"), Content: []byte("---\ntitle: doc4\n---\n# doc4\n*some content*")},
		{Name: filepath.FromSlash("sect/doc3/img1.png"), Content: []byte("‰PNG  ��� IHDR����������:~›U��� IDATWcø��ZMo��IEND®B`‚")},
		{Name: filepath.FromSlash("sect/img2.gif"), Content: []byte("GIF89a��€��ÿÿÿ���,�������D�;")},
		{Name: filepath.FromSlash("sect/img2.spf"), Content: []byte("****FAKE-FILETYPE****")},
		{Name: filepath.FromSlash("doc7.html"), Content: []byte("<html><body>doc7 content</body></html>")},
		{Name: filepath.FromSlash("sect/doc8.html"), Content: []byte("---\nmarkup: md\n---\n# title\nsome *content*")},
	}

	viper.Set("DefaultExtension", "html")
	viper.Set("verbose", true)

	s := &Site{
		Source:   &source.InMemorySource{ByteSource: sources},
		targets:  targetList{page: &target.PagePub{UglyURLs: true, PublishDir: "public"}},
		Language: helpers.NewLanguage("en"),
	}

	if err := buildAndRenderSite(s,
		"_default/single.html", "{{.Content}}",
		"head", "<head><script src=\"script.js\"></script></head>",
		"head_abs", "<head><script src=\"/script.js\"></script></head>"); err != nil {
		t.Fatalf("Failed to render site: %s", err)
	}

	tests := []struct {
		doc      string
		expected string
	}{
		{filepath.FromSlash("public/sect/doc1.html"), "\n\n<h1 id=\"title\">title</h1>\n\n<p>some <em>content</em></p>\n"},
		{filepath.FromSlash("public/sect/doc2.html"), "<!doctype html><html><body>more content</body></html>"},
		{filepath.FromSlash("public/sect/doc3.html"), "\n\n<h1 id=\"doc3\">doc3</h1>\n\n<p><em>some</em> content</p>\n"},
		{filepath.FromSlash("public/sect/doc3/img1.png"), string([]byte("‰PNG  ��� IHDR����������:~›U��� IDATWcø��ZMo��IEND®B`‚"))},
		{filepath.FromSlash("public/sect/img2.gif"), string([]byte("GIF89a��€��ÿÿÿ���,�������D�;"))},
		{filepath.FromSlash("public/sect/img2.spf"), string([]byte("****FAKE-FILETYPE****"))},
		{filepath.FromSlash("public/doc7.html"), "<html><body>doc7 content</body></html>"},
		{filepath.FromSlash("public/sect/doc8.html"), "\n\n<h1 id=\"title\">title</h1>\n\n<p>some <em>content</em></p>\n"},
	}

	for _, test := range tests {
		file, err := hugofs.Destination().Open(test.doc)
		if err != nil {
			t.Fatalf("Did not find %s in target.", test.doc)
		}

		content := helpers.ReaderToString(file)

		if content != test.expected {
			t.Errorf("%s content expected:\n%q\ngot:\n%q", test.doc, test.expected, content)
		}
	}

}
コード例 #18
0
ファイル: menu_test.go プロジェクト: krig/hugo
func doTestMenuWithUnicodeURLs(t *testing.T, canonifyURLs, uglyURLs bool) {
	viper.Reset()
	defer viper.Reset()

	viper.Set("CanonifyURLs", canonifyURLs)
	viper.Set("UglyURLs", uglyURLs)

	s := setupMenuTests(t, MENU_PAGE_SOURCES)

	unicodeRussian := findTestMenuEntryByID(s, "unicode", "unicode-russian")

	expectedBase := "/%D0%BD%D0%BE%D0%B2%D0%BE%D1%81%D1%82%D0%B8-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0"

	if !canonifyURLs {
		expectedBase = "/Zoo" + expectedBase
	}

	var expected string
	if uglyURLs {
		expected = expectedBase + ".html"
	} else {
		expected = expectedBase + "/"
	}

	assert.Equal(t, expected, unicodeRussian.URL, "uglyURLs[%t]", uglyURLs)
}
コード例 #19
0
ファイル: server.go プロジェクト: vinchu/hugo
func server(cmd *cobra.Command, args []string) {
	InitializeConfig()

	if BaseUrl == "" {
		BaseUrl = "http://localhost"
	}

	if !strings.HasPrefix(BaseUrl, "http://") {
		BaseUrl = "http://" + BaseUrl
	}

	if serverAppend {
		viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/")+":"+strconv.Itoa(serverPort))
	} else {
		viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/"))
	}

	build(serverWatch)

	// Watch runs its own server as part of the routine
	if serverWatch {
		jww.FEEDBACK.Println("Watching for changes in", helpers.AbsPathify(viper.GetString("ContentDir")))
		err := NewWatcher(serverPort)
		if err != nil {
			fmt.Println(err)
		}
	}

	serve(serverPort)
}
コード例 #20
0
ファイル: grnl.go プロジェクト: jzorn/grnl
// initConfig reads in config file and ENV variables if set.
func initConfig() {

	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".grnl") // name of config file (without extension)
	viper.AddConfigPath("$HOME") // adding home directory as first search path
	viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("Error using config file %q\n%q", viper.ConfigFileUsed(), err)
	}

	if db != "" {
		viper.Set("db", db)
	}

	if editor != "" {
		viper.Set("editor", editor)
	}

	if dateFormat != "" {
		viper.Set("dateFormat", dateFormat)
	}
}
コード例 #21
0
ファイル: rbac_test.go プロジェクト: yoshiharay/fabric
func setup() {
	// Conf
	viper.SetConfigName("rbac") // name of config file (without extension)
	viper.AddConfigPath(".")    // path to look for the config file in
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file [%s] \n", err))
	}

	// Logging
	var formatter = logging.MustStringFormatter(
		`%{color}[%{module}] %{shortfunc} [%{shortfile}] -> %{level:.4s} %{id:03x}%{color:reset} %{message}`,
	)
	logging.SetFormatter(formatter)

	logging.SetLevel(logging.DEBUG, "peer")
	logging.SetLevel(logging.DEBUG, "chaincode")
	logging.SetLevel(logging.DEBUG, "cryptoain")

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	hl := filepath.Join(os.TempDir(), "hyperledger")

	viper.Set("peer.fileSystemPath", filepath.Join(hl, "production"))
	viper.Set("server.rootpath", filepath.Join(hl, "ca"))

	removeFolders()
}
コード例 #22
0
ファイル: run_test.go プロジェクト: 5Sigma/Conduit
func TestRun(t *testing.T) {
	mb, err := mailbox.Create("test.testrun")
	if err != nil {
		t.Fatal(err)
	}
	key := mailbox.AccessKey{MailboxId: mb.Id}
	err = key.Create()
	if err != nil {
		t.Fatal(err)
	}
	msg, err := mb.PutMessage(`$("test");`)
	if err != nil {
		t.Fatal(err)
	}
	viper.Set("host", ":5112")
	viper.Set("mailbox", mb.Id)
	viper.Set("access_key", key.Secret)
	viper.Set("access_key_name", key.Name)
	viper.Set("show_requests", true)
	go serverCmd.Run(serverCmd, []string{})
	runCmd.ParseFlags([]string{"-1", "-d"})
	runCmd.Run(runCmd, []string{})
	dep, _ := mailbox.FindDeployment(msg.Deployment)
	resp, _ := dep.GetResponses()
	if len(resp) != 1 {
		t.Fatal("No response")
	}
}
コード例 #23
0
ファイル: root.go プロジェクト: romana/core
// preConfig sanitizes URLs and sets up config with URLs.
func preConfig(cmd *cli.Command, args []string) {
	var baseURL string

	// Add port details to rootURL else try localhost
	// if nothing is given on command line or config.
	if rootURL == "" {
		rootURL = config.GetString("RootURL")
	}
	if rootPort == "" {
		rootPort = config.GetString("RootPort")
	}
	if rootPort == "" {
		re, _ := regexp.Compile(`:\d+/?`)
		port := re.FindString(rootURL)
		port = strings.TrimPrefix(port, ":")
		port = strings.TrimSuffix(port, "/")
		if port != "" {
			rootPort = port
		} else {
			rootPort = "9600"
		}
	}
	config.Set("RootPort", rootPort)
	if rootURL != "" {
		baseURL = strings.TrimSuffix(rootURL, "/")
		baseURL = strings.TrimSuffix(baseURL, ":9600")
		baseURL = strings.TrimSuffix(baseURL, ":"+rootPort)
	} else {
		baseURL = "http://localhost"
	}
	config.Set("BaseURL", baseURL)
	rootURL = baseURL + ":" + rootPort + "/"
	config.Set("RootURL", rootURL)

	// Give command line options higher priority then
	// the corresponding config options.
	if format == "" {
		format = config.GetString("Format")
	}
	// if format is still not found just default to tabular format.
	if format == "" {
		format = "table"
	}
	config.Set("Format", format)

	if platform == "" {
		platform = config.GetString("Platform")
	}
	if platform == "" {
		platform = "openstack"
	}
	config.Set("Platform", platform)

	fmt.Println(config.GetString("username"))
	err := credential.Initialize()
	if err != nil {
		log.Printf("Error: %s", err)
		os.Exit(1)
	}
}
コード例 #24
0
ファイル: new.go プロジェクト: nitoyon/hugo
// NewContent adds new content to a Hugo site.
func NewContent(cmd *cobra.Command, args []string) error {
	if err := InitializeConfig(); err != nil {
		return err
	}

	if flagChanged(cmd.Flags(), "format") {
		viper.Set("MetaDataFormat", configFormat)
	}

	if flagChanged(cmd.Flags(), "editor") {
		viper.Set("NewContentEditor", contentEditor)
	}

	if len(args) < 1 {
		return newUserError("path needs to be provided")
	}

	createpath := args[0]

	var kind string

	createpath, kind = newContentPathSection(createpath)

	if contentType != "" {
		kind = contentType
	}

	return create.NewContent(kind, createpath)

}
コード例 #25
0
ファイル: shortcode_test.go プロジェクト: xinzhi/hugo
func TestHighlight(t *testing.T) {
	viper.Reset()
	defer viper.Reset()

	if !helpers.HasPygments() {
		t.Skip("Skip test as Pygments is not installed")
	}
	viper.Set("PygmentsStyle", "bw")
	viper.Set("PygmentsUseClasses", false)

	templ := tpl.New()

	code := `
{{< highlight java >}}
void do();
{{< /highlight >}}`

	p, _ := pageFromString(simplePage, "simple.md")
	output, err := HandleShortcodes(code, p, templ)

	if err != nil {
		t.Fatal("Handle shortcode error", err)
	}
	matched, err := regexp.MatchString("(?s)^\n<div class=\"highlight\" style=\"background: #ffffff\"><pre style=\"line-height: 125%\">.*?void</span> do().*?</pre></div>\n$", output)

	if err != nil {
		t.Fatal("Regexp error", err)
	}

	if !matched {
		t.Error("Hightlight mismatch, got\n", output)
	}
}
コード例 #26
0
ファイル: notify_test.go プロジェクト: tmrts/minikube
func TestShouldCheckURL(t *testing.T) {
	tempDir := tests.MakeTempDir()
	defer os.RemoveAll(tempDir)

	lastUpdateCheckFilePath := filepath.Join(tempDir, "last_update_check")

	// test that if users disable update notification in config, the URL version does not get checked
	viper.Set(config.WantUpdateNotification, false)
	if shouldCheckURLVersion(lastUpdateCheckFilePath) {
		t.Fatalf("Error: shouldCheckURLVersion returned true even though config had WantUpdateNotification: false")
	}

	// test that if users want update notification, the URL version does get checked
	viper.Set(config.WantUpdateNotification, true)
	if shouldCheckURLVersion(lastUpdateCheckFilePath) == false {
		t.Fatalf("Error: shouldCheckURLVersion returned false even though there was no last_update_check file")
	}

	// test that update notifications get triggered if it has been longer than 24 hours
	viper.Set(config.ReminderWaitPeriodInHours, 24)
	writeTimeToFile(lastUpdateCheckFilePath, time.Time{}) //time.Time{} returns time -> January 1, year 1, 00:00:00.000000000 UTC.
	if shouldCheckURLVersion(lastUpdateCheckFilePath) == false {
		t.Fatalf("Error: shouldCheckURLVersion returned false even though longer than 24 hours since last update")
	}

	// test that update notifications do not get triggered if it has been less than 24 hours
	writeTimeToFile(lastUpdateCheckFilePath, time.Now().UTC())
	if shouldCheckURLVersion(lastUpdateCheckFilePath) == true {
		t.Fatalf("Error: shouldCheckURLVersion returned false even though longer than 24 hours since last update")
	}

}
コード例 #27
0
ファイル: pygments_test.go プロジェクト: nurhavid/hugo
func TestParsePygmentsArgs(t *testing.T) {
	for i, this := range []struct {
		in                 string
		pygmentsStyle      string
		pygmentsUseClasses bool
		expect1            interface{}
	}{
		{"", "foo", true, "style=foo,noclasses=false,encoding=utf8"},
		{"style=boo,noclasses=true", "foo", true, "encoding=utf8,noclasses=true,style=boo"},
		{"Style=boo, noClasses=true", "foo", true, "encoding=utf8,noclasses=true,style=boo"},
		{"noclasses=true", "foo", true, "encoding=utf8,noclasses=true,style=foo"},
		{"style=boo", "foo", true, "encoding=utf8,noclasses=false,style=boo"},
		{"boo=invalid", "foo", false, false},
		{"style", "foo", false, false},
	} {
		viper.Set("PygmentsStyle", this.pygmentsStyle)
		viper.Set("PygmentsUseClasses", this.pygmentsUseClasses)

		result1, err := parsePygmentsOpts(this.in)
		if b, ok := this.expect1.(bool); ok && !b {
			if err == nil {
				t.Errorf("[%d] parsePygmentArgs didn't return an expected error", i)
			}
		} else {
			if err != nil {
				t.Errorf("[%d] parsePygmentArgs failed: %s", i, err)
				continue
			}
			if result1 != this.expect1 {
				t.Errorf("[%d] parsePygmentArgs got %v but expected %v", i, result1, this.expect1)
			}

		}
	}
}
コード例 #28
0
ファイル: site_test.go プロジェクト: digitalcraftsman/hugo
func TestSkipRender(t *testing.T) {
	testCommonResetState()

	hugofs.InitMemFs()
	sources := []source.ByteSource{
		{Name: filepath.FromSlash("sect/doc1.html"), Content: []byte("---\nmarkup: markdown\n---\n# title\nsome *content*")},
		{Name: filepath.FromSlash("sect/doc2.html"), Content: []byte("<!doctype html><html><body>more content</body></html>")},
		{Name: filepath.FromSlash("sect/doc3.md"), Content: []byte("# doc3\n*some* content")},
		{Name: filepath.FromSlash("sect/doc4.md"), Content: []byte("---\ntitle: doc4\n---\n# doc4\n*some content*")},
		{Name: filepath.FromSlash("sect/doc5.html"), Content: []byte("<!doctype html><html>{{ template \"head\" }}<body>body5</body></html>")},
		{Name: filepath.FromSlash("sect/doc6.html"), Content: []byte("<!doctype html><html>{{ template \"head_abs\" }}<body>body5</body></html>")},
		{Name: filepath.FromSlash("doc7.html"), Content: []byte("<html><body>doc7 content</body></html>")},
		{Name: filepath.FromSlash("sect/doc8.html"), Content: []byte("---\nmarkup: md\n---\n# title\nsome *content*")},
	}

	viper.Set("defaultExtension", "html")
	viper.Set("verbose", true)
	viper.Set("canonifyURLs", true)
	viper.Set("baseURL", "http://auth/bub")
	s := &Site{
		Source:   &source.InMemorySource{ByteSource: sources},
		targets:  targetList{page: &target.PagePub{UglyURLs: true}},
		Language: helpers.NewDefaultLanguage(),
	}

	if err := buildAndRenderSite(s,
		"_default/single.html", "{{.Content}}",
		"head", "<head><script src=\"script.js\"></script></head>",
		"head_abs", "<head><script src=\"/script.js\"></script></head>"); err != nil {
		t.Fatalf("Failed to build site: %s", err)
	}

	tests := []struct {
		doc      string
		expected string
	}{
		{filepath.FromSlash("sect/doc1.html"), "\n\n<h1 id=\"title\">title</h1>\n\n<p>some <em>content</em></p>\n"},
		{filepath.FromSlash("sect/doc2.html"), "<!doctype html><html><body>more content</body></html>"},
		{filepath.FromSlash("sect/doc3.html"), "\n\n<h1 id=\"doc3\">doc3</h1>\n\n<p><em>some</em> content</p>\n"},
		{filepath.FromSlash("sect/doc4.html"), "\n\n<h1 id=\"doc4\">doc4</h1>\n\n<p><em>some content</em></p>\n"},
		{filepath.FromSlash("sect/doc5.html"), "<!doctype html><html><head><script src=\"script.js\"></script></head><body>body5</body></html>"},
		{filepath.FromSlash("sect/doc6.html"), "<!doctype html><html><head><script src=\"http://auth/bub/script.js\"></script></head><body>body5</body></html>"},
		{filepath.FromSlash("doc7.html"), "<html><body>doc7 content</body></html>"},
		{filepath.FromSlash("sect/doc8.html"), "\n\n<h1 id=\"title\">title</h1>\n\n<p>some <em>content</em></p>\n"},
	}

	for _, test := range tests {
		file, err := hugofs.Destination().Open(test.doc)
		if err != nil {
			t.Fatalf("Did not find %s in target.", test.doc)
		}

		content := helpers.ReaderToString(file)

		if content != test.expected {
			t.Errorf("%s content expected:\n%q\ngot:\n%q", test.doc, test.expected, content)
		}
	}
}
コード例 #29
0
func TestExecuteInvokeTransaction(t *testing.T) {
	testDBWrapper.CleanDB(t)
	var opts []grpc.ServerOption

	//TLS is on by default. This is the ONLY test that does NOT use TLS
	viper.Set("peer.tls.enabled", false)

	//turn OFF keepalive. All other tests use keepalive
	viper.Set("peer.chaincode.keepalive", "0")

	if viper.GetBool("peer.tls.enabled") {
		creds, err := credentials.NewServerTLSFromFile(viper.GetString("peer.tls.cert.file"), viper.GetString("peer.tls.key.file"))
		if err != nil {
			grpclog.Fatalf("Failed to generate credentials %v", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	grpcServer := grpc.NewServer(opts...)
	viper.Set("peer.fileSystemPath", "/var/hyperledger/test/tmpdb")

	//use a different address than what we usually use for "peer"
	//we override the peerAddress set in chaincode_support.go
	peerAddress := "0.0.0.0:21212"

	lis, err := net.Listen("tcp", peerAddress)
	if err != nil {
		t.Fail()
		t.Logf("Error starting peer listener %s", err)
		return
	}

	getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
		return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil
	}

	ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond
	pb.RegisterChaincodeSupportServer(grpcServer, NewChaincodeSupport(DefaultChain, getPeerEndpoint, false, ccStartupTimeout, nil))

	go grpcServer.Serve(lis)

	var ctxt = context.Background()

	url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
	chaincodeID := &pb.ChaincodeID{Path: url}

	args := []string{"a", "b", "10"}
	err = invokeExample02Transaction(ctxt, chaincodeID, args, true)
	if err != nil {
		t.Fail()
		t.Logf("Error invoking transaction: %s", err)
	} else {
		fmt.Printf("Invoke test passed\n")
		t.Logf("Invoke test passed")
	}

	GetChain(DefaultChain).Stop(ctxt, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeID: chaincodeID}})

	closeListenerAndSleep(lis)
}
コード例 #30
0
ファイル: content_test.go プロジェクト: CODECOMMUNITY/hugo
func initViper() {
	viper.Reset()
	viper.Set("MetaDataFormat", "toml")
	viper.Set("archetypeDir", filepath.Join(os.TempDir(), "archetypes"))
	viper.Set("contentDir", filepath.Join(os.TempDir(), "content"))
	viper.Set("themesDir", filepath.Join(os.TempDir(), "themes"))
	viper.Set("theme", "sample")
}