hack-is-art hack-is-art - 1 month ago 8
Ruby Question

Iterate over directories and subdirectories recursively showing 'path/file' in ruby

I am using the code below to iterate recursively over files of directories and subfolders:

Dir.glob("**/*").each do |file|

filename = "#{File.basename(file)}"
output = `git log -1 -r -n 1 --pretty=format:\"%h: #{filename}\" -- #{filename}`

end


The result I am getting from this iteration looks like this:

Actual Output:
<The format I choose>: folder1
<The format I choose>: a_file
<The format I choose>: folder2
<The format I choose>: a_file
<The format I choose>: another_file
<The format I choose>: folder3
<The format I choose>: a_file


While the form I want is below.

Expected Output:
<The format I choose>: folder1/a_file
<The format I choose>: folder2/a_file
<The format I choose>: folder2/another_file
<The format I choose>: folder3/a_file


Can you point and explain my error in the loop?

Answer

Basically the reason is that you are running File.basename which gives you the 'basename' of the File and not the relative path.

Additionally the .glob("**/*") also includes directories and as such you need to take that into account.

This is how I would do it...

Dir.glob("**/*").each do |file|
   next if File.directory?(file) # skip the loop if the file is a directory
   puts file
   output = `git log -1 -r -n 1 --pretty=format:"%cd [%h]" -- #{file}`
   puts output  
end

Let me know if you want me to explain any line in the above code...