我有一个简短的 GO 应用程序,我构建它来修改配置文件并期望它们被覆盖,但它们却在附加,我不确定为什么。在我的 file.Sync() 之前,我已经尝试过 os.Truncate(),但最终得到了一个格式错误的文件。我也曾尝试写入 tmp 文件,但最终出现索引错误,我觉得这不值得尝试。我希望文件能够打开、读入、修改和覆盖现有内容。看起来好像文件没有完成写入?也许缓冲区?我做错了什么?
应用
package main
import (
"strings"
"bufio"
"fmt"
"regexp"
"flag"
"os"
"io"
"bytes"
)
var (
filename string
)
func isCommentOrBlank(line string) bool {
return strings.HasPrefix(line, "#") || "" == strings.TrimSpace(line)
}
func fileExists(filename string) bool {
if _, err := os.Stat(filename); err == nil {
return true
}
return false
}
func limitLength(s string, length int) string {
if len(s) < length {
return s
}
return s[:length]
}
func padWithSpace(str, pad string, length int) string {
for {
str += pad
if len(str) > length {
return str[0:length]
}
}
}
func ingest(filename string) (err error) {
file, err := os.OpenFile(filename, os.O_RDWR, 0644)
defer file.Close()
if err != nil {
return err
}
reader := bufio.NewReader(file) // Start reading from the file with a reader.
for {
var buffer bytes.Buffer
var l []byte
var isPrefix bool
for {
l, isPrefix, err = reader.ReadLine()
buffer.Write(l)
if !isPrefix {
break
}
}
if err == io.EOF || err != nil {
break
}
line := buffer.String()
pattern := regexp.MustCompile(`^#([^=]+)=(.+)$`)
matches := pattern.FindAllStringSubmatch(line, -1) // matches is [][]string
for _, string := range matches {
n := strings.Replace(strings.TrimSpace(string[1]), "#", "", -1)
v := strings.TrimSpace(string[2])
e := strings.ToLower(strings.Replace(n, ".", "/", -1))
// newline creation for if block
nl := "{{if exists \"/" + e + "\" -}}\n"
nl += padWithSpace(n, " ", 80) + "= {{getv \"/" + e + "\" \"" + v + "\"}}\n"
nl += "{{end -}}\n"
file.WriteString(nl)
}
// dont proccess comments
if (isCommentOrBlank(line)) {
if (!strings.Contains(line, "=")) {
file.WriteString(line + "\n")
}
} else {
a := strings.Split(line, "=")
n := strings.TrimSpace(a[0])
v := strings.TrimSpace(a[1])
e := strings.ToLower(strings.Replace(n, ".", "/", -1))
file.WriteString(padWithSpace(n, " ", 80) + "= {{getv \"/" + e + "\" \"" + v + "\"}}\n")
}
}
file.Sync()
if err != io.EOF {
fmt.Printf(" > Failed!: %v\n", err)
}
return
}
func main() {
flag.StringVar(&filename, "f", "filename", "The file location to be parsed")
flag.Parse()
if !fileExists(filename) {
fmt.Println(" > File does not exist\n")
}
ingest(filename)
}
重写配置
# The file contains the properties for Chaos Monkey.
# see documentation at:
# https://github.com/Netflix/SimianArmy/wiki/Configuration
# let chaos run
simianarmy.chaos.enabled = true
# don't allow chaos to kill (ie dryrun mode)
simianarmy.chaos.leashed = true
# set to "false" for Opt-In behavior, "true" for Opt-Out behavior
simianarmy.chaos.ASG.enabled = false
# uncomment this line to use tunable aggression
#simianarmy.client.chaos.class = com.netflix.simianarmy.tunable.TunablyAggressiveChaosMonkey
# default probability for all ASGs
simianarmy.chaos.ASG.probability = 1.0
# increase or decrease the termination limit
simianarmy.chaos.ASG.maxTerminationsPerDay = 1.0
# Strategies
simianarmy.chaos.shutdowninstance.enabled = true
simianarmy.chaos.blockallnetworktraffic.enabled = false
simianarmy.chaos.burncpu.enabled = false
simianarmy.chaos.killprocesses.enabled = false
simianarmy.chaos.nullroute.enabled = false
simianarmy.chaos.failapi.enabled = false
simianarmy.chaos.faildns.enabled = false
simianarmy.chaos.faildynamodb.enabled = false
simianarmy.chaos.fails3.enabled = false
simianarmy.chaos.networkcorruption.enabled = false
simianarmy.chaos.networklatency.enabled = false
simianarmy.chaos.networkloss.enabled = false
# Force-detaching EBS volumes may cause data loss
simianarmy.chaos.detachvolumes.enabled = false
# FillDisk fills the root disk.
# NOTE: This may incur charges for an EBS root volume. See burnmoney option.
simianarmy.chaos.burnio.enabled = false
# BurnIO causes disk activity on the root disk.
# NOTE: This may incur charges for an EBS root volume. See burnmoney option.
simianarmy.chaos.filldisk.enabled = false
# Where we know the chaos strategy will incur charges, we won't run it unless burnmoney is true.
simianarmy.chaos.burnmoney = false
# enable a specific ASG
# simianarmy.chaos.ASG.<asgName>.enabled = true
# simianarmy.chaos.ASG.<asgName>.probability = 1.0
# increase or decrease the termination limit for a specific ASG
# simianarmy.chaos.ASG.<asgName>.maxTerminationsPerDay = 1.0
# Enroll in mandatory terminations. If a group has not had a
# termination within the windowInDays range then it will terminate
# one instance in the group with a 0.5 probability (at some point in
# the next 2 days an instance should be terminated), then
# do nothing again for windowInDays. This forces "enabled" groups
# that have a probability of 0.0 to have terminations periodically.
simianarmy.chaos.mandatoryTermination.enabled = false
simianarmy.chaos.mandatoryTermination.windowInDays = 32
simianarmy.chaos.mandatoryTermination.defaultProbability = 0.5
# Enable notification for Chaos termination for a specific instance group
# simianarmy.chaos.<groupType>.<groupName>.notification.enabled = true
# Set the destination email the termination notification sent to for a specific instance group
# simianarmy.chaos.<groupType>.<groupName>.ownerEmail = foo@bar.com
# Set the source email that sends the termination notification
# simianarmy.chaos.notification.sourceEmail = foo@bar.com
# Enable notification for Chaos termination for all instance groups
#simianarmy.chaos.notification.global.enabled = true
# Set the destination email the termination notification is sent to for all instance groups
#simianarmy.chaos.notification.global.receiverEmail = foo@bar.com
# Set a prefix applied to the subject of all termination notifications
# Probably want to include a trailing space to separate from start of default text
#simianarmy.chaos.notification.subject.prefix = SubjectPrefix
# Set a suffix applied to the subject of all termination notifications
# Probably want to include an escaped space " \ " to separate from end of default text
#simianarmy.chaos.notification.subject.suffix = \ SubjectSuffix
# Set a prefix applied to the body of all termination notifications
# Probably want to include a trailing space to separate from start of default text
#simianarmy.chaos.notification.body.prefix = BodyPrefix
# Set a suffix applied to the body of all termination notifications
# Probably want to include an escaped space " \ " to separate from end of default text
#simianarmy.chaos.notification.body.suffix = \ BodySuffix
# Enable the email subject to be the same as the body, to include terminated instance and group information
#simianarmy.chaos.notification.subject.isBody = true
#set the tag filter on the ASGs to terminate only instances from the ASG with the this tag key and value
#simianarmy.chaos.ASGtag.key = chaos_monkey
#simianarmy.chaos.ASGtag.value = true
实际输出
# The file contains the properties for Chaos Monkey.
# see documentation at:
# https://github.com/Netflix/SimianArmy/wiki/Configuration
# let chaos run
simianarmy.chaos.enabled = true
# don't allow chaos to kill (ie dryrun mode)
simianarmy.chaos.leashed = true
# set to "false" for Opt-In behavior, "true" for Opt-Out behavior
simianarmy.chaos.ASG.enabled = false
# uncomment this line to use tunable aggression
#simianarmy.client.chaos.class = com.netflix.simianarmy.tunable.TunablyAggressiveChaosMonkey
# default probability for all ASGs
simianarmy.chaos.ASG.probability = 1.0
# increase or decrease the termination limit
simianarmy.chaos.ASG.maxTerminationsPerDay = 1.0
# Strategies
simianarmy.chaos.shutdowninstance.enabled = true
simianarmy.chaos.blockallnetworktraffic.enabled = false
simianarmy.chaos.burncpu.enabled = false
simianarmy.chaos.killprocesses.enabled = false
simianarmy.chaos.nullroute.enabled = false
simianarmy.chaos.failapi.enabled = false
simianarmy.chaos.faildns.enabled = false
simianarmy.chaos.faildynamodb.enabled = false
simianarmy.chaos.fails3.enabled = false
simianarmy.chaos.networkcorruption.enabled = false
simianarmy.chaos.networklatency.enabled = false
simianarmy.chaos.networkloss.enabled = false
# Force-detaching EBS volumes may cause data loss
simianarmy.chaos.detachvolumes.enabled = false
# FillDisk fills the root disk.
# NOTE: This may incur charges for an EBS root volume. See burnmoney option.
simianarmy.chaos.burnio.enabled = false
# BurnIO causes disk activity on the root disk.
# NOTE: This may incur charges for an EBS root volume. See burnmoney option.
simianarmy.chaos.filldisk.enabled = false
# Where we know the chaos strategy will incur charges, we won't run it unless burnmoney is true.
simianarmy.chaos.burnmoney = false
# enable a specific ASG
# simianarmy.chaos.ASG.<asgName>.enabled = true
# simianarmy.chaos.ASG.<asgName>.probability = 1.0
# increase or decrease the termination limit for a specific ASG
# simianarmy.chaos.ASG.<asgName>.maxTerminationsPerDay = 1.0
# Enroll in mandatory terminations. If a group has not had a
# termination within the windowInDays range then it will terminate
# one instance in the group with a 0.5 probability (at some point in
# the next 2 days an instance should be terminated), then
# do nothing again for windowInDays. This forces "enabled" groups
# that have a probability of 0.0 to have terminations periodically.
simianarmy.chaos.mandatoryTermination.enabled = false
simianarmy.chaos.mandatoryTermination.windowInDays = 32
simianarmy.chaos.mandatoryTermination.defaultProbability = 0.5
# Enable notification for Chaos termination for a specific instance group
# simianarmy.chaos.<groupType>.<groupName>.notification.enabled = true
# Set the destination email the termination notification sent to for a specific instance group
# simianarmy.chaos.<groupType>.<groupName>.ownerEmail = foo@bar.com
# Set the source email that sends the termination notification
# simianarmy.chaos.notification.sourceEmail = foo@bar.com
# Enable notification for Chaos termination for all instance groups
#simianarmy.chaos.notification.global.enabled = true
# Set the destination email the termination notification is sent to for all instance groups
#simianarmy.chaos.notification.global.receiverEmail = foo@bar.com
# Set a prefix applied to the subject of all termination notifications
# Probably want to include a trailing space to separate from start of default text
#simianarmy.chaos.notification.subject.prefix = SubjectPrefix
# Set a suffix applied to the subject of all termination notifications
# Probably want to include an escaped space " \ " to separate from end of default text
#simianarmy.chaos.notification.subject.suffix = \ SubjectSuffix
# Set a prefix applied to the body of all termination notifications
# Probably want to include a trailing space to separate from start of default text
#simianarmy.chaos.notification.body.prefix = BodyPrefix
# Set a suffix applied to the body of all termination notifications
# Probably want to include an escaped space " \ " to separa# The file contains the properties for Chaos Monkey.
# see documentation at:
# https://github.com/Netflix/SimianArmy/wiki/Configuration
# let chaos run
simianarmy.chaos.enabled = {{getv "/simianarmy/chaos/enabled" "true"}}
# don't allow chaos to kill (ie dryrun mode)
simianarmy.chaos.leashed = {{getv "/simianarmy/chaos/leashed" "true"}}
# set to "false" for Opt-In behavior, "true" for Opt-Out behavior
simianarmy.chaos.ASG.enabled = {{getv "/simianarmy/chaos/asg/enabled" "false"}}
# uncomment this line to use tunable aggression
{{if exists "/simianarmy/client/chaos/class" -}}
simianarmy.client.chaos.class = {{getv "/simianarmy/client/chaos/class" "com.netflix.simianarmy.tunable.TunablyAggressiveChaosMonkey"}}
{{end -}}
# default probability for all ASGs
simianarmy.chaos.ASG.probability = {{getv "/simianarmy/chaos/asg/probability" "1.0"}}
# increase or decrease the termination limit
simianarmy.chaos.ASG.maxTerminationsPerDay = {{getv "/simianarmy/chaos/asg/maxterminationsperday" "1.0"}}
# Strategies
simianarmy.chaos.shutdowninstance.enabled = {{getv "/simianarmy/chaos/shutdowninstance/enabled" "true"}}
simianarmy.chaos.blockallnetworktraffic.enabled = {{getv "/simianarmy/chaos/blockallnetworktraffic/enabled" "false"}}
simianarmy.chaos.burncpu.enabled = {{getv "/simianarmy/chaos/burncpu/enabled" "false"}}
simianarmy.chaos.killprocesses.enabled = {{getv "/simianarmy/chaos/killprocesses/enabled" "false"}}
simianarmy.chaos.nullroute.enabled = {{getv "/simianarmy/chaos/nullroute/enabled" "false"}}
simianarmy.chaos.failapi.enabled = {{getv "/simianarmy/chaos/failapi/enabled" "false"}}
simianarmy.chaos.faildns.enabled = {{getv "/simianarmy/chaos/faildns/enabled" "false"}}
simianarmy.chaos.faildynamodb.enabled = {{getv "/simianarmy/chaos/faildynamodb/enabled" "false"}}
simianarmy.chaos.fails3.enabled = {{getv "/simianarmy/chaos/fails3/enabled" "false"}}
simianarmy.chaos.networkcorruption.enabled = {{getv "/simianarmy/chaos/networkcorruption/enabled" "false"}}
simianarmy.chaos.networklatency.enabled = {{getv "/simianarmy/chaos/networklatency/enabled" "false"}}
simianarmy.chaos.networkloss.enabled = {{getv "/simianarmy/chaos/networkloss/enabled" "false"}}
# Force-detaching EBS volumes may cause data loss
simianarmy.chaos.detachvolumes.enabled = {{getv "/simianarmy/chaos/detachvolumes/enabled" "false"}}
# FillDisk fills the root disk.
# NOTE: This may incur charges for an EBS root volume. See burnmoney option.
simianarmy.chaos.burnio.enabled = {{getv "/simianarmy/chaos/burnio/enabled" "false"}}
# BurnIO causes disk activity on the root disk.
# NOTE: This may incur charges for an EBS root volume. See burnmoney option.
simianarmy.chaos.filldisk.enabled = {{getv "/simianarmy/chaos/filldisk/enabled" "false"}}
# Where we know the chaos strategy will incur charges, we won't run it unless burnmoney is true.
simianarmy.chaos.burnmoney = {{getv "/simianarmy/chaos/burnmoney" "false"}}
# enable a specific ASG
{{if exists "/simianarmy/chaos/asg/<asgname>/enabled" -}}
simianarmy.chaos.ASG.<asgName>.enabled = {{getv "/simianarmy/chaos/asg/<asgname>/enabled" "true"}}
{{end -}}
{{if exists "/simianarmy/chaos/asg/<asgname>/probability" -}}
simianarmy.chaos.ASG.<asgName>.probability = {{getv "/simianarmy/chaos/asg/<asgname>/probability" "1.0"}}
{{end -}}
# increase or decrease the termination limit for a specific ASG
{{if exists "/simianarmy/chaos/asg/<asgname>/maxterminationsperday" -}}
simianarmy.chaos.ASG.<asgName>.maxTerminationsPerDay = {{getv "/simianarmy/chaos/asg/<asgname>/maxterminationsperday" "1.0"}}
{{end -}}
# Enroll in mandatory terminations. If a group has not had a
# termination within the windowInDays range then it will terminate
# one instance in the group with a 0.5 probability (at some point in
# the next 2 days an instance should be terminated), then
# do nothing again for windowInDays. This forces "enabled" groups
# that have a probability of 0.0 to have terminations periodically.
simianarmy.chaos.mandatoryTermination.enabled = {{getv "/simianarmy/chaos/mandatorytermination/enabled" "false"}}
simianarmy.chaos.mandatoryTermination.windowInDays = {{getv "/simianarmy/chaos/mandatorytermination/windowindays" "32"}}
simianarmy.chaos.mandatoryTermination.defaultProbability = {{getv "/simianarmy/chaos/mandatorytermination/defaultprobability" "0.5"}}
# Enable notification for Chaos termination for a specific instance group
{{if exists "/simianarmy/chaos/<grouptype>/<groupname>/notification/enabled" -}}
simianarmy.chaos.<groupType>.<groupName>.notification.enabled = {{getv "/simianarmy/chaos/<grouptype>/<groupname>/notification/enabled" "true"}}
{{end -}}
# Set the destination email the termination notification sent to for a specific instance group
{{if exists "/simianarmy/chaos/<grouptype>/<groupname>/owneremail" -}}
simianarmy.chaos.<groupType>.<groupName>.ownerEmail = {{getv "/simianarmy/chaos/<grouptype>/<groupname>/owneremail" "foo@bar.com"}}
{{end -}}
# Set the source email that sends the termination notification
{{if exists "/simianarmy/chaos/notification/sourceemail" -}}
simianarmy.chaos.notification.sourceEmail = {{getv "/simianarmy/chaos/notification/sourceemail" "foo@bar.com"}}
{{end -}}
# Enable notification for Chaos termination for all instance groups
{{if exists "/simianarmy/chaos/notification/global/enabled" -}}
simianarmy.chaos.notification.global.enabled = {{getv "/simianarmy/chaos/notification/global/enabled" "true"}}
{{end -}}
# Set the destination email the termination notification is sent to for all instance groups
{{if exists "/simianarmy/chaos/notification/global/receiveremail" -}}
simianarmy.chaos.notification.global.receiverEmail = {{getv "/simianarmy/chaos/notification/global/receiveremail" "foo@bar.com"}}
{{end -}}
# Set a prefix applied to the subject of all termination notifications
# Probably want to include a trailing space to separate from start of default text
{{if exists "/simianarmy/chaos/notification/subject/prefix" -}}
simianarmy.chaos.notification.subject.prefix = {{getv "/simianarmy/chaos/notification/subject/prefix" "SubjectPrefix"}}
{{end -}}
# Set a suffix applied to the subject of all termination notifications
# Probably want to include an escaped space " \ " to separate from end of default text
{{if exists "/simianarmy/chaos/notification/subject/suffix" -}}
simianarmy.chaos.notification.subject.suffix = {{getv "/simianarmy/chaos/notification/subject/suffix" "\ SubjectSuffix"}}
{{end -}}
# Set a prefix applied to the body of all termination notifications
# Probably want to include a trailing space to separate from start of default text
{{if exists "/simianarmy/chaos/notification/body/prefix" -}}
simianarmy.chaos.notification.body.prefix = {{getv "/simianarmy/chaos/notification/body/prefix" "BodyPrefix"}}
{{end -}}
# Set a suffix applied to the body of all termination notifications
# Probably want to include an escaped space " \ " to separa
最佳答案
它会附加数据,因为当您读完时光标位于文件末尾。您可以使用 Seek() 移动光标,或者只是在阅读更多时打开它 (os.Open()) 然后覆盖 (os.Create( )) 阅读完毕。
关于go - 文件在应用程序中附加而不覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48794203/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我想用ruby编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序