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 117b9a4 Common routines for YAML updates
117b9a4 is described below
commit 117b9a499919e4b6627eee796176164607ce255f
Author: Sebb <[email protected]>
AuthorDate: Mon Jun 1 17:19:10 2020 +0100
Common routines for YAML updates
---
lib/whimsy/asf/yaml.rb | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 54 insertions(+)
diff --git a/lib/whimsy/asf/yaml.rb b/lib/whimsy/asf/yaml.rb
new file mode 100644
index 0000000..143a3d6
--- /dev/null
+++ b/lib/whimsy/asf/yaml.rb
@@ -0,0 +1,54 @@
+#!/usr/bin/env ruby
+
+require 'yaml'
+
+#
+# YAML file support
+#
+
+module YamlFile
+
+ #
+ # encapsulate updates to a YAML file
+ # opens the file for exclusive access with an exclusive lock
+ # Yields the parsed YAML to the block, and writes the updated
+ # data to the file
+ def self.update(yaml_file)
+ File.open(yaml_file, File::RDWR|File::CREAT, 0644) do |file|
+ file.flock(File::LOCK_EX)
+ yaml = YAML.load(file.read) || {} rescue {}
+ yield yaml
+ file.rewind
+ file.write YAML.dump(yaml)
+ file.truncate(file.pos)
+ end
+ end
+
+ #
+ # encapsulate reading a YAML file
+ # Opens the file read-only, with a shared lock, and parses the YAML
+ # This is yielded to the block (if provided), whilst holding the lock
+ # Otherwise the YAML is returned to the caller, and the lock is released
+ def self.read(yaml_file)
+ File.open(yaml_file, File::RDONLY) do |file|
+ file.flock(File::LOCK_SH)
+ yaml = YAML.load(file.read) || {} rescue {}
+ if block_given?
+ yield yaml
+ else
+ return yaml
+ end
+ end
+ end
+end
+
+if __FILE__ == $0
+ file = "/tmp/test.yaml"
+ YamlFile.update(file) do |yaml|
+ yaml['y'] = {ac: 'c'}
+ end
+ YamlFile.read(file) do |yaml|
+ p yaml
+ end
+ p YamlFile.read(file)
+end
\ No newline at end of file