Last active
January 22, 2021 10:43
-
-
Save nickserv/8466084 to your computer and use it in GitHub Desktop.
Ruby script: Find the current git repository
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
# Script: Find the current git repository | |
# Based on https://github.com/mojombo/grit/pull/178 by https://github.com/derricks | |
# Be sure to "gem install grit" before running this script | |
require 'grit' | |
# Returns true if the given path represents a root directory (/ or C:/) | |
def root_directory?(file_path) | |
# Implementation inspired by http://stackoverflow.com/a/4969416: | |
# Does file + ".." resolve to the same directory as file_path? | |
File.directory?(file_path) && | |
File.expand_path(file_path) == File.expand_path(File.join(file_path, '..')) | |
end | |
# Returns the git root directory given a path inside the repo. Returns nil if | |
# the path is not in a git repo. | |
def find_git_repo(start_path = '.') | |
raise NoSuchPathError unless File.exists?(start_path) | |
current_path = File.expand_path(start_path) | |
# for clarity: set to an explicit nil and then just return whatever | |
# the current value of this variable is (nil or otherwise) | |
return_path = nil | |
until root_directory?(current_path) | |
if File.exists?(File.join(current_path, '.git')) | |
# done | |
return_path = current_path | |
break | |
else | |
# go up a directory and try again | |
current_path = File.dirname(current_path) | |
end | |
end | |
return_path | |
end | |
# Returns a new Grit::Repo instance for the repo that has the given path. | |
# Returns nil if the path is not in a git repo. | |
def find_grit_repo(start_path = '.') | |
path = find_git_repo start_path | |
path.nil? ? nil : Grit::Repo.new(path) | |
end | |
# Command line interface (for testing) | |
puts find_git_repo(ARGV.first || '.') || '[no results]' |
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
def test_new_should_work_in_subdirectory | |
tmpdir = Dir.mktmpdir | |
gpath = File.join(tmpdir, '.git') | |
subdir_path = File.join(tmpdir, 'test_subdirectory') | |
FileUtils.mkdir_p(gpath) | |
FileUtils.mkdir_p(subdir_path) | |
assert(Repo.new(subdir_path)) | |
FileUtils.rm_rf(tmpdir) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment