Skip to content

Instantly share code, notes, and snippets.

@webcoyote
Created May 1, 2013 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webcoyote/5498740 to your computer and use it in GitHub Desktop.
Save webcoyote/5498740 to your computer and use it in GitHub Desktop.
Search for a configuration file in current directory upwards towards root directory the way that .gitignore and .p4config work
#!/usr/bin/env ruby
class SearchConfigFile
def self.search (filename, directory)
# Use current directory if directory not specified
directory ||= Dir.getwd
# Use expand_path to get absolute path; 1.8.7 compatible
search_up filename, File.expand_path(directory)
end
private
# Search upwards for file starting from given directory
def self.search_up (filename, directory)
path = File.join directory, filename
return path if File.file?(path)
parent = File.dirname(directory)
return if parent == directory
search_up filename, parent
end
end
if __FILE__ == $0
testfile = "test.yml"
testdir = File.expand_path(ARGV.first || Dir.getwd)
puts "Searching upwards for #{testfile} from #{testdir}"
filename = SearchConfigFile.search testfile, testdir
if filename.nil?
puts "Not found"
exit 1
end
puts filename
exit 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment