Skip to content

Instantly share code, notes, and snippets.

@cander
Last active March 6, 2019 01:17
Show Gist options
  • Save cander/deaa097e5b4b18f712edc8637d458bc0 to your computer and use it in GitHub Desktop.
Save cander/deaa097e5b4b18f712edc8637d458bc0 to your computer and use it in GitHub Desktop.
Create a hierarchy of files and directories based on the output of find
#!/bin/env ruby
#
# Given output from find(1) listing files and directories, reproduce that
# hierarchy with random data in the files.
#
# Usage: ruby make-dir-hierarchy.rb [find-output-file]
#
require 'securerandom'
def make_directory(path)
puts "mkdir #{path}"
Dir.mkdir(path) unless File.directory?(path)
end
def make_file(path, size)
dirname = File.dirname(path)
Dir.mkdir(dirname) unless File.directory?(dirname) # nneeded
puts "creating #{path} with #{size} bytes"
File.open(path, "w") { |fd| fd.puts SecureRandom.hex(size / 2) }
end
# Each line looks something like:
# 7306719 8 -rw-rw-r-- 1 bart staff 2586 Feb 20 13:23 ./core/misc/displace.js
def process_line(line)
toks = line.split
mode_str = toks[2]
size = toks[6].to_i
path = toks[-1] # does not handle spaces in names
case mode_str
when /^d/
make_directory(path)
when /^-/
make_file(path, size)
else
# we shouldn't see any symlinks??
puts "Unknown file mode: #{mode_str} for #{path}"
end
end
ARGF.each do |line|
process_line(line)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment