Created
May 1, 2013 22:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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