Error while moving a file (Errno::ENOENT) - ruby

I face the error when I try to move one file from another.
I'm sure that path is correct. The platform is windows. Permission is correct.
My code is below:
unless File.exists?(f2)
FileUtils.move(f1,f2)
end
Note I don't face problem with every file.

FileUtils.move(f1,f2) rescue do
not File.exists?(f1) and raise "source file does not exist"
File.exists?(f2) and raise "destination file already exists"
end
question should be closable now

Related

Nested `if` statement not evaluating the result of an operation

I am generating a file in a temp directory.
If the file to be generated is different from an already existing file, then I wan't to update it, and run a command. If it's the same, then I can do nothing.
My code looks like this:
errstatus = 0
if FileUtils.identical?('/var/tmp/newfile', '/var/tmp/originalfile')
$stderr.puts "Files are the same, nothing to do"
else
$stderr.puts "Files are different, let's update them."
if FileUtils.cp_r '/var/tmp/newfile', '/var/tmp/originalfile'
$stderr.puts "File copied successfully."
if system('systemcommand1 here')
$stderr.puts "command ran OK"
if system('systemcommand2 here')
$stderr.puts "next command ran ok"
else
$stderr.puts "command 2 failed"
errstatus = 1
end
else
$stderr.puts "command 1 failed"
errstatus = 1
end
end
end
When I run it when the files are different, I get the output:
Files are different, let's update them.
It runs with FileUtils.cp_r without any errors, but it doesn't tell that the File was copied successfully, or run the system command. I have used the same syntax to evaluate FileUtils.identical?, but it does not work for FileUtils.cp_r.
Where am I going wrong here?
FileUtils::cp_r returns nil (which in Ruby is falsy) if the copying was successful, raises an error if not. It will never return a truthy value, so making it a condition does not make sense.
Since it doesn't have an else statement right now, simply remove the if before it. If you want error handling for your cp_r, you will need to wrap it into a begin..rescue block.
Maybe it's because the if FileUtils.cp_r '/var/tmp/newfile', '/var/tmp/originalfile' doesn't have an else clause so if it returns false or throws and exception it doesn't enter the if.

Keeping files updated with a Chef recipe

The challenge prompt is above, and my latest attempt is below. The directories and files are created as expected, and the read-out after executing chef-apply multipleCopies.rb tells me the files are linked, but when I update any one of the files, the others do not follow suit. Any ideas? Here is my code:
for x in 1..3
directory "multipleCopy#{x}" do
mode '0755'
action :create
end
end
file "multipleCopy1/secret.txt" do
mode '0755'
action :create
end
for x in 2..3
link "multipleCopy#{x}/secret.txt" do
to "multipleCopy1/secret.txt"
link_type :hard
subscribes :reload, "multipleCopy1/secret.txt", :immediately
end
end
Note: For less headache, I am testing the recipe locally before uploading to the ubuntu server referenced in the prompt, which is why my file paths are different and why I have not yet included the ownership properties.
So a file hard link doesn't seem to be what the question is going for (though I would say your solution is maybe better since this is really not what Chef is for, more on that later). Instead they seem to want you to have three actually different files, but sync the contents.
So first the easy parts, creating the directories and the empty initial files. It's rare to see those for loops used in Ruby code, though it is syntactically valid:
3.times do |n|
directory "/var/save/multipleCopy#{n+1}" do
owner "ubuntu"
group "root"
mode "755"
end
file "/var/save/multipleCopy#{n+1}/secret.txt" do
owner "root
group "root"
mode "755"
end
end
But that doesn't implement the hard part of sync'ing the files. For that we need to first analyze the mtimes on the files and use the most recent as the file content to set.
latest_file = 3.times.sort_by { |n| ::File.mtime("/var/save/multipleCopy#{n+1}/secret.txt") rescue 0 }
latest_content = ::File.read("/var/save/multipleCopy#{latest_file+1}/secret.txt") rescue nil
and then in the file resource:
file "/var/save/multipleCopy#{n+1}/secret.txt" do
owner "root
group "root"
mode "755"
content latest_content
end
As for this not being a good use of Chef: Chef is about writing code which asserts the desired state of the machine. In the case of files like this, rather than doing this kind of funky stuff to check if a file has been edited, you would just say that Chef owns the file content for all three and if you want to update it, you do it via your cookbook (and then usually use a template or cookbook_file resource).

How to write a file with ruby? [duplicate]

This question already has answers here:
How to write to file in Ruby?
(7 answers)
Closed 7 years ago.
I want to create a temp file:
def create_file
FileUtils.mkdir_p('/var/log/my_app')
tmp_file = '/var/log/my_app/tmp_file'
File.open(tmp_file, 'w') do |file|
file.write 'test'
end
end
Here I am sure that the /var/log/my_app path exists. But after I run this method, I can't find a file named tmp_file under that path.
And there wasn't any error, too.
I think you would do better using Ruby's TempFile class and perhaps even Ruby's temp dir as suggested in this article: Quick tips for doing IO with Ruby.
I think you will find the article helpful. I believe it will make your approach easier - especially regarding deleting the file once you're done with it.
I don't see any error in your code. If you don't get any exception, the file must have been created, if this function has been executed.
I suggest that you make a test at the end of create_file:
if File.file?
puts "File has been created"
else
fail "File is not there!"
end
If you see "File has been created", but the file is still missing, something must have erased it before you had time to check its presence. If you see "File is not there!", something weird is going on and I would call an exorcist. If you don't see any message, it means that your function has not been executed.

Having trouble in getting input from user in Ruby

I have a method which check if the file exists, If the file does not exist then it should call another method which prompts the questions. Below is the sample code.
def readFile1()
flag = false
begin
#ssh.exec!("cd #{##home_dir}")
puts "\nChecking if file exists on #{#hostname}\n"
if #ssh.exec!("sh -c '[ -f "#{file_name}" ]; echo $?'").to_i == 0
flag = true
puts "File exists on #{#hostname}"
display()
else
puts "File does not exist. Please answer following questions."
prompt()
end
rescue => e
puts "readFile1 failed... #{e}"
end
return exists
end
def prompt()
puts "\nDo you want to enter the new file location? [y/n]"
ans = gets.chomp
puts "New location is #{ans}"
end
When I am calling readFile method, if the file does not exists, it prints Do you want to enter the new file location? [y/n] and does not wait for the user to enter the value but immediately prints the rescue block and quits. Below is the Output if file does not exists.
Checking if file exists on LNXAPP
File does not exist. Please answer following questions.
Do you want to enter the new file location? [y/n]
readFile1 failed... No such file or directory - LNXAPP
I want the user to enter the values for the questions but it's not happening.Need help in fixing this.
Your code is not ideal.
You should check if the file exists via:
if File.exist? location_of_your_file_goes_here
The begin/rescue is then not required, because
you already check before whether the file exists.
Also two spaces should be better than one tab,
at least when you display on a site such as here.
Reason is simple - it makes your code easier
to read for others.
You also don't need the flag variable if I am
right - try to omit it and use solely File.exist?
there.
Also you wrote:
"When I am calling readFile method"
But you have no method called readFile().
Your method is called readFile1().
I know that you probably know this too, but
you must be very specific so that the ruby
parser understands precisely what you mean,
and that what you describe with words also
matches to the code you use.
Another issue I see with your code is that
you do this:
return exists
but what is "exists" here? A variable?
A method? It has not been defined elsewhere
in your code.
Try to make your code as simple and as logical
as possible.

"No such file or directory" error

I am working through the event_manager intro to ruby lessons, and need to load a file called
event_attendees.csv from my event_manager.rb.
I cannot figure out where to put the event_attendees.csv file. I know that it needs to go in the root directory but I cannot figure out where that is.
When I look at the Dir.pwd for my ruby document, I get:
C:/Ruby_Documents/event_manger/event_manager/lib
Does it matter that windows uses \ instead of / when I call the doc? This is where I am:
puts "EventManager initialized"
contents = File.read "event_attendees.csv"
puts contents
according to event_manager instructions you just need one event_manager directory and you need to put your event_attendees.csv in the same directory.

Resources