You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@whimsical.apache.org by se...@apache.org on 2022/04/12 15:01:07 UTC

[whimsy] branch master updated: Skip yaml update if block returns nil

This is an automated email from the ASF dual-hosted git repository.

sebb pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/whimsy.git


The following commit(s) were added to refs/heads/master by this push:
     new d3bc9030 Skip yaml update if block returns nil
d3bc9030 is described below

commit d3bc9030e6db9c35316ac4b938a0ae8c94d0f4bc
Author: Sebb <se...@apache.org>
AuthorDate: Tue Apr 12 16:01:01 2022 +0100

    Skip yaml update if block returns nil
---
 lib/spec/lib/yaml_spec.rb | 13 +++++++++++++
 lib/whimsy/asf/yaml.rb    | 11 +++++++----
 2 files changed, 20 insertions(+), 4 deletions(-)

diff --git a/lib/spec/lib/yaml_spec.rb b/lib/spec/lib/yaml_spec.rb
index 833e84fa..572433f4 100644
--- a/lib/spec/lib/yaml_spec.rb
+++ b/lib/spec/lib/yaml_spec.rb
@@ -77,6 +77,7 @@ describe YamlFile do
     end
   end
   describe "YamlFile.update" do
+    tmpname = File.join(tmpdir, 'yaml_spec3.yaml')
     it "should create empty file" do
       YamlFile.update(tmpname) do |yaml|
         expect(yaml.class).to equal(Hash)
@@ -90,5 +91,17 @@ describe YamlFile do
       yaml = YamlFile.read(tmpname)
       expect(yaml.size).to equal(1)
     end
+    it "read not change the file time-stamp" do
+      mtime1 = File.mtime(tmpname)
+      YamlFile.update(tmpname) do |yaml|
+        expect(yaml.class).to equal(Hash)
+        expect(yaml.size).to equal(1)
+        yaml['test2'] = {a: 'b'}
+        expect(yaml.size).to equal(2)
+        nil
+      end
+      mtime2 = File.mtime(tmpname)
+      expect(mtime2).to eq(mtime1)
+    end
   end
 end
diff --git a/lib/whimsy/asf/yaml.rb b/lib/whimsy/asf/yaml.rb
index 8f41c4be..c055b3e8 100644
--- a/lib/whimsy/asf/yaml.rb
+++ b/lib/whimsy/asf/yaml.rb
@@ -13,7 +13,7 @@ module YamlFile
   # opens the file for exclusive access with an exclusive lock,
   # creating the file if necessary
   # Yields the parsed YAML to the block, and writes the return
-  # data to the file
+  # data to the file; if the block returns nil, the file will not be updated
   # The args are passed to YAML.safe_load, and default to permitted_classes: [Symbol]
   def self.update(yaml_file, *args)
     File.open(yaml_file, File::RDWR|File::CREAT, 0o644) do |file|
@@ -23,9 +23,12 @@ module YamlFile
       else
         yaml = YAML.safe_load(file.read, *args) || {}
       end
-      file.rewind
-      file.write YAML.dump(yield yaml)
-      file.truncate(file.pos)
+      output = yield yaml
+      unless output.nil?
+        file.rewind
+        file.write YAML.dump(output)
+        file.truncate(file.pos)
+      end
     end
   end