From 67cbf7f11e0e44663196cdf9e478590f2a957559 Mon Sep 17 00:00:00 2001 From: ydah <13041216+ydah@users.noreply.github.com> Date: Tue, 28 Jun 2022 17:24:11 +0900 Subject: [PATCH] Add new "Atomic File Operations" rule When doing file operations after confirming the existence check of a file, frequent parallel file operations may cause problems that are difficult to reproduce. Therefore, it is preferable to use atomic file operations. ```ruby # bad - race condition with another process may result in an error in `mkdir` unless Dir.exist?(path) FileUtils.mkdir(path) end # good - atomic and idempotent creation FileUtils.mkdir_p(path) # bad - race condition with another process may result in an error in `remove` if File.exist?(path) FileUtils.remove(path) end # good - atomic and idempotent removal FileUtils.rm_f(path) ``` --- README.adoc | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.adoc b/README.adoc index e43a0e1d..0b590038 100644 --- a/README.adoc +++ b/README.adoc @@ -2185,6 +2185,30 @@ File.open('testfile') do |f| end ---- +=== Atomic File Operations [[atomic-file-operations]] + +When doing file operations after confirming the existence check of a file, frequent parallel file operations may cause problems that are difficult to reproduce. +Therefore, it is preferable to use atomic file operations. + +[source,ruby] +---- +# bad - race condition with another process may result in an error in `mkdir` +unless Dir.exist?(path) + FileUtils.mkdir(path) +end + +# good - atomic and idempotent creation +FileUtils.mkdir_p(path) + +# bad - race condition with another process may result in an error in `remove` +if File.exist?(path) + FileUtils.remove(path) +end + +# good - atomic and idempotent removal +FileUtils.rm_f(path) +---- + === Standard Exceptions [[standard-exceptions]] Prefer the use of exceptions from the standard library over introducing new exception classes.