class RuboCop::Cop::Style::FileTouch


FileUtils.touch(filename)
# good
File.open(filename, ‘a+’) {}
File.open(filename, ‘a’) {}
# bad
@example
`FileUtils.touch` updates an existing file’s timestamps.
Autocorrection is unsafe for this cop because unlike ‘File.open`,
@safety
should be used instead.
If the intention was to update timestamps, `FileUtils.touch(’foo.txt’)‘
# 2024-11-26 12:17:23 +0100 -> unchanged
ruby -e “puts File.mtime(’foo.txt’)”
ruby -e “File.open(‘foo.txt’, ‘a’) {}”
# 2024-11-26 12:17:23 +0100
ruby -e “puts File.mtime(‘foo.txt’)”
For example, for an existing file ‘foo.txt`:
timestamps for an existing file, which might have been the intention.
Such a usage only creates a new file, but it doesn’t update
Checks for usage of ‘File.open` in append mode with empty block.

def empty_block?(node)

def empty_block?(node)
  node.block_type? && !node.body
end

def on_send(node)

def on_send(node)
  filename = file_open?(node)
  parent = node.parent
  return unless filename
  return unless parent && empty_block?(parent)
  message = format(MSG, argument: filename.source)
  add_offense(parent, message: message) do |corrector|
    corrector.replace(parent, "FileUtils.touch(#{filename.source})")
  end
end