I have a file that looks like:
my.githash="asdfsadfdsf"
some.key=234
some.blue=abchello
russia.green="asdfdsf"
I want to replace the string for the key my.githash with an up to date git hash vlaue.
How can I use ruby to update my configuration file?
To get the git hash value I will be using:
git rev-parse HEAD
Using gsub
you can replace a string using a regular expression match. In your case it's a little bit tricky because you don't know exactly the match.
Hence you can use
string.gsub(/(githash="(.+)")/) { $1.gsub($2, 'NEW_SHA') }
You can fetch the NEW_SHA
running a shell command.
sha = `git rev-parse HEAD`
string.gsub(/(githash="(.+)")/) { $1.gsub($2, sha) }
and read the file from the file system
sha = `git rev-parse HEAD`
content = File.read('/path/to/fike')
content.gsub!(/(githash="(.+)")/) { $1.gsub($2, sha) }
File.write('/path/to/fike', content)
This is a very simple example. You can optimize it further. You can also use a single gsub
, but it will require you to write twice the delimiters.
content.gsub!(/githash="(.+)"/, %Q{githash="#{sha}"})
Another (longer but perhaps more accurate) way is to write a simple parser that loads the file in a Hash parsing each line (as lines seems to follow a specific syntax), and then dumps the Hash back in a formatted file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.