diff options
author | elijah <elijah@riseup.net> | 2013-06-04 23:06:10 -0700 |
---|---|---|
committer | elijah <elijah@riseup.net> | 2013-06-04 23:06:10 -0700 |
commit | 8f79b632aeeee1111087dee6ebb6302aca700bbd (patch) | |
tree | 647b24bee28b28301de6c4a82a916222cde491e8 /lib/leap_cli/util.rb | |
parent | a46321a43318a9cd3e2dd645b64fe81b71e7f8ea (diff) |
add support for `leap facts`. includes some fun new helpers, like run_with_progress(), capture(), and replace_file!().
Diffstat (limited to 'lib/leap_cli/util.rb')
-rw-r--r-- | lib/leap_cli/util.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/leap_cli/util.rb b/lib/leap_cli/util.rb index b2a1dcf..116c212 100644 --- a/lib/leap_cli/util.rb +++ b/lib/leap_cli/util.rb @@ -203,6 +203,40 @@ module LeapCli end end + # + # replace contents of a file, with an exclusive lock. + # + # 1. locks file + # 2. reads contents + # 3. yields contents + # 4. replaces file with return value of the block + # + def replace_file!(filepath, &block) + filepath = Path.named_path(filepath) + if !File.exists?(filepath) + content = yield(nil) + unless content.nil? + write_file!(filepath, content) + log :created, filepath + end + else + File.open(filepath, File::RDWR|File::CREAT, 0644) do |f| + f.flock(File::LOCK_EX) + old_content = f.read + new_content = yield(old_content) + if old_content == new_content + log :nochange, filepath, 2 + else + f.rewind + f.write(new_content) + f.flush + f.truncate(f.pos) + log :updated, filepath + end + end + end + end + def remove_file!(filepath) filepath = Path.named_path(filepath) if File.exists?(filepath) |