|
1 | 1 | defmodule GitHooks.Git.GitPath do
|
2 | 2 | @moduledoc false
|
3 | 3 |
|
| 4 | + alias GitHooks.Git |
| 5 | + |
4 | 6 | @doc """
|
5 | 7 | Returns the absolute path to the project's root directory.
|
6 | 8 | """
|
7 | 9 | def resolve_app_path do
|
8 |
| - # Attempt to get the project path from the config, |
9 |
| - # otherwise find the git root by traversing upwards. |
10 |
| - Application.get_env(:git_hooks, :project_path) || |
| 10 | + project_path = Application.get_env(:git_hooks, :project_path) |
| 11 | + |
| 12 | + if project_path do |
| 13 | + Path.expand(project_path) |
| 14 | + else |
| 15 | + # Find the git root by traversing upwards |
11 | 16 | find_git_root(File.cwd!()) ||
|
12 |
| - raise "Could not find .git directory from #{File.cwd!()}" |
| 17 | + raise "Could not find .git directory from #{File.cwd!()}" |
| 18 | + end |
13 | 19 | end
|
14 | 20 |
|
15 | 21 | @doc """
|
16 | 22 | Returns the absolute `.git/hooks` path directory for the parent project.
|
17 | 23 | """
|
18 | 24 | def resolve_git_hooks_path do
|
19 |
| - Path.join(resolve_git_dir(), "hooks") |
| 25 | + "hooks" |
| 26 | + |> resolve_git_path() |
| 27 | + |> Path.expand(resolve_app_path()) |
20 | 28 | end
|
21 | 29 |
|
22 | 30 | @doc """
|
23 | 31 | Returns the path to a specific hook file within the `.git/hooks` directory.
|
24 | 32 | """
|
25 | 33 | def git_hooks_path_for(hook_name) do
|
26 |
| - Path.join(resolve_git_hooks_path(), hook_name) |
| 34 | + resolve_git_hooks_path() |
| 35 | + |> Path.join(hook_name) |
| 36 | + |> Path.expand() |
27 | 37 | end
|
28 | 38 |
|
29 | 39 | #
|
30 | 40 | # Private helper functions
|
31 | 41 | #
|
32 | 42 |
|
| 43 | + # Resolves the absolute path to a directory within the `.git` directory |
| 44 | + defp resolve_git_path(dir) when is_binary(dir) and dir != "" do |
| 45 | + git_path = |
| 46 | + Git.git_version() |
| 47 | + |> Version.compare(Version.parse!("2.10.0")) |
| 48 | + |> case do |
| 49 | + :lt -> |
| 50 | + git_dir = resolve_git_dir() |
| 51 | + Path.join(git_dir, dir) |
| 52 | + |
| 53 | + _ -> |
| 54 | + {git_path, 0} = |
| 55 | + System.cmd("git", ["rev-parse", "--git-path", dir], cd: resolve_app_path()) |
| 56 | + |
| 57 | + String.trim(git_path) |
| 58 | + end |
| 59 | + |
| 60 | + Path.expand(git_path, resolve_app_path()) |
| 61 | + end |
| 62 | + |
| 63 | + defp resolve_git_path(_dir) do |
| 64 | + raise ArgumentError, "resolve_git_path/1 requires a non-empty directory argument" |
| 65 | + end |
| 66 | + |
33 | 67 | # Returns the absolute `.git` directory path for the parent project.
|
34 | 68 | defp resolve_git_dir do
|
35 | 69 | {git_dir, 0} =
|
|
0 commit comments