Golang GetBool示例

说明

golang getbool示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: github.com/spf13/viper

示例#1
文件: load_test.go 项目: slok/daton

func (s *ConfigTestSuite) TestLoadDefaults(c *C) {
	LoadSettingsFromFile()

	c.Assert(viper.GetInt("Port"), Equals, Port)
	c.Assert(viper.GetBool("EnableAutomerge"), Equals, EnableAutomerge)
	c.Assert(viper.GetBool("Debug"), Equals, Debug)
}

示例#2
文件: site.go 项目: johnsto/hugo

// Render a page for each section
func (s *Site) RenderSectionLists() error {
	for section, data := range s.Sections {
		n := s.NewNode()
		if viper.GetBool("PluralizeListTitles") {
			n.Title = strings.Title(inflect.Pluralize(section))
		} else {
			n.Title = strings.Title(section)
		}
		s.setUrls(n, section)
		n.Date = data[0].Page.Date
		n.Data["Pages"] = data.Pages()
		layouts := []string{"section/" + section + ".html", "_default/section.html", "_default/list.html", "indexes/" + section + ".html", "_default/indexes.html"}

		err := s.render(n, section, s.appendThemeTemplates(layouts)...)
		if err != nil {
			return err
		}

		if !viper.GetBool("DisableRSS") {
			// XML Feed
			rssLayouts := []string{"section/" + section + ".rss.xml", "_default/rss.xml", "rss.xml", "_internal/_default/rss.xml"}
			s.setUrls(n, section+".xml")
			err = s.render(n, section+".xml", s.appendThemeTemplates(rssLayouts)...)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

示例#3
文件: hugo.go 项目: tubo028/hugo

func copyStatic() error {
	publishDir := helpers.AbsPathify(viper.GetString("publishDir")) + helpers.FilePathSeparator

	// If root, remove the second '/'
	if publishDir == "//" {
		publishDir = helpers.FilePathSeparator
	}

	// Includes both theme/static & /static
	staticSourceFs := getStaticSourceFs()

	if staticSourceFs == nil {
		jww.WARN.Println("No static directories found to sync")
		return nil
	}

	syncer := fsync.NewSyncer()
	syncer.NoTimes = viper.GetBool("notimes")
	syncer.SrcFs = staticSourceFs
	syncer.DestFs = hugofs.Destination()
	// Now that we are using a unionFs for the static directories
	// We can effectively clean the publishDir on initial sync
	syncer.Delete = viper.GetBool("cleanDestinationDir")
	if syncer.Delete {
		jww.INFO.Println("removing all files from destination that don't exist in static dirs")
	}
	jww.INFO.Println("syncing static files to", publishDir)

	// because we are using a baseFs (to get the union right).
	// set sync src to root
	return syncer.Sync(publishDir, helpers.FilePathSeparator)
}

示例#4
文件: site.go 项目: dunn/hugo

func (s *Site) initializeSiteInfo() {
	params := viper.GetStringMap("Params")

	permalinks := make(PermalinkOverrides)
	for k, v := range viper.GetStringMapString("Permalinks") {
		permalinks[k] = PathPattern(v)
	}

	s.Info = SiteInfo{
		BaseUrl:         template.URL(helpers.SanitizeUrlKeepTrailingSlash(viper.GetString("BaseUrl"))),
		Title:           viper.GetString("Title"),
		Author:          viper.GetStringMap("author"),
		LanguageCode:    viper.GetString("languagecode"),
		Copyright:       viper.GetString("copyright"),
		DisqusShortname: viper.GetString("DisqusShortname"),
		BuildDrafts:     viper.GetBool("BuildDrafts"),
		canonifyUrls:    viper.GetBool("CanonifyUrls"),
		Pages:           &s.Pages,
		Recent:          &s.Pages,
		Menus:           &s.Menus,
		Params:          params,
		Permalinks:      permalinks,
		Data:            &s.Data,
	}
}

示例#5
文件: main.go 项目: tenc/obc-peer-pre-public

func createEventHubServer() (net.Listener, *grpc.Server, error) {
	var lis net.Listener
	var grpcServer *grpc.Server
	var err error
	if viper.GetBool("peer.validator.enabled") {
		lis, err = net.Listen("tcp", viper.GetString("peer.validator.events.address"))
		if err != nil {
			return nil, nil, fmt.Errorf("failed to listen: %v", err)
		}

		//TODO - do we need different SSL material for events ?
		var opts []grpc.ServerOption
		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 {
				return nil, nil, fmt.Errorf("Failed to generate credentials %v", err)
			}
			opts = []grpc.ServerOption{grpc.Creds(creds)}
		}

		grpcServer = grpc.NewServer(opts...)
		ehServer := producer.NewOpenchainEventsServer(uint(viper.GetInt("peer.validator.events.buffersize")), viper.GetInt("peer.validator.events.timeout"))
		pb.RegisterOpenchainEventsServer(grpcServer, ehServer)
	}
	return lis, grpcServer, err
}

示例#6
文件: config.go 项目: livitski/sman

//getConfig reads config and returns struct
func getConfig() (c Config) {
	c.SnippetDir = expandPath(viper.GetString("snippet_dir"))
	c.Shell = viper.GetString("shell")
	c.AppendHistory = viper.GetBool("append_history")
	c.ExecConfirm = viper.GetBool("exec_confirm")
	return c
}

示例#7
文件: page.go 项目: vinchu/hugo

func (p *Page) permalink() (*url.URL, error) {
	baseUrl := string(p.Site.BaseUrl)
	dir := strings.TrimSpace(p.Dir)
	pSlug := strings.TrimSpace(p.Slug)
	pUrl := strings.TrimSpace(p.Url)
	var permalink string
	var err error

	if len(pUrl) > 0 {
		return helpers.MakePermalink(baseUrl, pUrl), nil
	}

	if override, ok := p.Site.Permalinks[p.Section]; ok {
		permalink, err = override.Expand(p)

		if err != nil {
			return nil, err
		}
		// fmt.Printf("have a section override for %q in section %s → %s\n", p.Title, p.Section, permalink)
	} else {
		if len(pSlug) > 0 {
			permalink = helpers.UrlPrep(viper.GetBool("UglyUrls"), path.Join(dir, p.Slug+"."+p.Extension))
		} else {
			_, t := path.Split(p.FileName)
			permalink = helpers.UrlPrep(viper.GetBool("UglyUrls"), path.Join(dir, helpers.ReplaceExtension(strings.TrimSpace(t), p.Extension)))
		}
	}

	return helpers.MakePermalink(baseUrl, permalink), nil
}

示例#8
文件: event-shuttle.go 项目: wojtekzw/event-shuttle

func (a *appConfig) getAndValidateConfig(cmd *cobra.Command) error {
	var err error

	a.port = viper.GetString("port")
	a.debug = viper.GetBool("debug")
	a.cpu = viper.GetInt("cpu")
	a.allowDegradedMode = viper.GetBool("allow-degraded-mode")

	// check logLevel values and set initLogLevel
	a.logLevel = viper.GetString("log-level")
	a.initLogLevel, err = log.ParseLevel(a.logLevel)
	if err != nil {
		err = fmt.Errorf("Invalid log level: \"%s\"\n%s", a.logLevel, cmd.Flags().Lookup("log-level").Usage)
		return err
	}

	// check db name
	a.db = viper.GetString("db")
	if a.db == "" {
		err = fmt.Errorf("Db name can't be empty\n%s", cmd.Flags().Lookup("db").Usage)
		return err
	}

	// Kafka brokers
	a.kafkaBrokerList = strings.Split(viper.GetString("kafka-brokers"), ",")
	if len(a.kafkaBrokerList) == 0 {
		err = fmt.Errorf("Broker list is empty or invalid format (%s)\n%s", a.kafkaBrokers, cmd.Flags().Lookup("kafka-brokers").Usage)
		return err
	}

	return nil
}

示例#9
文件: validity_period_test.go 项目: RicHernandez2/fabric

func getSecHelper() (crypto.Peer, error) {
	var secHelper crypto.Peer
	var err error
	if viper.GetBool("security.enabled") {
		enrollID := viper.GetString("security.enrollID")
		enrollSecret := viper.GetString("security.enrollSecret")
		if viper.GetBool("peer.validator.enabled") {
			if err = crypto.RegisterValidator(enrollID, nil, enrollID, enrollSecret); nil != err {
				return nil, err
			}
			secHelper, err = crypto.InitValidator(enrollID, nil)
			if nil != err {
				return nil, err
			}
		} else {
			if err = crypto.RegisterPeer(enrollID, nil, enrollID, enrollSecret); nil != err {
				return nil, err
			}
			secHelper, err = crypto.InitPeer(enrollID, nil)
			if nil != err {
				return nil, err
			}
		}
	}
	return secHelper, err
}

示例#10
文件: page.go 项目: JTrembl1/hugo

func (p *Page) permalink() (*url.URL, error) {
	baseURL := string(p.Site.BaseURL)
	dir := strings.TrimSpace(helpers.MakePath(filepath.ToSlash(strings.ToLower(p.Source.Dir()))))
	pSlug := strings.TrimSpace(helpers.URLize(p.Slug))
	pURL := strings.TrimSpace(helpers.URLize(p.URL))
	var permalink string
	var err error

	if len(pURL) > 0 {
		return helpers.MakePermalink(baseURL, pURL), nil
	}

	if override, ok := p.Site.Permalinks[p.Section()]; ok {
		permalink, err = override.Expand(p)

		if err != nil {
			return nil, err
		}
		// fmt.Printf("have a section override for %q in section %s → %s\n", p.Title, p.Section, permalink)
	} else {
		if len(pSlug) > 0 {
			permalink = helpers.URLPrep(viper.GetBool("UglyURLs"), path.Join(dir, p.Slug+"."+p.Extension()))
		} else {
			_, t := filepath.Split(p.Source.LogicalName())
			permalink = helpers.URLPrep(viper.GetBool("UglyURLs"), path.Join(dir, helpers.ReplaceExtension(strings.TrimSpace(t), p.Extension())))
		}
	}

	return helpers.MakePermalink(baseURL, permalink), nil
}

示例#11
文件: site.go 项目: maruel/hugo

func (s *Site) initializeSiteInfo() {
	params := viper.GetStringMap("Params")

	permalinks := make(PermalinkOverrides)
	for k, v := range viper.GetStringMapString("Permalinks") {
		permalinks[k] = PathPattern(v)
	}

	s.Info = SiteInfo{
		BaseURL:               template.URL(helpers.SanitizeURLKeepTrailingSlash(viper.GetString("BaseURL"))),
		Title:                 viper.GetString("Title"),
		Author:                viper.GetStringMap("author"),
		Social:                viper.GetStringMapString("social"),
		LanguageCode:          viper.GetString("languagecode"),
		Copyright:             viper.GetString("copyright"),
		DisqusShortname:       viper.GetString("DisqusShortname"),
		GoogleAnalytics:       viper.GetString("GoogleAnalytics"),
		RSSLink:               s.permalinkStr(viper.GetString("RSSUri")),
		BuildDrafts:           viper.GetBool("BuildDrafts"),
		canonifyURLs:          viper.GetBool("CanonifyURLs"),
		preserveTaxonomyNames: viper.GetBool("PreserveTaxonomyNames"),
		Pages:      &s.Pages,
		Menus:      &s.Menus,
		Params:     params,
		Permalinks: permalinks,
		Data:       &s.Data,
	}
}

示例#12
文件: site.go 项目: dunn/hugo

func (s *Site) renderAndWritePage(name string, dest string, d interface{}, layouts ...string) error {
	renderBuffer := bp.GetBuffer()
	defer bp.PutBuffer(renderBuffer)

	err := s.render(name, d, renderBuffer, layouts...)

	outBuffer := bp.GetBuffer()
	defer bp.PutBuffer(outBuffer)

	transformLinks := transform.NewEmptyTransforms()

	if viper.GetBool("CanonifyUrls") {
		absURL, err := transform.AbsURL(viper.GetString("BaseUrl"))
		if err != nil {
			return err
		}
		transformLinks = append(transformLinks, absURL...)
	}

	if viper.GetBool("watch") && !viper.GetBool("DisableLiveReload") {
		transformLinks = append(transformLinks, transform.LiveReloadInject)
	}

	transformer := transform.NewChain(transformLinks...)
	transformer.Apply(outBuffer, renderBuffer)

	if err == nil {
		if err = s.WriteDestPage(dest, outBuffer); err != nil {
			return err
		}
	}
	return err
}

示例#13
文件: dockercontroller.go 项目: srderson/fabric

func getDockerHostConfig() *docker.HostConfig {
	if hostConfig != nil {
		return hostConfig
	}
	dockerKey := func(key string) string {
		return "vm.docker.hostConfig." + key
	}
	getInt64 := func(key string) int64 {
		defer func() {
			if err := recover(); err != nil {
				dockerLogger.Warningf("load vm.docker.hostConfig.%s failed, error: %v", key, err)
			}
		}()
		n := viper.GetInt(dockerKey(key))
		return int64(n)
	}

	var logConfig docker.LogConfig
	err := viper.UnmarshalKey(dockerKey("LogConfig"), &logConfig)
	if err != nil {
		dockerLogger.Warningf("load docker HostConfig.LogConfig failed, error: %s", err.Error())
	}
	networkMode := viper.GetString(dockerKey("NetworkMode"))
	if networkMode == "" {
		networkMode = "host"
	}
	dockerLogger.Debugf("docker container hostconfig NetworkMode: %s", networkMode)

	hostConfig = &docker.HostConfig{
		CapAdd:  viper.GetStringSlice(dockerKey("CapAdd")),
		CapDrop: viper.GetStringSlice(dockerKey("CapDrop")),

		DNS:         viper.GetStringSlice(dockerKey("Dns")),
		DNSSearch:   viper.GetStringSlice(dockerKey("DnsSearch")),
		ExtraHosts:  viper.GetStringSlice(dockerKey("ExtraHosts")),
		NetworkMode: networkMode,
		IpcMode:     viper.GetString(dockerKey("IpcMode")),
		PidMode:     viper.GetString(dockerKey("PidMode")),
		UTSMode:     viper.GetString(dockerKey("UTSMode")),
		LogConfig:   logConfig,

		ReadonlyRootfs:   viper.GetBool(dockerKey("ReadonlyRootfs")),
		SecurityOpt:      viper.GetStringSlice(dockerKey("SecurityOpt")),
		CgroupParent:     viper.GetString(dockerKey("CgroupParent")),
		Memory:           getInt64("Memory"),
		MemorySwap:       getInt64("MemorySwap"),
		MemorySwappiness: getInt64("MemorySwappiness"),
		OOMKillDisable:   viper.GetBool(dockerKey("OomKillDisable")),
		CPUShares:        getInt64("CpuShares"),
		CPUSet:           viper.GetString(dockerKey("Cpuset")),
		CPUSetCPUs:       viper.GetString(dockerKey("CpusetCPUs")),
		CPUSetMEMs:       viper.GetString(dockerKey("CpusetMEMs")),
		CPUQuota:         getInt64("CpuQuota"),
		CPUPeriod:        getInt64("CpuPeriod"),
		BlkioWeight:      getInt64("BlkioWeight"),
	}

	return hostConfig
}

示例#14
文件: endorser_test.go 项目: hyperledger/fabric

//initialize peer and start up. If security==enabled, login as vp
func initPeer(chainID string) (net.Listener, error) {
	//start clean
	finitPeer(nil)
	var opts []grpc.ServerOption
	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 {
			return nil, fmt.Errorf("Failed to generate credentials %v", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	grpcServer := grpc.NewServer(opts...)

	viper.Set("peer.fileSystemPath", filepath.Join(os.TempDir(), "hyperledger", "production"))

	peerAddress, err := peer.GetLocalAddress()
	if err != nil {
		return nil, fmt.Errorf("Error obtaining peer address: %s", err)
	}
	lis, err := net.Listen("tcp", peerAddress)
	if err != nil {
		return nil, fmt.Errorf("Error starting peer listener %s", err)
	}

	//initialize ledger
	peer.MockInitialize()

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

	// Install security object for peer
	if viper.GetBool("security.enabled") {
		//TODO:  integrate new crypto / idp
		securityLevel := viper.GetInt("security.level")
		hashAlgorithm := viper.GetString("security.hashAlgorithm")
		primitives.SetSecurityLevel(hashAlgorithm, securityLevel)
	} else {
		// the primitives need to be instantiated no matter what. Otherwise
		// the escc code won't have a hash algorithm available to hash the proposal
		primitives.SetSecurityLevel("SHA2", 256)
	}

	ccStartupTimeout := time.Duration(30000) * time.Millisecond
	pb.RegisterChaincodeSupportServer(grpcServer, chaincode.NewChaincodeSupport(getPeerEndpoint, false, ccStartupTimeout))

	chaincode.RegisterSysCCs()

	if err = peer.MockCreateChain(chainID); err != nil {
		closeListenerAndSleep(lis)
		return nil, err
	}

	chaincode.DeploySysCCs(chainID)

	go grpcServer.Serve(lis)

	return lis, nil
}

示例#15
文件: page.go 项目: JTrembl1/hugo

func (p *Page) ShouldBuild() bool {
	if viper.GetBool("BuildFuture") || p.PublishDate.IsZero() || p.PublishDate.Before(time.Now()) {
		if viper.GetBool("BuildDrafts") || !p.Draft {
			return true
		}
	}
	return false
}

示例#16
文件: doit.go 项目: neurodrone/doit

// GetBool returns a config value as a bool.
func (c *LiveConfig) GetBool(ns, key string) bool {
	if ns == NSRoot {
		return viper.GetBool(key)
	}

	nskey := fmt.Sprintf("%s-%s", ns, key)
	return viper.GetBool(nskey)
}

示例#17
文件: content_renderer.go 项目: tarsisazevedo/hugo

func (renderer *HugoMmarkHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string, caption []byte, subfigure bool, callouts bool) {
	if viper.GetBool("PygmentsCodeFences") && (lang != "" || viper.GetBool("PygmentsCodeFencesGuessSyntax")) {
		str := html.UnescapeString(string(text))
		out.WriteString(Highlight(str, lang, ""))
	} else {
		renderer.Renderer.BlockCode(out, text, lang, caption, subfigure, callouts)
	}
}

示例#18
文件: config.go 项目: jxstanford/stormpath-sdk-go

func loadOAuth2Config() {
	Config.OAuth2Enabled = viper.GetBool("stormpath.web.oauth2.enabled")
	Config.OAuth2URI = viper.GetString("stormpath.web.oauth2.uri")
	Config.OAuth2ClientCredentialsGrantTypeEnabled = viper.GetBool("stormpath.web.oauth2.client_credentials.enabled")
	Config.OAuth2ClientCredentialsGrantTypeAccessTokenTTL = time.Duration(viper.GetInt("stormpath.web.oauth2.client_credentials.accessToken.ttl")) * time.Second
	Config.OAuth2PasswordGrantTypeEnabled = viper.GetBool("stormpath.web.oauth2.password.enabled")
	Config.OAuth2PasswordGrantTypeValidationStrategy = viper.GetString("stormpath.web.oauth2.password.validationStrategy")
}

示例#19
文件: userGet.go 项目: Crosse/msgraph

func setupAPI() *msgraph.GraphAPI {
	api := msgraph.New(viper.GetString("tenantDomain"))
	api.SetDebug(viper.GetBool("debug"))
	api.SetHTTPDebug(viper.GetBool("httpdebug"))
	api.SetClientID(viper.GetString("clientID"))
	api.SetClientSecret(viper.GetString("clientSecret"))

	return api
}

示例#20
文件: config.go 项目: nanopack/portal

func LoadConfigFile() error {
	if ConfigFile == "" {
		return nil
	}
	// Set defaults to whatever might be there already
	viper.SetDefault("api-token", ApiToken)
	viper.SetDefault("api-host", ApiHost)
	viper.SetDefault("api-port", ApiPort)
	viper.SetDefault("api-key", ApiKey)
	viper.SetDefault("api-cert", ApiCert)
	viper.SetDefault("api-key-password", ApiKeyPassword)
	viper.SetDefault("db-connection", DatabaseConnection)
	viper.SetDefault("cluster-connection", ClusterConnection)
	viper.SetDefault("cluster-token", ClusterToken)
	viper.SetDefault("insecure", Insecure)
	viper.SetDefault("just-proxy", JustProxy)
	viper.SetDefault("log-level", LogLevel)
	viper.SetDefault("log-file", LogFile)
	viper.SetDefault("server", Server)
	viper.SetDefault("proxy-http", RouteHttp)
	viper.SetDefault("proxy-tls", RouteTls)
	viper.SetDefault("proxy-ignore-upstream", ProxyIgnore)
	viper.SetDefault("balancer", Balancer)
	viper.SetDefault("work-dir", WorkDir)

	filename := filepath.Base(ConfigFile)
	viper.SetConfigName(filename[:len(filename)-len(filepath.Ext(filename))])
	viper.AddConfigPath(filepath.Dir(ConfigFile))

	err := viper.ReadInConfig()
	if err != nil {
		return fmt.Errorf("Fatal error config file: %s \n", err)
	}

	// Set values. Config file will override commandline
	ApiToken = viper.GetString("api-token")
	ApiHost = viper.GetString("api-host")
	ApiPort = viper.GetString("api-port")
	ApiKey = viper.GetString("api-key")
	ApiCert = viper.GetString("api-cert")
	ApiKeyPassword = viper.GetString("api-key-password")
	DatabaseConnection = viper.GetString("db-connection")
	ClusterConnection = viper.GetString("cluster-connection")
	ClusterToken = viper.GetString("cluster-token")
	Insecure = viper.GetBool("insecure")
	JustProxy = viper.GetBool("just-proxy")
	LogLevel = viper.GetString("log-level")
	LogFile = viper.GetString("log-file")
	Server = viper.GetBool("server")
	RouteHttp = viper.GetString("proxy-http")
	RouteTls = viper.GetString("proxy-tls")
	ProxyIgnore = viper.GetBool("proxy-ignore-upstream")
	Balancer = viper.GetString("balancer")
	WorkDir = viper.GetString("work-dir")

	return nil
}

示例#21
文件: content_renderer.go 项目: tarsisazevedo/hugo

func (renderer *HugoHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string) {
	if viper.GetBool("PygmentsCodeFences") && (lang != "" || viper.GetBool("PygmentsCodeFencesGuessSyntax")) {
		opts := viper.GetString("PygmentsOptions")
		str := html.UnescapeString(string(text))
		out.WriteString(Highlight(str, lang, opts))
	} else {
		renderer.Renderer.BlockCode(out, text, lang)
	}
}

示例#22
文件: site.go 项目: jaden/hugo

func (s *Site) RenderSitemap() error {
	if viper.GetBool("DisableSitemap") {
		return nil
	}

	sitemapDefault := parseSitemap(viper.GetStringMap("Sitemap"))

	optChanged := false

	n := s.NewNode()

	// Prepend homepage to the list of pages
	pages := make(Pages, 0)

	page := &Page{}
	page.Date = s.Info.LastChange
	page.Site = &s.Info
	page.Url = "/"

	pages = append(pages, page)
	pages = append(pages, s.Pages...)

	n.Data["Pages"] = pages

	for _, page := range pages {
		if page.Sitemap.ChangeFreq == "" {
			page.Sitemap.ChangeFreq = sitemapDefault.ChangeFreq
		}

		if page.Sitemap.Priority == -1 {
			page.Sitemap.Priority = sitemapDefault.Priority
		}
	}

	// Force `UglyUrls` option to force `sitemap.xml` file name
	switch s.PageTarget().(type) {
	case *target.Filesystem:
		s.PageTarget().(*target.PagePub).UglyUrls = true
		optChanged = true
	}

	smLayouts := []string{"sitemap.xml", "_default/sitemap.xml", "_internal/_default/sitemap.xml"}
	b, err := s.renderXML("sitemap", n, s.appendThemeTemplates(smLayouts)...)
	if err != nil {
		return err
	}
	if err := s.WriteDestFile("sitemap.xml", b); err != nil {
		return err
	}

	if optChanged {
		s.PageTarget().(*target.PagePub).UglyUrls = viper.GetBool("UglyUrls")
	}

	return nil
}

示例#23
文件: conf.go 项目: RobinUS2/indispenso

func UpdateLegacyBool(from string, to string, defaultValue bool) {
	val := viper.GetBool(from)
	if val == defaultValue {
		return
	}

	if viper.GetBool(to) == defaultValue {
		viper.Set(to, viper.GetBool(from))
	}
}

示例#24
文件: site.go 项目: johnsto/hugo

func (s *Site) RenderHomePage() error {
	n := s.NewNode()
	n.Title = n.Site.Title
	s.setUrls(n, "/")
	n.Data["Pages"] = s.Pages
	layouts := []string{"index.html", "_default/list.html", "_default/single.html"}
	err := s.render(n, "/", s.appendThemeTemplates(layouts)...)
	if err != nil {
		return err
	}

	if !viper.GetBool("DisableRSS") {
		// XML Feed
		n.Url = helpers.Urlize("index.xml")
		n.Title = "Recent Content"
		n.Permalink = s.permalink("index.xml")
		high := 50
		if len(s.Pages) < high {
			high = len(s.Pages)
		}
		n.Data["Pages"] = s.Pages[:high]
		if len(s.Pages) > 0 {
			n.Date = s.Pages[0].Date
		}

		if !viper.GetBool("DisableRSS") {
			rssLayouts := []string{"rss.xml", "_default/rss.xml", "_internal/_default/rss.xml"}
			err := s.render(n, ".xml", s.appendThemeTemplates(rssLayouts)...)
			if err != nil {
				return err
			}
		}
	}

	// Force `UglyUrls` option to force `404.html` file name
	switch s.Target.(type) {
	case *target.Filesystem:
		if !s.Target.(*target.Filesystem).UglyUrls {
			s.Target.(*target.Filesystem).UglyUrls = true
			defer func() { s.Target.(*target.Filesystem).UglyUrls = false }()
		}
	}

	n.Url = helpers.Urlize("404.html")
	n.Title = "404 Page not found"
	n.Permalink = s.permalink("404.html")

	nfLayouts := []string{"404.html"}
	nfErr := s.render(n, "404.html", s.appendThemeTemplates(nfLayouts)...)
	if nfErr != nil {
		return nfErr
	}

	return nil
}

示例#25
文件: queue.go 项目: matthieugrieger/mumbledj

// Skip performs the necessary actions that take place when a track is skipped
// via a command.
func (q *Queue) Skip() {
	// Set AudioStream to nil if it isn't already.
	if DJ.AudioStream != nil {
		DJ.AudioStream = nil
	}

	// Remove all track skips.
	DJ.Skips.ResetTrackSkips()

	q.mutex.Lock()
	// If caching is disabled, delete the track from disk.
	if len(q.Queue) != 0 && !viper.GetBool("cache.enabled") {
		DJ.YouTubeDL.Delete(q.Queue[0])
	}

	// If automatic track shuffling is enabled, assign a random track in the queue to be the next track.
	if viper.GetBool("queue.automatic_shuffle_on") {
		q.mutex.Unlock()
		q.RandomNextTrack(false)
		q.mutex.Lock()
	}

	// Remove all playlist skips if this is the last track of the playlist still in the queue.
	if playlist := q.Queue[0].GetPlaylist(); playlist != nil {
		id := playlist.GetID()
		playlistIsFinished := true

		q.mutex.Unlock()
		q.Traverse(func(i int, t interfaces.Track) {
			if i != 0 && t.GetPlaylist() != nil {
				if t.GetPlaylist().GetID() == id {
					playlistIsFinished = false
				}
			}
		})
		q.mutex.Lock()

		if playlistIsFinished {
			DJ.Skips.ResetPlaylistSkips()
		}
	}

	// Skip the track.
	length := len(q.Queue)
	if length > 1 {
		q.Queue = q.Queue[1:]
	} else {
		q.Queue = make([]interfaces.Track, 0)
	}
	q.mutex.Unlock()

	if err := q.playIfNeeded(); err != nil {
		q.Skip()
	}
}

示例#26
文件: config.go 项目: yoshiharay/fabric

// CacheConfiguration computes and caches commonly-used constants and
// computed constants as package variables. Routines which were previously
// global have been embedded here to preserve the original abstraction.
func CacheConfiguration() (err error) {

	// getLocalAddress returns the address:port the local peer is operating on.  Affected by env:peer.addressAutoDetect
	getLocalAddress := func() (peerAddress string, err error) {
		if viper.GetBool("peer.addressAutoDetect") {
			// Need to get the port from the peer.address setting, and append to the determined host IP
			_, port, err := net.SplitHostPort(viper.GetString("peer.address"))
			if err != nil {
				err = fmt.Errorf("Error auto detecting Peer's address: %s", err)
				return "", err
			}
			peerAddress = net.JoinHostPort(GetLocalIP(), port)
			peerLogger.Infof("Auto detected peer address: %s", peerAddress)
		} else {
			peerAddress = viper.GetString("peer.address")
		}
		return
	}

	// getPeerEndpoint returns the PeerEndpoint for this Peer instance.  Affected by env:peer.addressAutoDetect
	getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
		var peerAddress string
		var peerType pb.PeerEndpoint_Type
		peerAddress, err := getLocalAddress()
		if err != nil {
			return nil, err
		}
		if viper.GetBool("peer.validator.enabled") {
			peerType = pb.PeerEndpoint_VALIDATOR
		} else {
			peerType = pb.PeerEndpoint_NON_VALIDATOR
		}
		return &pb.PeerEndpoint{ID: &pb.PeerID{Name: viper.GetString("peer.id")}, Address: peerAddress, Type: peerType}, nil
	}

	localAddress, localAddressError = getLocalAddress()
	peerEndpoint, peerEndpointError = getPeerEndpoint()

	syncStateSnapshotChannelSize = viper.GetInt("peer.sync.state.snapshot.channelSize")
	syncStateDeltasChannelSize = viper.GetInt("peer.sync.state.deltas.channelSize")
	syncBlocksChannelSize = viper.GetInt("peer.sync.blocks.channelSize")
	validatorEnabled = viper.GetBool("peer.validator.enabled")

	securityEnabled = viper.GetBool("security.enabled")

	configurationCached = true

	if localAddressError != nil {
		return localAddressError
	} else if peerEndpointError != nil {
		return peerEndpointError
	}
	return
}

示例#27
文件: root_test.go 项目: dyweb/Ayi

func TestBindFlag(t *testing.T) {
	assert := assert.New(t)
	RootCmd.SetArgs([]string{""})
	_ = RootCmd.Execute()
	assert.Equal(false, viper.GetBool("Verbose"))
	assert.Equal(false, viper.GetBool("DryRun"))
	RootCmd.SetArgs([]string{"-v", "-n"})
	_ = RootCmd.Execute()
	assert.Equal(true, viper.GetBool("Verbose"))
	assert.Equal(true, viper.GetBool("DryRun"))
}

示例#28
文件: site.go 项目: jempe/hugo

func (s *Site) RenderHomePage() error {
	n := s.newHomeNode()
	layouts := []string{"index.html", "_default/list.html", "_default/single.html"}
	b, err := s.renderPage("homepage", n, s.appendThemeTemplates(layouts)...)
	if err != nil {
		return err
	}
	if err := s.WriteDestPage("/", b); err != nil {
		return err
	}

	if !viper.GetBool("DisableRSS") {
		// XML Feed
		n.Url = helpers.Urlize("index.xml")
		n.Title = "Recent Content"
		n.Permalink = s.permalink("index.xml")
		high := 50
		if len(s.Pages) < high {
			high = len(s.Pages)
		}
		n.Data["Pages"] = s.Pages[:high]
		if len(s.Pages) > 0 {
			n.Date = s.Pages[0].Date
		}

		if !viper.GetBool("DisableRSS") {
			rssLayouts := []string{"rss.xml", "_default/rss.xml", "_internal/_default/rss.xml"}
			b, err := s.renderXML("homepage rss", n, s.appendThemeTemplates(rssLayouts)...)
			if err != nil {
				return err
			}
			if err := s.WriteDestFile("rss.xml", b); err != nil {
				return err
			}
		}
	}

	n.Url = helpers.Urlize("404.html")
	n.Title = "404 Page not found"
	n.Permalink = s.permalink("404.html")

	nfLayouts := []string{"404.html"}
	b, nfErr := s.renderPage("404 page", n, s.appendThemeTemplates(nfLayouts)...)
	if nfErr != nil {
		return nfErr
	}
	if err := s.WriteDestFile("404.html", b); err != nil {
		return err
	}

	return nil
}

示例#29
文件: url.go 项目: tarsisazevedo/hugo

func getLanguagePrefix() string {
	if !viper.GetBool("Multilingual") {
		return ""
	}

	defaultLang := viper.GetString("DefaultContentLanguage")
	defaultInSubDir := viper.GetBool("DefaultContentLanguageInSubdir")

	currentLang := viper.Get("CurrentContentLanguage").(*Language).Lang
	if currentLang == "" || (currentLang == defaultLang && !defaultInSubDir) {
		return ""
	}
	return currentLang
}

示例#30
文件: site.go 项目: johnsto/hugo

func (s *Site) render(d interface{}, out string, layouts ...string) (err error) {

	layout, found := s.findFirstLayout(layouts...)
	if found == false {
		jww.WARN.Printf("Unable to locate layout: %s\n", layouts)
		return
	}

	transformLinks := transform.NewEmptyTransforms()

	if viper.GetBool("CanonifyUrls") {
		absURL, err := transform.AbsURL(viper.GetString("BaseUrl"))
		if err != nil {
			return err
		}
		transformLinks = append(transformLinks, absURL...)
	}

	if viper.GetBool("watch") && !viper.GetBool("DisableLiveReload") {
		transformLinks = append(transformLinks, transform.LiveReloadInject)
	}

	transformer := transform.NewChain(transformLinks...)

	var renderBuffer *bytes.Buffer

	if strings.HasSuffix(out, ".xml") {
		renderBuffer = s.NewXMLBuffer()
	} else {
		renderBuffer = new(bytes.Buffer)
	}

	err = s.renderThing(d, layout, renderBuffer)
	if err != nil {
		// Behavior here should be dependent on if running in server or watch mode.
		jww.ERROR.Println(fmt.Errorf("Rendering error: %v", err))
		if !s.Running() {
			os.Exit(-1)
		}
	}

	var outBuffer = new(bytes.Buffer)
	if strings.HasSuffix(out, ".xml") {
		outBuffer = renderBuffer
	} else {
		transformer.Apply(outBuffer, renderBuffer)
	}

	return s.WritePublic(out, outBuffer)
}

展开阅读全文