git 4.4.6 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +1 -0
  3. data/CHANGELOG.md +348 -39
  4. data/CONTRIBUTING.md +1014 -144
  5. data/README.md +386 -504
  6. data/UPGRADING.md +1822 -0
  7. data/git.gemspec +102 -22
  8. data/lib/git/author_info.rb +65 -0
  9. data/lib/git/branch_delete_failure.rb +34 -0
  10. data/lib/git/branch_delete_result.rb +66 -0
  11. data/lib/git/branch_info.rb +237 -0
  12. data/lib/git/command_line/base.rb +247 -0
  13. data/lib/git/command_line/capturing.rb +308 -0
  14. data/lib/git/command_line/result.rb +88 -0
  15. data/lib/git/command_line/streaming.rb +236 -0
  16. data/lib/git/command_line.rb +45 -323
  17. data/lib/git/commands/add.rb +139 -0
  18. data/lib/git/commands/am/abort.rb +43 -0
  19. data/lib/git/commands/am/apply.rb +263 -0
  20. data/lib/git/commands/am/continue.rb +43 -0
  21. data/lib/git/commands/am/quit.rb +43 -0
  22. data/lib/git/commands/am/retry.rb +49 -0
  23. data/lib/git/commands/am/show_current_patch.rb +64 -0
  24. data/lib/git/commands/am/skip.rb +42 -0
  25. data/lib/git/commands/am.rb +33 -0
  26. data/lib/git/commands/apply.rb +242 -0
  27. data/lib/git/commands/archive/list_formats.rb +46 -0
  28. data/lib/git/commands/archive.rb +145 -0
  29. data/lib/git/commands/arguments.rb +4521 -0
  30. data/lib/git/commands/base.rb +522 -0
  31. data/lib/git/commands/branch/copy.rb +102 -0
  32. data/lib/git/commands/branch/create.rb +177 -0
  33. data/lib/git/commands/branch/delete.rb +88 -0
  34. data/lib/git/commands/branch/list.rb +178 -0
  35. data/lib/git/commands/branch/move.rb +102 -0
  36. data/lib/git/commands/branch/set_upstream.rb +86 -0
  37. data/lib/git/commands/branch/show_current.rb +49 -0
  38. data/lib/git/commands/branch/unset_upstream.rb +53 -0
  39. data/lib/git/commands/branch.rb +34 -0
  40. data/lib/git/commands/cat_file/batch.rb +385 -0
  41. data/lib/git/commands/cat_file/filtered.rb +105 -0
  42. data/lib/git/commands/cat_file/raw.rb +203 -0
  43. data/lib/git/commands/cat_file.rb +49 -0
  44. data/lib/git/commands/checkout/branch.rb +153 -0
  45. data/lib/git/commands/checkout/files.rb +116 -0
  46. data/lib/git/commands/checkout.rb +38 -0
  47. data/lib/git/commands/checkout_index.rb +106 -0
  48. data/lib/git/commands/clean.rb +102 -0
  49. data/lib/git/commands/clone.rb +241 -0
  50. data/lib/git/commands/commit.rb +273 -0
  51. data/lib/git/commands/commit_tree.rb +101 -0
  52. data/lib/git/commands/config_option_syntax/add.rb +86 -0
  53. data/lib/git/commands/config_option_syntax/get.rb +121 -0
  54. data/lib/git/commands/config_option_syntax/get_all.rb +118 -0
  55. data/lib/git/commands/config_option_syntax/get_color.rb +95 -0
  56. data/lib/git/commands/config_option_syntax/get_color_bool.rb +96 -0
  57. data/lib/git/commands/config_option_syntax/get_regexp.rb +119 -0
  58. data/lib/git/commands/config_option_syntax/get_urlmatch.rb +111 -0
  59. data/lib/git/commands/config_option_syntax/list.rb +111 -0
  60. data/lib/git/commands/config_option_syntax/remove_section.rb +79 -0
  61. data/lib/git/commands/config_option_syntax/rename_section.rb +83 -0
  62. data/lib/git/commands/config_option_syntax/replace_all.rb +109 -0
  63. data/lib/git/commands/config_option_syntax/set.rb +119 -0
  64. data/lib/git/commands/config_option_syntax/unset.rb +92 -0
  65. data/lib/git/commands/config_option_syntax/unset_all.rb +94 -0
  66. data/lib/git/commands/config_option_syntax.rb +56 -0
  67. data/lib/git/commands/describe.rb +156 -0
  68. data/lib/git/commands/diff.rb +657 -0
  69. data/lib/git/commands/diff_files.rb +519 -0
  70. data/lib/git/commands/diff_index.rb +499 -0
  71. data/lib/git/commands/fetch.rb +354 -0
  72. data/lib/git/commands/fsck.rb +138 -0
  73. data/lib/git/commands/gc.rb +134 -0
  74. data/lib/git/commands/grep.rb +339 -0
  75. data/lib/git/commands/init.rb +101 -0
  76. data/lib/git/commands/log.rb +634 -0
  77. data/lib/git/commands/ls_files.rb +195 -0
  78. data/lib/git/commands/ls_remote.rb +161 -0
  79. data/lib/git/commands/ls_tree.rb +135 -0
  80. data/lib/git/commands/maintenance/register.rb +73 -0
  81. data/lib/git/commands/maintenance/run.rb +105 -0
  82. data/lib/git/commands/maintenance/start.rb +67 -0
  83. data/lib/git/commands/maintenance/stop.rb +56 -0
  84. data/lib/git/commands/maintenance/unregister.rb +80 -0
  85. data/lib/git/commands/maintenance.rb +29 -0
  86. data/lib/git/commands/merge/abort.rb +44 -0
  87. data/lib/git/commands/merge/continue.rb +44 -0
  88. data/lib/git/commands/merge/quit.rb +46 -0
  89. data/lib/git/commands/merge/start.rb +250 -0
  90. data/lib/git/commands/merge.rb +28 -0
  91. data/lib/git/commands/merge_base.rb +91 -0
  92. data/lib/git/commands/mv.rb +82 -0
  93. data/lib/git/commands/name_rev.rb +119 -0
  94. data/lib/git/commands/pull.rb +382 -0
  95. data/lib/git/commands/push.rb +251 -0
  96. data/lib/git/commands/read_tree.rb +154 -0
  97. data/lib/git/commands/remote/add.rb +96 -0
  98. data/lib/git/commands/remote/get_url.rb +68 -0
  99. data/lib/git/commands/remote/list.rb +56 -0
  100. data/lib/git/commands/remote/prune.rb +63 -0
  101. data/lib/git/commands/remote/remove.rb +52 -0
  102. data/lib/git/commands/remote/rename.rb +76 -0
  103. data/lib/git/commands/remote/set_branches.rb +70 -0
  104. data/lib/git/commands/remote/set_head.rb +89 -0
  105. data/lib/git/commands/remote/set_url.rb +78 -0
  106. data/lib/git/commands/remote/set_url_add.rb +70 -0
  107. data/lib/git/commands/remote/set_url_delete.rb +71 -0
  108. data/lib/git/commands/remote/show.rb +77 -0
  109. data/lib/git/commands/remote/update.rb +79 -0
  110. data/lib/git/commands/remote.rb +42 -0
  111. data/lib/git/commands/repack.rb +281 -0
  112. data/lib/git/commands/reset.rb +154 -0
  113. data/lib/git/commands/rev_parse.rb +304 -0
  114. data/lib/git/commands/revert/abort.rb +45 -0
  115. data/lib/git/commands/revert/continue.rb +62 -0
  116. data/lib/git/commands/revert/quit.rb +47 -0
  117. data/lib/git/commands/revert/skip.rb +44 -0
  118. data/lib/git/commands/revert/start.rb +158 -0
  119. data/lib/git/commands/revert.rb +29 -0
  120. data/lib/git/commands/rm.rb +113 -0
  121. data/lib/git/commands/show.rb +632 -0
  122. data/lib/git/commands/show_ref/exclude_existing.rb +119 -0
  123. data/lib/git/commands/show_ref/exists.rb +75 -0
  124. data/lib/git/commands/show_ref/list.rb +149 -0
  125. data/lib/git/commands/show_ref/verify.rb +122 -0
  126. data/lib/git/commands/show_ref.rb +42 -0
  127. data/lib/git/commands/stash/apply.rb +81 -0
  128. data/lib/git/commands/stash/branch.rb +67 -0
  129. data/lib/git/commands/stash/clear.rb +43 -0
  130. data/lib/git/commands/stash/create.rb +60 -0
  131. data/lib/git/commands/stash/drop.rb +73 -0
  132. data/lib/git/commands/stash/list.rb +43 -0
  133. data/lib/git/commands/stash/pop.rb +87 -0
  134. data/lib/git/commands/stash/push.rb +112 -0
  135. data/lib/git/commands/stash/show.rb +158 -0
  136. data/lib/git/commands/stash/store.rb +72 -0
  137. data/lib/git/commands/stash.rb +38 -0
  138. data/lib/git/commands/status.rb +174 -0
  139. data/lib/git/commands/symbolic_ref/delete.rb +72 -0
  140. data/lib/git/commands/symbolic_ref/read.rb +99 -0
  141. data/lib/git/commands/symbolic_ref/update.rb +79 -0
  142. data/lib/git/commands/symbolic_ref.rb +38 -0
  143. data/lib/git/commands/tag/create.rb +142 -0
  144. data/lib/git/commands/tag/delete.rb +57 -0
  145. data/lib/git/commands/tag/list.rb +146 -0
  146. data/lib/git/commands/tag/verify.rb +71 -0
  147. data/lib/git/commands/tag.rb +26 -0
  148. data/lib/git/commands/update_ref/batch.rb +145 -0
  149. data/lib/git/commands/update_ref/delete.rb +90 -0
  150. data/lib/git/commands/update_ref/update.rb +103 -0
  151. data/lib/git/commands/update_ref.rb +42 -0
  152. data/lib/git/commands/version.rb +60 -0
  153. data/lib/git/commands/worktree/add.rb +139 -0
  154. data/lib/git/commands/worktree/list.rb +64 -0
  155. data/lib/git/commands/worktree/lock.rb +58 -0
  156. data/lib/git/commands/worktree/management_base.rb +51 -0
  157. data/lib/git/commands/worktree/move.rb +66 -0
  158. data/lib/git/commands/worktree/prune.rb +67 -0
  159. data/lib/git/commands/worktree/remove.rb +63 -0
  160. data/lib/git/commands/worktree/repair.rb +71 -0
  161. data/lib/git/commands/worktree/unlock.rb +47 -0
  162. data/lib/git/commands/worktree.rb +43 -0
  163. data/lib/git/commands/write_tree.rb +68 -0
  164. data/lib/git/commands.rb +88 -0
  165. data/lib/git/config.rb +64 -1
  166. data/lib/git/config_entry_info.rb +106 -0
  167. data/lib/git/configuring.rb +795 -0
  168. data/lib/git/detached_head_info.rb +57 -0
  169. data/lib/git/diff.rb +295 -12
  170. data/lib/git/diff_file_numstat_info.rb +31 -0
  171. data/lib/git/diff_file_patch_info.rb +136 -0
  172. data/lib/git/diff_file_raw_info.rb +129 -0
  173. data/lib/git/diff_info.rb +162 -0
  174. data/lib/git/diff_path_status.rb +80 -19
  175. data/lib/git/diff_result.rb +34 -0
  176. data/lib/git/diff_stats.rb +66 -14
  177. data/lib/git/dirstat_info.rb +102 -0
  178. data/lib/git/encoding_utils.rb +57 -1
  179. data/lib/git/errors.rb +107 -26
  180. data/lib/git/escaped_path.rb +55 -3
  181. data/lib/git/execution_context/global.rb +31 -0
  182. data/lib/git/execution_context/repository.rb +151 -0
  183. data/lib/git/execution_context.rb +559 -0
  184. data/lib/git/factories.rb +1049 -0
  185. data/lib/git/file_ref.rb +77 -0
  186. data/lib/git/fsck_object.rb +17 -9
  187. data/lib/git/fsck_result.rb +27 -16
  188. data/lib/git/log.rb +172 -65
  189. data/lib/git/object.rb +323 -108
  190. data/lib/git/parsers/branch.rb +240 -0
  191. data/lib/git/parsers/cat_file.rb +111 -0
  192. data/lib/git/parsers/config_entry.rb +110 -0
  193. data/lib/git/parsers/diff.rb +792 -0
  194. data/lib/git/parsers/fsck.rb +144 -0
  195. data/lib/git/parsers/grep.rb +42 -0
  196. data/lib/git/parsers/ls_remote.rb +79 -0
  197. data/lib/git/parsers/ls_tree.rb +58 -0
  198. data/lib/git/parsers/remote.rb +162 -0
  199. data/lib/git/parsers/stash.rb +292 -0
  200. data/lib/git/parsers/status.rb +251 -0
  201. data/lib/git/parsers/tag.rb +341 -0
  202. data/lib/git/parsers/worktree.rb +185 -0
  203. data/lib/git/path_resolver.rb +274 -0
  204. data/lib/git/remote_info.rb +203 -0
  205. data/lib/git/repository/branching.rb +796 -0
  206. data/lib/git/repository/committing.rb +221 -0
  207. data/lib/git/repository/context_helpers.rb +454 -0
  208. data/lib/git/repository/diffing.rb +743 -0
  209. data/lib/git/repository/inspecting.rb +252 -0
  210. data/lib/git/repository/logging.rb +410 -0
  211. data/lib/git/repository/maintenance.rb +65 -0
  212. data/lib/git/repository/merging.rb +429 -0
  213. data/lib/git/repository/object_operations.rb +1334 -0
  214. data/lib/git/repository/remote_operations.rb +772 -0
  215. data/lib/git/repository/shared_private.rb +120 -0
  216. data/lib/git/repository/staging.rb +409 -0
  217. data/lib/git/repository/stashing.rb +619 -0
  218. data/lib/git/repository/status_operations.rb +196 -0
  219. data/lib/git/repository/worktree_operations.rb +252 -0
  220. data/lib/git/repository.rb +204 -1
  221. data/lib/git/stash_info.rb +102 -0
  222. data/lib/git/status_file_info.rb +258 -0
  223. data/lib/git/status_info.rb +189 -0
  224. data/lib/git/system_call_guard.rb +95 -0
  225. data/lib/git/tag_delete_failure.rb +34 -0
  226. data/lib/git/tag_delete_result.rb +66 -0
  227. data/lib/git/tag_info.rb +99 -0
  228. data/lib/git/url.rb +12 -5
  229. data/lib/git/version.rb +111 -2
  230. data/lib/git/version_constraint.rb +85 -0
  231. data/lib/git/worktree_info.rb +128 -0
  232. data/lib/git.rb +319 -332
  233. metadata +318 -74
  234. data/.commitlintrc.yml +0 -38
  235. data/.github/copilot-instructions.md +0 -2733
  236. data/.github/issue_template.md +0 -15
  237. data/.github/pull_request_template.md +0 -17
  238. data/.github/workflows/continuous_integration.yml +0 -120
  239. data/.github/workflows/enforce_conventional_commits.yml +0 -29
  240. data/.github/workflows/experimental_continuous_integration.yml +0 -59
  241. data/.github/workflows/release.yml +0 -53
  242. data/.gitignore +0 -15
  243. data/.husky/commit-msg +0 -1
  244. data/.release-please-manifest.json +0 -3
  245. data/.rubocop.yml +0 -55
  246. data/.rubocop_todo.yml +0 -12
  247. data/Gemfile +0 -5
  248. data/Rakefile +0 -18
  249. data/lib/git/args_builder.rb +0 -111
  250. data/lib/git/author.rb +0 -16
  251. data/lib/git/base.rb +0 -1140
  252. data/lib/git/branch.rb +0 -423
  253. data/lib/git/branches.rb +0 -68
  254. data/lib/git/command_line_result.rb +0 -92
  255. data/lib/git/index.rb +0 -6
  256. data/lib/git/lib.rb +0 -2333
  257. data/lib/git/path.rb +0 -38
  258. data/lib/git/remote.rb +0 -39
  259. data/lib/git/stash.rb +0 -26
  260. data/lib/git/stashes.rb +0 -56
  261. data/lib/git/status.rb +0 -159
  262. data/lib/git/working_directory.rb +0 -6
  263. data/lib/git/worktree.rb +0 -39
  264. data/lib/git/worktrees.rb +0 -47
  265. data/package.json +0 -10
  266. data/redesign/1_architecture_existing.md +0 -66
  267. data/redesign/2_architecture_redesign.md +0 -130
  268. data/redesign/3_architecture_implementation.md +0 -138
  269. data/redesign/index.md +0 -34
  270. data/release-please-config.json +0 -36
  271. data/tasks/gem_tasks.rake +0 -10
  272. data/tasks/rubocop.rake +0 -12
  273. data/tasks/test.rake +0 -13
  274. data/tasks/test_gem.rake +0 -12
  275. data/tasks/yard.rake +0 -23
data/lib/git/lib.rb DELETED
@@ -1,2333 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative 'args_builder'
4
-
5
- require 'git/command_line'
6
- require 'git/errors'
7
- require 'logger'
8
- require 'pathname'
9
- require 'pp'
10
- require 'process_executer'
11
- require 'stringio'
12
- require 'tempfile'
13
- require 'zlib'
14
-
15
- module Git
16
- # Internal git operations
17
- # @api private
18
- class Lib
19
- # The path to the Git working copy. The default is '"./.git"'.
20
- #
21
- # @return [Pathname] the path to the Git working copy.
22
- #
23
- # @see [Git working tree](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefworkingtreeaworkingtree)
24
- #
25
- attr_reader :git_work_dir
26
-
27
- # The path to the Git repository directory. The default is
28
- # `"#{git_work_dir}/.git"`.
29
- #
30
- # @return [Pathname] the Git repository directory.
31
- #
32
- # @see [Git repository](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefrepositoryarepository)
33
- #
34
- attr_reader :git_dir
35
-
36
- # The Git index file used to stage changes (using `git add`) before they
37
- # are committed.
38
- #
39
- # @return [Pathname] the Git index file
40
- #
41
- # @see [Git index file](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefindexaindex)
42
- #
43
- attr_reader :git_index_file
44
-
45
- # Create a new Git::Lib object
46
- #
47
- # @overload initialize(base, logger)
48
- #
49
- # @param base [Hash] the hash containing paths to the Git working copy,
50
- # the Git repository directory, and the Git index file.
51
- #
52
- # @option base [Pathname] :working_directory
53
- # @option base [Pathname] :repository
54
- # @option base [Pathname] :index
55
- #
56
- # @param [Logger] logger
57
- #
58
- # @overload initialize(base, logger)
59
- #
60
- # @param base [#dir, #repo, #index] an object with methods to get the Git worktree (#dir),
61
- # the Git repository directory (#repo), and the Git index file (#index).
62
- #
63
- # @param [Logger] logger
64
- #
65
- def initialize(base = nil, logger = nil)
66
- @logger = logger || Logger.new(nil)
67
- @git_ssh = :use_global_config
68
-
69
- case base
70
- when Git::Base
71
- initialize_from_base(base)
72
- when Hash
73
- initialize_from_hash(base)
74
- end
75
- end
76
-
77
- INIT_OPTION_MAP = [
78
- { keys: [:bare], flag: '--bare', type: :boolean },
79
- { keys: [:initial_branch], flag: '--initial-branch', type: :valued_equals }
80
- ].freeze
81
-
82
- # creates or reinitializes the repository
83
- #
84
- # options:
85
- # :bare
86
- # :working_directory
87
- # :initial_branch
88
- #
89
- def init(opts = {})
90
- args = build_args(opts, INIT_OPTION_MAP)
91
- command('init', *args)
92
- end
93
-
94
- CLONE_OPTION_MAP = [
95
- { keys: [:bare], flag: '--bare', type: :boolean },
96
- { keys: [:recursive], flag: '--recursive', type: :boolean },
97
- { keys: [:mirror], flag: '--mirror', type: :boolean },
98
- { keys: [:branch], flag: '--branch', type: :valued_space },
99
- { keys: [:filter], flag: '--filter', type: :valued_space },
100
- { keys: %i[remote origin], flag: '--origin', type: :valued_space },
101
- { keys: [:config], flag: '--config', type: :repeatable_valued_space },
102
- {
103
- keys: [:single_branch],
104
- type: :custom,
105
- validator: ->(value) { [nil, true, false].include?(value) },
106
- builder: lambda do |value|
107
- case value
108
- when true
109
- ['--single-branch']
110
- when false
111
- ['--no-single-branch']
112
- else
113
- []
114
- end
115
- end
116
- },
117
- {
118
- keys: [:depth],
119
- type: :custom,
120
- builder: ->(value) { ['--depth', value.to_i] if value }
121
- }
122
- ].freeze
123
-
124
- # Clones a repository into a newly created directory
125
- #
126
- # @param [String] repository_url the URL of the repository to clone
127
- #
128
- # @param [String, nil] directory the directory to clone into
129
- #
130
- # If nil, the repository is cloned into a directory with the same name as
131
- # the repository.
132
- #
133
- # @param [Hash] opts the options for this command
134
- #
135
- # @option opts [Boolean] :bare (false) if true, clone as a bare repository
136
- #
137
- # @option opts [String] :branch the branch to checkout
138
- #
139
- # @option opts [String, Array] :config one or more configuration options to set
140
- #
141
- # @option opts [Integer] :depth the number of commits back to pull
142
- #
143
- # @option opts [String] :filter specify partial clone
144
- #
145
- # @option opts [String] :mirror set up a mirror of the source repository
146
- #
147
- # @option opts [String] :origin the name of the remote
148
- #
149
- # @option opts [String] :path an optional prefix for the directory parameter
150
- #
151
- # @option opts [String] :remote the name of the remote
152
- #
153
- # @option opts [Boolean] :recursive after the clone is created, initialize all
154
- # within, using their default settings
155
- #
156
- # @option opts [Numeric, nil] :timeout the number of seconds to wait for the
157
- # command to complete
158
- #
159
- # See {Git::Lib#command} for more information about :timeout
160
- #
161
- # @return [Hash] the options to pass to {Git::Base.new}
162
- #
163
- # @todo make this work with SSH password or auth_key
164
- #
165
- def clone(repository_url, directory, opts = {})
166
- @path = opts[:path] || '.'
167
- clone_dir = opts[:path] ? File.join(@path, directory) : directory
168
-
169
- args = build_args(opts, CLONE_OPTION_MAP)
170
- args.push('--', repository_url, clone_dir)
171
-
172
- command('clone', *args, timeout: opts[:timeout])
173
-
174
- return_base_opts_from_clone(clone_dir, opts)
175
- end
176
-
177
- # Returns the name of the default branch of the given repository
178
- #
179
- # @param repository [URI, Pathname, String] The (possibly remote) repository to clone from
180
- #
181
- # @return [String] the name of the default branch
182
- #
183
- def repository_default_branch(repository)
184
- output = command('ls-remote', '--symref', '--', repository, 'HEAD')
185
-
186
- match_data = output.match(%r{^ref: refs/remotes/origin/(?<default_branch>[^\t]+)\trefs/remotes/origin/HEAD$})
187
- return match_data[:default_branch] if match_data
188
-
189
- match_data = output.match(%r{^ref: refs/heads/(?<default_branch>[^\t]+)\tHEAD$})
190
- return match_data[:default_branch] if match_data
191
-
192
- raise Git::UnexpectedResultError, 'Unable to determine the default branch'
193
- end
194
-
195
- ## READ COMMANDS ##
196
-
197
- # The map defining how to translate user options to git command arguments.
198
- DESCRIBE_OPTION_MAP = [
199
- { keys: [:all], flag: '--all', type: :boolean },
200
- { keys: [:tags], flag: '--tags', type: :boolean },
201
- { keys: [:contains], flag: '--contains', type: :boolean },
202
- { keys: [:debug], flag: '--debug', type: :boolean },
203
- { keys: [:long], flag: '--long', type: :boolean },
204
- { keys: [:always], flag: '--always', type: :boolean },
205
- { keys: %i[exact_match exact-match], flag: '--exact-match', type: :boolean },
206
- { keys: [:abbrev], flag: '--abbrev', type: :valued_equals },
207
- { keys: [:candidates], flag: '--candidates', type: :valued_equals },
208
- { keys: [:match], flag: '--match', type: :valued_equals },
209
- {
210
- keys: [:dirty],
211
- type: :custom,
212
- builder: lambda do |value|
213
- return '--dirty' if value == true
214
-
215
- "--dirty=#{value}" if value.is_a?(String)
216
- end
217
- }
218
- ].freeze
219
-
220
- # Finds most recent tag that is reachable from a commit
221
- #
222
- # @see https://git-scm.com/docs/git-describe git-describe
223
- #
224
- # @param commit_ish [String, nil] target commit sha or object name
225
- #
226
- # @param opts [Hash] the given options
227
- #
228
- # @option opts :all [Boolean]
229
- # @option opts :tags [Boolean]
230
- # @option opts :contains [Boolean]
231
- # @option opts :debug [Boolean]
232
- # @option opts :long [Boolean]
233
- # @option opts :always [Boolean]
234
- # @option opts :exact_match [Boolean]
235
- # @option opts :dirty [true, String]
236
- # @option opts :abbrev [String]
237
- # @option opts :candidates [String]
238
- # @option opts :match [String]
239
- #
240
- # @return [String] the tag name
241
- #
242
- # @raise [ArgumentError] if the commit_ish is a string starting with a hyphen
243
- #
244
- def describe(commit_ish = nil, opts = {})
245
- assert_args_are_not_options('commit-ish object', commit_ish)
246
-
247
- args = build_args(opts, DESCRIBE_OPTION_MAP)
248
- args << commit_ish if commit_ish
249
-
250
- command('describe', *args)
251
- end
252
-
253
- # Return the commits that are within the given revision range
254
- #
255
- # @see https://git-scm.com/docs/git-log git-log
256
- #
257
- # @param opts [Hash] the given options
258
- #
259
- # @option opts :count [Integer] the maximum number of commits to return (maps to max-count)
260
- # @option opts :all [Boolean]
261
- # @option opts :cherry [Boolean]
262
- # @option opts :since [String]
263
- # @option opts :until [String]
264
- # @option opts :grep [String]
265
- # @option opts :author [String]
266
- # @option opts :between [Array<String>] an array of two commit-ish strings to specify a revision range
267
- #
268
- # Only :between or :object options can be used, not both.
269
- #
270
- # @option opts :object [String] the revision range for the git log command
271
- #
272
- # Only :between or :object options can be used, not both.
273
- #
274
- # @option opts :path_limiter [String, Pathname, Array<String, Pathname>] only
275
- # include commits that impact files from the specified paths
276
- #
277
- # @return [Array<String>] the log output
278
- #
279
- # @raise [ArgumentError] if the resulting revision range is a string starting with a hyphen
280
- #
281
- def log_commits(opts = {})
282
- assert_args_are_not_options('between', opts[:between]&.first)
283
- assert_args_are_not_options('object', opts[:object])
284
-
285
- arr_opts = log_common_options(opts)
286
-
287
- arr_opts << '--pretty=oneline'
288
-
289
- arr_opts += log_path_options(opts)
290
-
291
- log_or_empty_on_unborn { command_lines('log', *arr_opts).map { |l| l.split.first } }
292
- end
293
-
294
- FULL_LOG_EXTRA_OPTIONS_MAP = [
295
- { type: :static, flag: '--pretty=raw' },
296
- { keys: [:skip], flag: '--skip', type: :valued_equals },
297
- { keys: [:merges], flag: '--merges', type: :boolean }
298
- ].freeze
299
-
300
- # Return the commits that are within the given revision range
301
- #
302
- # @see https://git-scm.com/docs/git-log git-log
303
- #
304
- # @param opts [Hash] the given options
305
- #
306
- # @option opts :count [Integer] the maximum number of commits to return (maps to
307
- # max-count)
308
- #
309
- # @option opts :all [Boolean]
310
- #
311
- # @option opts :cherry [Boolean]
312
- #
313
- # @option opts :since [String]
314
- #
315
- # @option opts :until [String]
316
- #
317
- # @option opts :grep [String]
318
- #
319
- # @option opts :author [String]
320
- #
321
- # @option opts :between [Array<String>] an array of two commit-ish strings to
322
- # specify a revision range
323
- #
324
- # Only :between or :object options can be used, not both.
325
- #
326
- # @option opts :object [String] the revision range for the git log command
327
- #
328
- # Only :between or :object options can be used, not both.
329
- #
330
- # @option opts :path_limiter [String, Pathname, Array<String, Pathname>] only include commits that
331
- # impact files from the specified paths
332
- #
333
- # @option opts :skip [Integer]
334
- #
335
- # @return [Array<Hash>] the log output parsed into an array of hashs for each commit
336
- #
337
- # Each hash contains the following keys:
338
- #
339
- # * 'sha' [String] the commit sha
340
- # * 'author' [String] the author of the commit
341
- # * 'message' [String] the commit message
342
- # * 'parent' [Array<String>] the commit shas of the parent commits
343
- # * 'tree' [String] the tree sha
344
- # * 'author' [String] the author of the commit and timestamp of when the
345
- # changes were created
346
- # * 'committer' [String] the committer of the commit and timestamp of when the
347
- # commit was applied
348
- # * 'merges' [Boolean] if truthy, only include merge commits (aka commits with
349
- # 2 or more parents)
350
- #
351
- # @raise [ArgumentError] if the revision range (specified with :between or
352
- # :object) is a string starting with a hyphen
353
- #
354
- def full_log_commits(opts = {})
355
- assert_args_are_not_options('between', opts[:between]&.first)
356
- assert_args_are_not_options('object', opts[:object])
357
-
358
- args = log_common_options(opts)
359
- args += build_args(opts, FULL_LOG_EXTRA_OPTIONS_MAP)
360
- args += log_path_options(opts)
361
-
362
- log_or_empty_on_unborn do
363
- full_log = command_lines('log', *args)
364
- process_commit_log_data(full_log)
365
- end
366
- end
367
-
368
- # Verify and resolve a Git revision to its full SHA
369
- #
370
- # @see https://git-scm.com/docs/git-rev-parse git-rev-parse
371
- # @see https://git-scm.com/docs/git-rev-parse#_specifying_revisions Valid ways to specify revisions
372
- # @see https://git-scm.com/docs/git-rev-parse#Documentation/git-rev-parse.txt-emltrefnamegtemegemmasterememheadsmasterememrefsheadsmasterem
373
- # Ref disambiguation rules
374
- #
375
- # @example
376
- # lib.rev_parse('HEAD') # => '9b9b31e704c0b85ffdd8d2af2ded85170a5af87d'
377
- # lib.rev_parse('9b9b31e') # => '9b9b31e704c0b85ffdd8d2af2ded85170a5af87d'
378
- #
379
- # @param revision [String] the revision to resolve
380
- #
381
- # @return [String] the full commit hash
382
- #
383
- # @raise [Git::FailedError] if the revision cannot be resolved
384
- # @raise [ArgumentError] if the revision is a string starting with a hyphen
385
- #
386
- def rev_parse(revision)
387
- assert_args_are_not_options('rev', revision)
388
-
389
- command('rev-parse', '--revs-only', '--end-of-options', revision, '--')
390
- end
391
-
392
- # For backwards compatibility with the old method name
393
- alias revparse rev_parse
394
-
395
- # Find the first symbolic name for given commit_ish
396
- #
397
- # @param commit_ish [String] the commit_ish to find the symbolic name of
398
- #
399
- # @return [String, nil] the first symbolic name or nil if the commit_ish isn't found
400
- #
401
- # @raise [ArgumentError] if the commit_ish is a string starting with a hyphen
402
- #
403
- def name_rev(commit_ish)
404
- assert_args_are_not_options('commit_ish', commit_ish)
405
-
406
- command('name-rev', commit_ish).split[1]
407
- end
408
-
409
- alias namerev name_rev
410
-
411
- # Output the contents or other properties of one or more objects.
412
- #
413
- # @see https://git-scm.com/docs/git-cat-file git-cat-file
414
- #
415
- # @example Get the contents of a file without a block
416
- # lib.cat_file_contents('README.md') # => "This is a README file\n"
417
- #
418
- # @example Get the contents of a file with a block
419
- # lib.cat_file_contents('README.md') { |f| f.read } # => "This is a README file\n"
420
- #
421
- # @param object [String] the object whose contents to return
422
- #
423
- # @return [String] the object contents
424
- #
425
- # @raise [ArgumentError] if object is a string starting with a hyphen
426
- #
427
- def cat_file_contents(object)
428
- assert_args_are_not_options('object', object)
429
-
430
- if block_given?
431
- Tempfile.create do |file|
432
- # If a block is given, write the output from the process to a temporary
433
- # file and then yield the file to the block
434
- #
435
- command('cat-file', '-p', object, out: file, err: file)
436
- file.rewind
437
- yield file
438
- end
439
- else
440
- # If a block is not given, return the file contents as a string
441
- command('cat-file', '-p', object)
442
- end
443
- end
444
-
445
- alias object_contents cat_file_contents
446
-
447
- # Get the type for the given object
448
- #
449
- # @see https://git-scm.com/docs/git-cat-file git-cat-file
450
- #
451
- # @param object [String] the object to get the type
452
- #
453
- # @return [String] the object type
454
- #
455
- # @raise [ArgumentError] if object is a string starting with a hyphen
456
- #
457
- def cat_file_type(object)
458
- assert_args_are_not_options('object', object)
459
-
460
- command('cat-file', '-t', object)
461
- end
462
-
463
- alias object_type cat_file_type
464
-
465
- # Get the size for the given object
466
- #
467
- # @see https://git-scm.com/docs/git-cat-file git-cat-file
468
- #
469
- # @param object [String] the object to get the type
470
- #
471
- # @return [String] the object type
472
- #
473
- # @raise [ArgumentError] if object is a string starting with a hyphen
474
- #
475
- def cat_file_size(object)
476
- assert_args_are_not_options('object', object)
477
-
478
- command('cat-file', '-s', object).to_i
479
- end
480
-
481
- alias object_size cat_file_size
482
-
483
- # Return a hash of commit data
484
- #
485
- # @see https://git-scm.com/docs/git-cat-file git-cat-file
486
- #
487
- # @param object [String] the object to get the type
488
- #
489
- # @return [Hash] commit data
490
- #
491
- # The returned commit data has the following keys:
492
- # * tree [String]
493
- # * parent [Array<String>]
494
- # * author [String] the author name, email, and commit timestamp
495
- # * committer [String] the committer name, email, and merge timestamp
496
- # * message [String] the commit message
497
- # * gpgsig [String] the public signing key of the commit (if signed)
498
- #
499
- # @raise [ArgumentError] if object is a string starting with a hyphen
500
- #
501
- def cat_file_commit(object)
502
- assert_args_are_not_options('object', object)
503
-
504
- cdata = command_lines('cat-file', 'commit', object)
505
- process_commit_data(cdata, object)
506
- end
507
-
508
- alias commit_data cat_file_commit
509
-
510
- def process_commit_data(data, sha)
511
- # process_commit_headers consumes the header lines from the `data` array,
512
- # leaving only the message lines behind.
513
- headers = process_commit_headers(data)
514
- message = "#{data.join("\n")}\n"
515
-
516
- { 'sha' => sha, 'message' => message }.merge(headers)
517
- end
518
-
519
- CAT_FILE_HEADER_LINE = /\A(?<key>\w+) (?<value>.*)\z/
520
-
521
- def each_cat_file_header(data)
522
- while (match = CAT_FILE_HEADER_LINE.match(data.shift))
523
- key = match[:key]
524
- value_lines = [match[:value]]
525
-
526
- value_lines << data.shift.lstrip while data.first.start_with?(' ')
527
-
528
- yield key, value_lines.join("\n")
529
- end
530
- end
531
-
532
- # Return a hash of annotated tag data
533
- #
534
- # Does not work with lightweight tags. List all annotated tags in your repository
535
- # with the following command:
536
- #
537
- # ```sh
538
- # git for-each-ref --format='%(refname:strip=2)' refs/tags | \
539
- # while read tag; do git cat-file tag $tag >/dev/null 2>&1 && echo $tag; done
540
- # ```
541
- #
542
- # @see https://git-scm.com/docs/git-cat-file git-cat-file
543
- #
544
- # @param object [String] the tag to retrieve
545
- #
546
- # @return [Hash] tag data
547
- #
548
- # Example tag data returned:
549
- # ```ruby
550
- # {
551
- # "name" => "annotated_tag",
552
- # "object" => "46abbf07e3c564c723c7c039a43ab3a39e5d02dd",
553
- # "type" => "commit",
554
- # "tag" => "annotated_tag",
555
- # "tagger" => "Scott Chacon <schacon@gmail.com> 1724799270 -0700",
556
- # "message" => "Creating an annotated tag\n"
557
- # }
558
- # ```
559
- #
560
- # The returned commit data has the following keys:
561
- # * object [String] the sha of the tag object
562
- # * type [String]
563
- # * tag [String] tag name
564
- # * tagger [String] the name and email of the user who created the tag
565
- # and the timestamp of when the tag was created
566
- # * message [String] the tag message
567
- #
568
- # @raise [ArgumentError] if object is a string starting with a hyphen
569
- #
570
- def cat_file_tag(object)
571
- assert_args_are_not_options('object', object)
572
-
573
- tdata = command_lines('cat-file', 'tag', object)
574
- process_tag_data(tdata, object)
575
- end
576
-
577
- alias tag_data cat_file_tag
578
-
579
- def process_tag_data(data, name)
580
- hsh = { 'name' => name }
581
-
582
- each_cat_file_header(data) do |key, value|
583
- hsh[key] = value
584
- end
585
-
586
- hsh['message'] = "#{data.join("\n")}\n"
587
-
588
- hsh
589
- end
590
-
591
- def process_commit_log_data(data)
592
- RawLogParser.new(data).parse
593
- end
594
-
595
- # A private parser class to process the output of `git log --pretty=raw`
596
- # @api private
597
- class RawLogParser
598
- def initialize(lines)
599
- @lines = lines
600
- @commits = []
601
- @current_commit = nil
602
- @in_message = false
603
- end
604
-
605
- def parse
606
- @lines.each { |line| process_line(line.chomp) }
607
- finalize_commit
608
- @commits
609
- end
610
-
611
- private
612
-
613
- def process_line(line)
614
- if line.empty?
615
- @in_message = !@in_message
616
- return
617
- end
618
-
619
- @in_message = false if @in_message && !line.start_with?(' ')
620
-
621
- @in_message ? process_message_line(line) : process_metadata_line(line)
622
- end
623
-
624
- def process_message_line(line)
625
- @current_commit['message'] << "#{line[4..]}\n"
626
- end
627
-
628
- def process_metadata_line(line)
629
- key, *value = line.split
630
- value = value.join(' ')
631
-
632
- case key
633
- when 'commit'
634
- start_new_commit(value)
635
- when 'parent'
636
- @current_commit['parent'] << value
637
- else
638
- @current_commit[key] = value
639
- end
640
- end
641
-
642
- def start_new_commit(sha)
643
- finalize_commit
644
- @current_commit = { 'sha' => sha, 'message' => +'', 'parent' => [] }
645
- end
646
-
647
- def finalize_commit
648
- @commits << @current_commit if @current_commit
649
- end
650
- end
651
- private_constant :RawLogParser
652
-
653
- LS_TREE_OPTION_MAP = [
654
- { keys: [:recursive], flag: '-r', type: :boolean }
655
- ].freeze
656
-
657
- def ls_tree(sha, opts = {})
658
- data = { 'blob' => {}, 'tree' => {}, 'commit' => {} }
659
- args = build_args(opts, LS_TREE_OPTION_MAP)
660
-
661
- args.unshift(sha)
662
- args << opts[:path] if opts[:path]
663
-
664
- command_lines('ls-tree', *args).each do |line|
665
- (info, filenm) = split_status_line(line)
666
- (mode, type, sha) = info.split
667
- data[type][filenm] = { mode: mode, sha: sha }
668
- end
669
-
670
- data
671
- end
672
-
673
- def mv(file1, file2)
674
- command_lines('mv', '--', file1, file2)
675
- end
676
-
677
- def full_tree(sha)
678
- command_lines('ls-tree', '-r', sha)
679
- end
680
-
681
- def tree_depth(sha)
682
- full_tree(sha).size
683
- end
684
-
685
- def change_head_branch(branch_name)
686
- command('symbolic-ref', 'HEAD', "refs/heads/#{branch_name}")
687
- end
688
-
689
- BRANCH_LINE_REGEXP = /
690
- ^
691
- # Prefix indicates if this branch is checked out. The prefix is one of:
692
- (?:
693
- (?<current>\*[[:blank:]]) | # Current branch (checked out in the current worktree)
694
- (?<worktree>\+[[:blank:]]) | # Branch checked out in a different worktree
695
- [[:blank:]]{2} # Branch not checked out
696
- )
697
-
698
- # The branch's full refname
699
- (?:
700
- (?<not_a_branch>\(not[[:blank:]]a[[:blank:]]branch\)) |
701
- (?:\(HEAD[[:blank:]]detached[[:blank:]]at[[:blank:]](?<detached_ref>[^)]+)\)) |
702
- (?<refname>[^[[:blank:]]]+)
703
- )
704
-
705
- # Optional symref
706
- # If this ref is a symbolic reference, this is the ref referenced
707
- (?:
708
- [[:blank:]]->[[:blank:]](?<symref>.*)
709
- )?
710
- $
711
- /x
712
-
713
- def branches_all
714
- lines = command_lines('branch', '-a')
715
- lines.each_with_index.filter_map do |line, index|
716
- parse_branch_line(line, index, lines)
717
- end
718
- end
719
-
720
- def worktrees_all
721
- arr = []
722
- directory = ''
723
- # Output example for `worktree list --porcelain`:
724
- # worktree /code/public/ruby-git
725
- # HEAD 4bef5abbba073c77b4d0ccc1ffcd0ed7d48be5d4
726
- # branch refs/heads/master
727
- #
728
- # worktree /tmp/worktree-1
729
- # HEAD b8c63206f8d10f57892060375a86ae911fad356e
730
- # detached
731
- #
732
- command_lines('worktree', 'list', '--porcelain').each do |w|
733
- s = w.split
734
- directory = s[1] if s[0] == 'worktree'
735
- arr << [directory, s[1]] if s[0] == 'HEAD'
736
- end
737
- arr
738
- end
739
-
740
- def worktree_add(dir, commitish = nil)
741
- return worktree_command('worktree', 'add', dir, commitish) unless commitish.nil?
742
-
743
- worktree_command('worktree', 'add', dir)
744
- end
745
-
746
- def worktree_remove(dir)
747
- worktree_command('worktree', 'remove', dir)
748
- end
749
-
750
- def worktree_prune
751
- worktree_command('worktree', 'prune')
752
- end
753
-
754
- def list_files(ref_dir)
755
- dir = File.join(@git_dir, 'refs', ref_dir)
756
- Dir.glob('**/*', base: dir).select { |f| File.file?(File.join(dir, f)) }
757
- end
758
-
759
- # The state and name of branch pointed to by `HEAD`
760
- #
761
- # HEAD can be in the following states:
762
- #
763
- # **:active**: `HEAD` points to a branch reference which in turn points to a
764
- # commit representing the tip of that branch. This is the typical state when
765
- # working on a branch.
766
- #
767
- # **:unborn**: `HEAD` points to a branch reference that does not yet exist
768
- # because no commits have been made on that branch. This state occurs in two
769
- # scenarios:
770
- #
771
- # * When a repository is newly initialized, and no commits have been made on the
772
- # initial branch.
773
- # * When a new branch is created using `git checkout --orphan <branch>`, starting
774
- # a new branch with no history.
775
- #
776
- # **:detached**: `HEAD` points directly to a specific commit (identified by its
777
- # SHA) rather than a branch reference. This state occurs when you check out a
778
- # commit, a tag, or any state that is not directly associated with a branch. The
779
- # branch name in this case is `HEAD`.
780
- #
781
- HeadState = Struct.new(:state, :name)
782
-
783
- # The current branch state which is the state of `HEAD`
784
- #
785
- # @return [HeadState] the state and name of the current branch
786
- #
787
- def current_branch_state
788
- branch_name = command('branch', '--show-current')
789
- return HeadState.new(:detached, 'HEAD') if branch_name.empty?
790
-
791
- state = get_branch_state(branch_name)
792
- HeadState.new(state, branch_name)
793
- end
794
-
795
- def branch_current
796
- branch_name = command('branch', '--show-current')
797
- branch_name.empty? ? 'HEAD' : branch_name
798
- end
799
-
800
- def branch_contains(commit, branch_name = '')
801
- command('branch', branch_name, '--contains', commit)
802
- end
803
-
804
- GREP_OPTION_MAP = [
805
- { keys: [:ignore_case], flag: '-i', type: :boolean },
806
- { keys: [:invert_match], flag: '-v', type: :boolean },
807
- { keys: [:extended_regexp], flag: '-E', type: :boolean },
808
- # For validation only, as these are handled manually
809
- { keys: [:object], type: :validate_only },
810
- { keys: [:path_limiter], type: :validate_only }
811
- ].freeze
812
-
813
- # returns hash
814
- # [tree-ish] = [[line_no, match], [line_no, match2]]
815
- # [tree-ish] = [[line_no, match], [line_no, match2]]
816
- def grep(string, opts = {})
817
- opts[:object] ||= 'HEAD'
818
- ArgsBuilder.validate!(opts, GREP_OPTION_MAP)
819
-
820
- boolean_flags = build_args(opts, GREP_OPTION_MAP)
821
- args = ['-n', *boolean_flags, '-e', string, opts[:object]]
822
-
823
- if (limiter = opts[:path_limiter])
824
- args.push('--', *Array(limiter))
825
- end
826
-
827
- lines = execute_grep_command(args)
828
- parse_grep_output(lines)
829
- end
830
-
831
- # Validate that the given arguments cannot be mistaken for a command-line option
832
- #
833
- # @param arg_name [String] the name of the arguments to mention in the error message
834
- # @param args [Array<String, nil>] the arguments to validate
835
- #
836
- # @raise [ArgumentError] if any of the parameters are a string starting with a hyphen
837
- # @return [void]
838
- #
839
- def assert_args_are_not_options(arg_name, *args)
840
- invalid_args = args.select { |arg| arg&.start_with?('-') }
841
- return unless invalid_args.any?
842
-
843
- raise ArgumentError, "Invalid #{arg_name}: '#{invalid_args.join("', '")}'"
844
- end
845
-
846
- # Normalizes path specifications for Git commands
847
- #
848
- # Converts a single path or array of paths into a consistent array format
849
- # suitable for appending to Git command arguments after '--'. Empty strings
850
- # are filtered out after conversion.
851
- #
852
- # @param pathspecs [String, Pathname, Array<String, Pathname>, nil] path(s) to normalize
853
- # @param arg_name [String] name of the argument for error messages
854
- # @return [Array<String>, nil] normalized array of path strings, or nil if empty/nil input
855
- # @raise [ArgumentError] if any path is not a String or Pathname
856
- #
857
- def normalize_pathspecs(pathspecs, arg_name)
858
- return nil unless pathspecs
859
-
860
- normalized = Array(pathspecs)
861
- validate_pathspec_types(normalized, arg_name)
862
-
863
- normalized = normalized.map(&:to_s).reject(&:empty?)
864
- return nil if normalized.empty?
865
-
866
- normalized
867
- end
868
-
869
- # Validates that all pathspecs are String or Pathname objects
870
- #
871
- # @param pathspecs [Array] the pathspecs to validate
872
- # @param arg_name [String] name of the argument for error messages
873
- # @raise [ArgumentError] if any path is not a String or Pathname
874
- #
875
- def validate_pathspec_types(pathspecs, arg_name)
876
- return if pathspecs.all? { |path| path.is_a?(String) || path.is_a?(Pathname) }
877
-
878
- raise ArgumentError, "Invalid #{arg_name}: must be a String, Pathname, or Array of Strings/Pathnames"
879
- end
880
-
881
- # Handle deprecated :path option in favor of :path_limiter
882
- def handle_deprecated_path_option(opts)
883
- if opts.key?(:path_limiter)
884
- opts[:path_limiter]
885
- elsif opts.key?(:path)
886
- Git::Deprecation.warn(
887
- 'Git::Lib#diff_path_status :path option is deprecated. Use :path_limiter instead.'
888
- )
889
- opts[:path]
890
- end
891
- end
892
-
893
- DIFF_FULL_OPTION_MAP = [
894
- { type: :static, flag: '-p' },
895
- { keys: [:path_limiter], type: :validate_only }
896
- ].freeze
897
-
898
- def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
899
- assert_args_are_not_options('commit or commit range', obj1, obj2)
900
- ArgsBuilder.validate!(opts, DIFF_FULL_OPTION_MAP)
901
-
902
- args = build_args(opts, DIFF_FULL_OPTION_MAP)
903
- args.push(obj1, obj2).compact!
904
-
905
- if (pathspecs = normalize_pathspecs(opts[:path_limiter], 'path limiter'))
906
- args.push('--', *pathspecs)
907
- end
908
-
909
- command('diff', *args)
910
- end
911
-
912
- DIFF_STATS_OPTION_MAP = [
913
- { type: :static, flag: '--numstat' },
914
- { keys: [:path_limiter], type: :validate_only }
915
- ].freeze
916
-
917
- def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
918
- assert_args_are_not_options('commit or commit range', obj1, obj2)
919
- ArgsBuilder.validate!(opts, DIFF_STATS_OPTION_MAP)
920
-
921
- args = build_args(opts, DIFF_STATS_OPTION_MAP)
922
- args.push(obj1, obj2).compact!
923
-
924
- if (pathspecs = normalize_pathspecs(opts[:path_limiter], 'path limiter'))
925
- args.push('--', *pathspecs)
926
- end
927
-
928
- output_lines = command_lines('diff', *args)
929
- parse_diff_stats_output(output_lines)
930
- end
931
-
932
- DIFF_PATH_STATUS_OPTION_MAP = [
933
- { type: :static, flag: '--name-status' },
934
- { keys: [:path_limiter], type: :validate_only },
935
- { keys: [:path], type: :validate_only }
936
- ].freeze
937
-
938
- def diff_path_status(reference1 = nil, reference2 = nil, opts = {})
939
- assert_args_are_not_options('commit or commit range', reference1, reference2)
940
- ArgsBuilder.validate!(opts, DIFF_PATH_STATUS_OPTION_MAP)
941
-
942
- args = build_args(opts, DIFF_PATH_STATUS_OPTION_MAP)
943
- args.push(reference1, reference2).compact!
944
-
945
- path_limiter = handle_deprecated_path_option(opts)
946
- if (pathspecs = normalize_pathspecs(path_limiter, 'path limiter'))
947
- args.push('--', *pathspecs)
948
- end
949
-
950
- parse_diff_path_status(args)
951
- end
952
-
953
- # compares the index and the working directory
954
- def diff_files
955
- diff_as_hash('diff-files')
956
- end
957
-
958
- # compares the index and the repository
959
- def diff_index(treeish)
960
- diff_as_hash('diff-index', treeish)
961
- end
962
-
963
- # List all files that are in the index
964
- #
965
- # @param location [String] the location to list the files from
966
- #
967
- # @return [Hash<String, Hash>] a hash of files in the index
968
- # * key: file [String] the file path
969
- # * value: file_info [Hash] the file information containing the following keys:
970
- # * :path [String] the file path
971
- # * :mode_index [String] the file mode
972
- # * :sha_index [String] the file sha
973
- # * :stage [String] the file stage
974
- #
975
- def ls_files(location = nil)
976
- location ||= '.'
977
- {}.tap do |files|
978
- command_lines('ls-files', '--stage', location).each do |line|
979
- (info, file) = split_status_line(line)
980
- (mode, sha, stage) = info.split
981
- files[file] = {
982
- path: file, mode_index: mode, sha_index: sha, stage: stage
983
- }
984
- end
985
- end
986
- end
987
-
988
- # Unescape a path if it is quoted
989
- #
990
- # Git commands that output paths (e.g. ls-files, diff), will escape unusual
991
- # characters.
992
- #
993
- # @example
994
- # lib.unescape_if_quoted('"quoted_file_\\342\\230\\240"') # => 'quoted_file_☠'
995
- # lib.unescape_if_quoted('unquoted_file') # => 'unquoted_file'
996
- #
997
- # @param path [String] the path to unescape if quoted
998
- #
999
- # @return [String] the unescaped path if quoted otherwise the original path
1000
- #
1001
- # @api private
1002
- #
1003
- def unescape_quoted_path(path)
1004
- if path.start_with?('"') && path.end_with?('"')
1005
- Git::EscapedPath.new(path[1..-2]).unescape
1006
- else
1007
- path
1008
- end
1009
- end
1010
-
1011
- LS_REMOTE_OPTION_MAP = [
1012
- { keys: [:refs], flag: '--refs', type: :boolean }
1013
- ].freeze
1014
-
1015
- def ls_remote(location = nil, opts = {})
1016
- ArgsBuilder.validate!(opts, LS_REMOTE_OPTION_MAP)
1017
-
1018
- flags = build_args(opts, LS_REMOTE_OPTION_MAP)
1019
- positional_arg = location || '.'
1020
-
1021
- output_lines = command_lines('ls-remote', *flags, positional_arg)
1022
- parse_ls_remote_output(output_lines)
1023
- end
1024
-
1025
- def ignored_files
1026
- command_lines('ls-files', '--others', '-i', '--exclude-standard').map { |f| unescape_quoted_path(f) }
1027
- end
1028
-
1029
- def untracked_files
1030
- command_lines('ls-files', '--others', '--exclude-standard', chdir: @git_work_dir).map do |f|
1031
- unescape_quoted_path(f)
1032
- end
1033
- end
1034
-
1035
- def config_remote(name)
1036
- hsh = {}
1037
- config_list.each do |key, value|
1038
- hsh[key.gsub("remote.#{name}.", '')] = value if /remote.#{name}/.match(key)
1039
- end
1040
- hsh
1041
- end
1042
-
1043
- def config_get(name)
1044
- command('config', '--get', name, chdir: @git_dir)
1045
- end
1046
-
1047
- def global_config_get(name)
1048
- command('config', '--global', '--get', name)
1049
- end
1050
-
1051
- def config_list
1052
- parse_config_list command_lines('config', '--list', chdir: @git_dir)
1053
- end
1054
-
1055
- def global_config_list
1056
- parse_config_list command_lines('config', '--global', '--list')
1057
- end
1058
-
1059
- def parse_config_list(lines)
1060
- hsh = {}
1061
- lines.each do |line|
1062
- (key, *values) = line.split('=')
1063
- hsh[key] = values.join('=')
1064
- end
1065
- hsh
1066
- end
1067
-
1068
- def parse_config(file)
1069
- parse_config_list command_lines('config', '--list', '--file', file)
1070
- end
1071
-
1072
- # Shows objects
1073
- #
1074
- # @param [String|NilClass] objectish the target object reference (nil == HEAD)
1075
- # @param [String|NilClass] path the path of the file to be shown
1076
- # @return [String] the object information
1077
- def show(objectish = nil, path = nil)
1078
- arr_opts = []
1079
-
1080
- arr_opts << (path ? "#{objectish}:#{path}" : objectish)
1081
-
1082
- command('show', *arr_opts.compact, chomp: false)
1083
- end
1084
-
1085
- ## WRITE COMMANDS ##
1086
-
1087
- CONFIG_SET_OPTION_MAP = [
1088
- { keys: [:file], flag: '--file', type: :valued_space }
1089
- ].freeze
1090
-
1091
- def config_set(name, value, options = {})
1092
- ArgsBuilder.validate!(options, CONFIG_SET_OPTION_MAP)
1093
- flags = build_args(options, CONFIG_SET_OPTION_MAP)
1094
- command('config', *flags, name, value)
1095
- end
1096
-
1097
- def global_config_set(name, value)
1098
- command('config', '--global', name, value)
1099
- end
1100
-
1101
- ADD_OPTION_MAP = [
1102
- { keys: [:all], flag: '--all', type: :boolean },
1103
- { keys: [:force], flag: '--force', type: :boolean }
1104
- ].freeze
1105
-
1106
- # Update the index from the current worktree to prepare the for the next commit
1107
- #
1108
- # @example
1109
- # lib.add('path/to/file')
1110
- # lib.add(['path/to/file1','path/to/file2'])
1111
- # lib.add(:all => true)
1112
- #
1113
- # @param [String, Array<String>] paths files to be added to the repository (relative to the worktree root)
1114
- # @param [Hash] options
1115
- #
1116
- # @option options [Boolean] :all Add, modify, and remove index entries to match the worktree
1117
- # @option options [Boolean] :force Allow adding otherwise ignored files
1118
- #
1119
- def add(paths = '.', options = {})
1120
- args = build_args(options, ADD_OPTION_MAP)
1121
-
1122
- args << '--'
1123
- args.concat(Array(paths))
1124
-
1125
- command('add', *args)
1126
- end
1127
-
1128
- RM_OPTION_MAP = [
1129
- { type: :static, flag: '-f' },
1130
- { keys: [:recursive], flag: '-r', type: :boolean },
1131
- { keys: [:cached], flag: '--cached', type: :boolean }
1132
- ].freeze
1133
-
1134
- def rm(path = '.', opts = {})
1135
- args = build_args(opts, RM_OPTION_MAP)
1136
-
1137
- args << '--'
1138
- args.concat(Array(path))
1139
-
1140
- command('rm', *args)
1141
- end
1142
-
1143
- # Returns true if the repository is empty (meaning it has no commits)
1144
- #
1145
- # @return [Boolean]
1146
- #
1147
- def empty?
1148
- command('rev-parse', '--verify', 'HEAD')
1149
- false
1150
- rescue Git::FailedError => e
1151
- raise unless e.result.status.exitstatus == 128 &&
1152
- e.result.stderr == 'fatal: Needed a single revision'
1153
-
1154
- true
1155
- end
1156
-
1157
- COMMIT_OPTION_MAP = [
1158
- { keys: %i[add_all all], flag: '--all', type: :boolean },
1159
- { keys: [:allow_empty], flag: '--allow-empty', type: :boolean },
1160
- { keys: [:no_verify], flag: '--no-verify', type: :boolean },
1161
- { keys: [:allow_empty_message], flag: '--allow-empty-message', type: :boolean },
1162
- { keys: [:author], flag: '--author', type: :valued_equals },
1163
- { keys: [:message], flag: '--message', type: :valued_equals },
1164
- { keys: [:no_gpg_sign], flag: '--no-gpg-sign', type: :boolean },
1165
- { keys: [:date], flag: '--date', type: :valued_equals, validator: ->(v) { v.is_a?(String) } },
1166
- { keys: [:amend], type: :custom, builder: ->(value) { ['--amend', '--no-edit'] if value } },
1167
- {
1168
- keys: [:gpg_sign],
1169
- type: :custom,
1170
- builder: lambda { |value|
1171
- if value
1172
- value == true ? '--gpg-sign' : "--gpg-sign=#{value}"
1173
- end
1174
- }
1175
- }
1176
- ].freeze
1177
-
1178
- # Takes the commit message with the options and executes the commit command
1179
- #
1180
- # accepts options:
1181
- # :amend
1182
- # :all
1183
- # :allow_empty
1184
- # :author
1185
- # :date
1186
- # :no_verify
1187
- # :allow_empty_message
1188
- # :gpg_sign (accepts true or a gpg key ID as a String)
1189
- # :no_gpg_sign (conflicts with :gpg_sign)
1190
- #
1191
- # @param [String] message the commit message to be used
1192
- # @param [Hash] opts the commit options to be used
1193
-
1194
- def commit(message, opts = {})
1195
- opts[:message] = message if message # Handle message arg for backward compatibility
1196
-
1197
- # Perform cross-option validation before building args
1198
- raise ArgumentError, 'cannot specify :gpg_sign and :no_gpg_sign' if opts[:gpg_sign] && opts[:no_gpg_sign]
1199
-
1200
- ArgsBuilder.validate!(opts, COMMIT_OPTION_MAP)
1201
-
1202
- args = build_args(opts, COMMIT_OPTION_MAP)
1203
- command('commit', *args)
1204
- end
1205
- RESET_OPTION_MAP = [
1206
- { keys: [:hard], flag: '--hard', type: :boolean }
1207
- ].freeze
1208
-
1209
- def reset(commit, opts = {})
1210
- args = build_args(opts, RESET_OPTION_MAP)
1211
- args << commit if commit
1212
- command('reset', *args)
1213
- end
1214
-
1215
- CLEAN_OPTION_MAP = [
1216
- { keys: [:force], flag: '--force', type: :boolean },
1217
- { keys: [:ff], flag: '-ff', type: :boolean },
1218
- { keys: [:d], flag: '-d', type: :boolean },
1219
- { keys: [:x], flag: '-x', type: :boolean }
1220
- ].freeze
1221
-
1222
- def clean(opts = {})
1223
- args = build_args(opts, CLEAN_OPTION_MAP)
1224
- command('clean', *args)
1225
- end
1226
-
1227
- REVERT_OPTION_MAP = [
1228
- { keys: [:no_edit], flag: '--no-edit', type: :boolean }
1229
- ].freeze
1230
-
1231
- def revert(commitish, opts = {})
1232
- # Forcing --no-edit as default since it's not an interactive session.
1233
- opts = { no_edit: true }.merge(opts)
1234
-
1235
- args = build_args(opts, REVERT_OPTION_MAP)
1236
- args << commitish
1237
-
1238
- command('revert', *args)
1239
- end
1240
-
1241
- def apply(patch_file)
1242
- arr_opts = []
1243
- arr_opts << '--' << patch_file if patch_file
1244
- command('apply', *arr_opts)
1245
- end
1246
-
1247
- def apply_mail(patch_file)
1248
- arr_opts = []
1249
- arr_opts << '--' << patch_file if patch_file
1250
- command('am', *arr_opts)
1251
- end
1252
-
1253
- def stashes_all
1254
- stash_log_lines.each_with_index.map do |line, index|
1255
- parse_stash_log_line(line, index)
1256
- end
1257
- end
1258
-
1259
- def stash_save(message)
1260
- output = command('stash', 'save', message)
1261
- output =~ /HEAD is now at/
1262
- end
1263
-
1264
- def stash_apply(id = nil)
1265
- if id
1266
- command('stash', 'apply', id)
1267
- else
1268
- command('stash', 'apply')
1269
- end
1270
- end
1271
-
1272
- def stash_clear
1273
- command('stash', 'clear')
1274
- end
1275
-
1276
- def stash_list
1277
- command('stash', 'list')
1278
- end
1279
-
1280
- def branch_new(branch)
1281
- command('branch', branch)
1282
- end
1283
-
1284
- def branch_delete(branch)
1285
- command('branch', '-D', branch)
1286
- end
1287
-
1288
- CHECKOUT_OPTION_MAP = [
1289
- { keys: %i[force f], flag: '--force', type: :boolean },
1290
- { keys: %i[new_branch b], type: :validate_only },
1291
- { keys: [:start_point], type: :validate_only }
1292
- ].freeze
1293
-
1294
- # Runs checkout command to checkout or create branch
1295
- #
1296
- # accepts options:
1297
- # :new_branch
1298
- # :force
1299
- # :start_point
1300
- #
1301
- # @param [String] branch
1302
- # @param [Hash] opts
1303
- def checkout(branch = nil, opts = {})
1304
- if branch.is_a?(Hash) && opts.empty?
1305
- opts = branch
1306
- branch = nil
1307
- end
1308
- ArgsBuilder.validate!(opts, CHECKOUT_OPTION_MAP)
1309
-
1310
- flags = build_args(opts, CHECKOUT_OPTION_MAP)
1311
- positional_args = build_checkout_positional_args(branch, opts)
1312
-
1313
- command('checkout', *flags, *positional_args)
1314
- end
1315
-
1316
- def checkout_file(version, file)
1317
- arr_opts = []
1318
- arr_opts << version
1319
- arr_opts << file
1320
- command('checkout', *arr_opts)
1321
- end
1322
-
1323
- MERGE_OPTION_MAP = [
1324
- { keys: [:no_commit], flag: '--no-commit', type: :boolean },
1325
- { keys: [:no_ff], flag: '--no-ff', type: :boolean },
1326
- { keys: [:m], flag: '-m', type: :valued_space }
1327
- ].freeze
1328
-
1329
- def merge(branch, message = nil, opts = {})
1330
- # For backward compatibility, treat the message arg as the :m option.
1331
- opts[:m] = message if message
1332
- ArgsBuilder.validate!(opts, MERGE_OPTION_MAP)
1333
-
1334
- args = build_args(opts, MERGE_OPTION_MAP)
1335
- args.concat(Array(branch))
1336
-
1337
- command('merge', *args)
1338
- end
1339
-
1340
- MERGE_BASE_OPTION_MAP = [
1341
- { keys: [:octopus], flag: '--octopus', type: :boolean },
1342
- { keys: [:independent], flag: '--independent', type: :boolean },
1343
- { keys: [:fork_point], flag: '--fork-point', type: :boolean },
1344
- { keys: [:all], flag: '--all', type: :boolean }
1345
- ].freeze
1346
-
1347
- def merge_base(*args)
1348
- opts = args.last.is_a?(Hash) ? args.pop : {}
1349
- ArgsBuilder.validate!(opts, MERGE_BASE_OPTION_MAP)
1350
-
1351
- flags = build_args(opts, MERGE_BASE_OPTION_MAP)
1352
- command_args = flags + args
1353
-
1354
- command('merge-base', *command_args).lines.map(&:strip)
1355
- end
1356
-
1357
- def unmerged
1358
- unmerged = []
1359
- command_lines('diff', '--cached').each do |line|
1360
- unmerged << ::Regexp.last_match(1) if line =~ /^\* Unmerged path (.*)/
1361
- end
1362
- unmerged
1363
- end
1364
-
1365
- def conflicts # :yields: file, your, their
1366
- unmerged.each do |file_path|
1367
- Tempfile.create(['YOUR-', File.basename(file_path)]) do |your_file|
1368
- write_staged_content(file_path, 2, your_file).flush
1369
-
1370
- Tempfile.create(['THEIR-', File.basename(file_path)]) do |their_file|
1371
- write_staged_content(file_path, 3, their_file).flush
1372
- yield(file_path, your_file.path, their_file.path)
1373
- end
1374
- end
1375
- end
1376
- end
1377
-
1378
- REMOTE_ADD_OPTION_MAP = [
1379
- { keys: %i[with_fetch fetch], flag: '-f', type: :boolean },
1380
- { keys: [:track], flag: '-t', type: :valued_space }
1381
- ].freeze
1382
-
1383
- def remote_add(name, url, opts = {})
1384
- ArgsBuilder.validate!(opts, REMOTE_ADD_OPTION_MAP)
1385
-
1386
- flags = build_args(opts, REMOTE_ADD_OPTION_MAP)
1387
- positional_args = ['--', name, url]
1388
- command_args = ['add'] + flags + positional_args
1389
-
1390
- command('remote', *command_args)
1391
- end
1392
-
1393
- REMOTE_SET_BRANCHES_OPTION_MAP = [
1394
- { keys: [:add], flag: '--add', type: :boolean }
1395
- ].freeze
1396
-
1397
- def remote_set_branches(name, branches, opts = {})
1398
- ArgsBuilder.validate!(opts, REMOTE_SET_BRANCHES_OPTION_MAP)
1399
-
1400
- flags = build_args(opts, REMOTE_SET_BRANCHES_OPTION_MAP)
1401
- branch_args = Array(branches).flatten
1402
- command_args = ['set-branches'] + flags + [name] + branch_args
1403
-
1404
- command('remote', *command_args)
1405
- end
1406
-
1407
- def remote_set_url(name, url)
1408
- arr_opts = ['set-url']
1409
- arr_opts << name
1410
- arr_opts << url
1411
-
1412
- command('remote', *arr_opts)
1413
- end
1414
-
1415
- def remote_remove(name)
1416
- command('remote', 'rm', name)
1417
- end
1418
-
1419
- def remotes
1420
- command_lines('remote')
1421
- end
1422
-
1423
- def tags
1424
- command_lines('tag')
1425
- end
1426
-
1427
- TAG_OPTION_MAP = [
1428
- { keys: %i[force f], flag: '-f', type: :boolean },
1429
- { keys: %i[annotate a], flag: '-a', type: :boolean },
1430
- { keys: %i[sign s], flag: '-s', type: :boolean },
1431
- { keys: %i[delete d], flag: '-d', type: :boolean },
1432
- { keys: %i[message m], flag: '-m', type: :valued_space }
1433
- ].freeze
1434
-
1435
- def tag(name, *args)
1436
- opts = args.last.is_a?(Hash) ? args.pop : {}
1437
- target = args.first
1438
-
1439
- validate_tag_options!(opts)
1440
- ArgsBuilder.validate!(opts, TAG_OPTION_MAP)
1441
-
1442
- flags = build_args(opts, TAG_OPTION_MAP)
1443
- positional_args = [name, target].compact
1444
-
1445
- command('tag', *flags, *positional_args)
1446
- end
1447
-
1448
- FETCH_OPTION_MAP = [
1449
- { keys: [:all], flag: '--all', type: :boolean },
1450
- { keys: %i[tags t], flag: '--tags', type: :boolean },
1451
- { keys: %i[prune p], flag: '--prune', type: :boolean },
1452
- { keys: %i[prune-tags P], flag: '--prune-tags', type: :boolean },
1453
- { keys: %i[force f], flag: '--force', type: :boolean },
1454
- { keys: %i[update-head-ok u], flag: '--update-head-ok', type: :boolean },
1455
- { keys: [:unshallow], flag: '--unshallow', type: :boolean },
1456
- { keys: [:depth], flag: '--depth', type: :valued_space },
1457
- { keys: [:ref], type: :validate_only }
1458
- ].freeze
1459
-
1460
- def fetch(remote, opts)
1461
- ArgsBuilder.validate!(opts, FETCH_OPTION_MAP)
1462
- args = build_args(opts, FETCH_OPTION_MAP)
1463
-
1464
- if remote || opts[:ref]
1465
- args << '--'
1466
- args << remote if remote
1467
- args << opts[:ref] if opts[:ref]
1468
- end
1469
-
1470
- command('fetch', *args, merge: true)
1471
- end
1472
-
1473
- PUSH_OPTION_MAP = [
1474
- { keys: [:mirror], flag: '--mirror', type: :boolean },
1475
- { keys: [:delete], flag: '--delete', type: :boolean },
1476
- { keys: %i[force f], flag: '--force', type: :boolean },
1477
- { keys: [:push_option], flag: '--push-option', type: :repeatable_valued_space },
1478
- { keys: [:all], type: :validate_only }, # For validation purposes
1479
- { keys: [:tags], type: :validate_only } # From the `push` method's logic
1480
- ].freeze
1481
-
1482
- def push(remote = nil, branch = nil, opts = nil)
1483
- remote, branch, opts = normalize_push_args(remote, branch, opts)
1484
- ArgsBuilder.validate!(opts, PUSH_OPTION_MAP)
1485
-
1486
- raise ArgumentError, 'remote is required if branch is specified' if !remote && branch
1487
-
1488
- args = build_push_args(remote, branch, opts)
1489
-
1490
- if opts[:mirror]
1491
- command('push', *args)
1492
- else
1493
- command('push', *args)
1494
- command('push', '--tags', *(args - [branch].compact)) if opts[:tags]
1495
- end
1496
- end
1497
-
1498
- PULL_OPTION_MAP = [
1499
- { keys: [:allow_unrelated_histories], flag: '--allow-unrelated-histories', type: :boolean }
1500
- ].freeze
1501
-
1502
- def pull(remote = nil, branch = nil, opts = {})
1503
- raise ArgumentError, 'You must specify a remote if a branch is specified' if remote.nil? && !branch.nil?
1504
-
1505
- ArgsBuilder.validate!(opts, PULL_OPTION_MAP)
1506
-
1507
- flags = build_args(opts, PULL_OPTION_MAP)
1508
- positional_args = [remote, branch].compact
1509
-
1510
- command('pull', *flags, *positional_args)
1511
- end
1512
-
1513
- def tag_sha(tag_name)
1514
- head = File.join(@git_dir, 'refs', 'tags', tag_name)
1515
- return File.read(head).chomp if File.exist?(head)
1516
-
1517
- begin
1518
- command('show-ref', '--tags', '-s', tag_name)
1519
- rescue Git::FailedError => e
1520
- raise unless e.result.status.exitstatus == 1 && e.result.stderr == ''
1521
-
1522
- ''
1523
- end
1524
- end
1525
-
1526
- def repack
1527
- command('repack', '-a', '-d')
1528
- end
1529
-
1530
- def gc
1531
- command('gc', '--prune', '--aggressive', '--auto')
1532
- end
1533
-
1534
- FSCK_OPTION_MAP = [
1535
- { flag: '--no-progress', type: :static },
1536
- { keys: [:unreachable], flag: '--unreachable', type: :boolean },
1537
- { keys: [:strict], flag: '--strict', type: :boolean },
1538
- { keys: [:connectivity_only], flag: '--connectivity-only', type: :boolean },
1539
- { keys: [:root], flag: '--root', type: :boolean },
1540
- { keys: [:tags], flag: '--tags', type: :boolean },
1541
- { keys: [:cache], flag: '--cache', type: :boolean },
1542
- { keys: [:no_reflogs], flag: '--no-reflogs', type: :boolean },
1543
- { keys: [:lost_found], flag: '--lost-found', type: :boolean },
1544
- { keys: [:dangling], flag: '--dangling', type: :boolean_negatable },
1545
- { keys: [:full], flag: '--full', type: :boolean_negatable },
1546
- { keys: [:name_objects], flag: '--name-objects', type: :boolean_negatable },
1547
- { keys: [:references], flag: '--references', type: :boolean_negatable }
1548
- ].freeze
1549
-
1550
- def fsck(*objects, **opts)
1551
- args = ArgsBuilder.build(opts, FSCK_OPTION_MAP)
1552
- args.concat(objects) unless objects.empty?
1553
- # fsck returns non-zero exit status when issues are found:
1554
- # 1 = errors found, 2 = missing objects, 4 = warnings
1555
- # We still want to parse the output in these cases
1556
- output = begin
1557
- command('fsck', *args)
1558
- rescue Git::FailedError => e
1559
- raise unless [1, 2, 4].include?(e.result.status.exitstatus)
1560
-
1561
- e.result.stdout
1562
- end
1563
- parse_fsck_output(output)
1564
- end
1565
-
1566
- READ_TREE_OPTION_MAP = [
1567
- { keys: [:prefix], flag: '--prefix', type: :valued_equals }
1568
- ].freeze
1569
-
1570
- def read_tree(treeish, opts = {})
1571
- ArgsBuilder.validate!(opts, READ_TREE_OPTION_MAP)
1572
- flags = build_args(opts, READ_TREE_OPTION_MAP)
1573
- command('read-tree', *flags, treeish)
1574
- end
1575
-
1576
- def write_tree
1577
- command('write-tree')
1578
- end
1579
-
1580
- COMMIT_TREE_OPTION_MAP = [
1581
- { keys: %i[parent parents], flag: '-p', type: :repeatable_valued_space },
1582
- { keys: [:message], flag: '-m', type: :valued_space }
1583
- ].freeze
1584
-
1585
- def commit_tree(tree, opts = {})
1586
- opts[:message] ||= "commit tree #{tree}"
1587
- ArgsBuilder.validate!(opts, COMMIT_TREE_OPTION_MAP)
1588
-
1589
- flags = build_args(opts, COMMIT_TREE_OPTION_MAP)
1590
- command('commit-tree', tree, *flags)
1591
- end
1592
-
1593
- def update_ref(ref, commit)
1594
- command('update-ref', ref, commit)
1595
- end
1596
-
1597
- CHECKOUT_INDEX_OPTION_MAP = [
1598
- { keys: [:prefix], flag: '--prefix', type: :valued_equals },
1599
- { keys: [:force], flag: '--force', type: :boolean },
1600
- { keys: [:all], flag: '--all', type: :boolean },
1601
- { keys: [:path_limiter], type: :validate_only }
1602
- ].freeze
1603
-
1604
- def checkout_index(opts = {})
1605
- ArgsBuilder.validate!(opts, CHECKOUT_INDEX_OPTION_MAP)
1606
- args = build_args(opts, CHECKOUT_INDEX_OPTION_MAP)
1607
-
1608
- if (path = opts[:path_limiter]) && path.is_a?(String)
1609
- args.push('--', path)
1610
- end
1611
-
1612
- command('checkout-index', *args)
1613
- end
1614
-
1615
- ARCHIVE_OPTION_MAP = [
1616
- { keys: [:prefix], flag: '--prefix', type: :valued_equals },
1617
- { keys: [:remote], flag: '--remote', type: :valued_equals },
1618
- # These options are used by helpers or handled manually
1619
- { keys: [:path], type: :validate_only },
1620
- { keys: [:format], type: :validate_only },
1621
- { keys: [:add_gzip], type: :validate_only }
1622
- ].freeze
1623
-
1624
- def archive(sha, file = nil, opts = {})
1625
- ArgsBuilder.validate!(opts, ARCHIVE_OPTION_MAP)
1626
- file ||= temp_file_name
1627
- format, gzip = parse_archive_format_options(opts)
1628
-
1629
- args = build_args(opts, ARCHIVE_OPTION_MAP)
1630
- args.unshift("--format=#{format}")
1631
- args << sha
1632
- args.push('--', opts[:path]) if opts[:path]
1633
-
1634
- File.open(file, 'wb') { |f| command('archive', *args, out: f) }
1635
- apply_gzip(file) if gzip
1636
-
1637
- file
1638
- end
1639
-
1640
- # returns the current version of git, as an Array of Fixnums.
1641
- def current_command_version
1642
- output = command('version')
1643
- version = output[/\d+(\.\d+)+/]
1644
- version_parts = version.split('.').collect(&:to_i)
1645
- version_parts.fill(0, version_parts.length...3)
1646
- end
1647
-
1648
- # Returns current_command_version <=> other_version
1649
- #
1650
- # @example
1651
- # lib.current_command_version #=> [2, 42, 0]
1652
- #
1653
- # lib.compare_version_to(2, 41, 0) #=> 1
1654
- # lib.compare_version_to(2, 42, 0) #=> 0
1655
- # lib.compare_version_to(2, 43, 0) #=> -1
1656
- #
1657
- # @param other_version [Array<Object>] the other version to compare to
1658
- # @return [Integer] -1 if this version is less than other_version, 0 if equal, or 1 if greater than
1659
- #
1660
- def compare_version_to(*other_version)
1661
- current_command_version <=> other_version
1662
- end
1663
-
1664
- def required_command_version
1665
- [2, 28]
1666
- end
1667
-
1668
- def meets_required_version?
1669
- (current_command_version <=> required_command_version) >= 0
1670
- end
1671
-
1672
- def self.warn_if_old_command(lib) # rubocop:disable Naming/PredicateMethod
1673
- Git::Deprecation.warn('Git::Lib#warn_if_old_command is deprecated. Use meets_required_version?.')
1674
-
1675
- return true if @version_checked
1676
-
1677
- @version_checked = true
1678
- unless lib.meets_required_version?
1679
- warn "[WARNING] The git gem requires git #{lib.required_command_version.join('.')} or later, " \
1680
- "but only found #{lib.current_command_version.join('.')}. You should probably upgrade."
1681
- end
1682
- true
1683
- end
1684
-
1685
- COMMAND_ARG_DEFAULTS = {
1686
- out: nil,
1687
- err: nil,
1688
- normalize: true,
1689
- chomp: true,
1690
- merge: false,
1691
- chdir: nil,
1692
- timeout: nil # Don't set to Git.config.timeout here since it is mutable
1693
- }.freeze
1694
-
1695
- STATIC_GLOBAL_OPTS = %w[
1696
- -c core.quotePath=true
1697
- -c color.ui=false
1698
- -c color.advice=false
1699
- -c color.diff=false
1700
- -c color.grep=false
1701
- -c color.push=false
1702
- -c color.remote=false
1703
- -c color.showBranch=false
1704
- -c color.status=false
1705
- -c color.transport=false
1706
- ].freeze
1707
-
1708
- LOG_OPTION_MAP = [
1709
- { type: :static, flag: '--no-color' },
1710
- { keys: [:all], flag: '--all', type: :boolean },
1711
- { keys: [:cherry], flag: '--cherry', type: :boolean },
1712
- { keys: [:since], flag: '--since', type: :valued_equals },
1713
- { keys: [:until], flag: '--until', type: :valued_equals },
1714
- { keys: [:grep], flag: '--grep', type: :valued_equals },
1715
- { keys: [:author], flag: '--author', type: :valued_equals },
1716
- { keys: [:count], flag: '--max-count', type: :valued_equals },
1717
- { keys: [:between], type: :custom, builder: ->(value) { "#{value[0]}..#{value[1]}" if value } }
1718
- ].freeze
1719
-
1720
- FSCK_OBJECT_PATTERN = /\A(dangling|missing|unreachable) (\w+) ([0-9a-f]{40})(?: \((.+)\))?\z/
1721
- FSCK_WARNING_PATTERN = /\Awarning in (\w+) ([0-9a-f]{40}): (.+)\z/
1722
- FSCK_ROOT_PATTERN = /\Aroot ([0-9a-f]{40})\z/
1723
- FSCK_TAGGED_PATTERN = /\Atagged (\w+) ([0-9a-f]{40}) \((.+)\) in ([0-9a-f]{40})\z/
1724
-
1725
- private_constant :FSCK_OBJECT_PATTERN, :FSCK_WARNING_PATTERN, :FSCK_ROOT_PATTERN, :FSCK_TAGGED_PATTERN
1726
-
1727
- private
1728
-
1729
- def parse_fsck_output(output)
1730
- result = { dangling: [], missing: [], unreachable: [], warnings: [], root: [], tagged: [] }
1731
- output.each_line { |line| parse_fsck_line(line.strip, result) }
1732
- Git::FsckResult.new(**result)
1733
- end
1734
-
1735
- def parse_fsck_line(line, result)
1736
- parse_fsck_object_line(line, result) ||
1737
- parse_fsck_warning_line(line, result) ||
1738
- parse_fsck_root_line(line, result) ||
1739
- parse_fsck_tagged_line(line, result)
1740
- end
1741
-
1742
- def parse_fsck_object_line(line, result)
1743
- return unless (match = FSCK_OBJECT_PATTERN.match(line))
1744
-
1745
- result[match[1].to_sym] << Git::FsckObject.new(type: match[2].to_sym, sha: match[3], name: match[4])
1746
- end
1747
-
1748
- def parse_fsck_warning_line(line, result)
1749
- return unless (match = FSCK_WARNING_PATTERN.match(line))
1750
-
1751
- result[:warnings] << Git::FsckObject.new(type: match[1].to_sym, sha: match[2], message: match[3])
1752
- end
1753
-
1754
- def parse_fsck_root_line(line, result)
1755
- return unless (match = FSCK_ROOT_PATTERN.match(line))
1756
-
1757
- result[:root] << Git::FsckObject.new(type: :commit, sha: match[1])
1758
- end
1759
-
1760
- def parse_fsck_tagged_line(line, result)
1761
- return unless (match = FSCK_TAGGED_PATTERN.match(line))
1762
-
1763
- result[:tagged] << Git::FsckObject.new(type: match[1].to_sym, sha: match[2], name: match[3])
1764
- end
1765
-
1766
- def parse_diff_path_status(args)
1767
- command_lines('diff', *args).each_with_object({}) do |line, memo|
1768
- status, path = split_status_line(line)
1769
- memo[path] = status
1770
- end
1771
- end
1772
-
1773
- def build_checkout_positional_args(branch, opts)
1774
- args = []
1775
- if opts[:new_branch] || opts[:b]
1776
- args.push('-b', branch)
1777
- args << opts[:start_point] if opts[:start_point]
1778
- elsif branch
1779
- args << branch
1780
- end
1781
- args
1782
- end
1783
-
1784
- def build_args(opts, option_map)
1785
- Git::ArgsBuilder.new(opts, option_map).build
1786
- end
1787
-
1788
- def initialize_from_base(base_object)
1789
- @git_dir = base_object.repo.to_s
1790
- @git_index_file = base_object.index&.to_s
1791
- @git_work_dir = base_object.dir&.to_s
1792
- @git_ssh = base_object.git_ssh
1793
- end
1794
-
1795
- def initialize_from_hash(base_hash)
1796
- @git_dir = base_hash[:repository]
1797
- @git_index_file = base_hash[:index]
1798
- @git_work_dir = base_hash[:working_directory]
1799
- @git_ssh = base_hash.key?(:git_ssh) ? base_hash[:git_ssh] : :use_global_config
1800
- end
1801
-
1802
- def return_base_opts_from_clone(clone_dir, opts)
1803
- base_opts = {}
1804
- base_opts[:repository] = clone_dir if opts[:bare] || opts[:mirror]
1805
- base_opts[:working_directory] = clone_dir unless opts[:bare] || opts[:mirror]
1806
- base_opts[:log] = opts[:log] if opts[:log]
1807
- base_opts[:git_ssh] = opts[:git_ssh] if opts.key?(:git_ssh)
1808
- base_opts
1809
- end
1810
-
1811
- def process_commit_headers(data)
1812
- headers = { 'parent' => [] } # Pre-initialize for multiple parents
1813
- each_cat_file_header(data) do |key, value|
1814
- if key == 'parent'
1815
- headers['parent'] << value
1816
- else
1817
- headers[key] = value
1818
- end
1819
- end
1820
- headers
1821
- end
1822
-
1823
- def parse_branch_line(line, index, all_lines)
1824
- match_data = match_branch_line(line, index, all_lines)
1825
-
1826
- return nil if match_data[:not_a_branch] || match_data[:detached_ref]
1827
-
1828
- format_branch_data(match_data)
1829
- end
1830
-
1831
- def match_branch_line(line, index, all_lines)
1832
- match_data = line.match(BRANCH_LINE_REGEXP)
1833
- raise Git::UnexpectedResultError, unexpected_branch_line_error(all_lines, line, index) unless match_data
1834
-
1835
- match_data
1836
- end
1837
-
1838
- def format_branch_data(match_data)
1839
- [
1840
- match_data[:refname],
1841
- !match_data[:current].nil?,
1842
- !match_data[:worktree].nil?,
1843
- match_data[:symref]
1844
- ]
1845
- end
1846
-
1847
- def unexpected_branch_line_error(lines, line, index)
1848
- <<~ERROR
1849
- Unexpected line in output from `git branch -a`, line #{index + 1}
1850
-
1851
- Full output:
1852
- #{lines.join("\n ")}
1853
-
1854
- Line #{index + 1}:
1855
- "#{line}"
1856
- ERROR
1857
- end
1858
-
1859
- def get_branch_state(branch_name)
1860
- command('rev-parse', '--verify', '--quiet', branch_name)
1861
- :active
1862
- rescue Git::FailedError => e
1863
- # An exit status of 1 with empty stderr from `rev-parse --verify`
1864
- # indicates a ref that exists but does not yet point to a commit.
1865
- raise unless e.result.status.exitstatus == 1 && e.result.stderr.empty?
1866
-
1867
- :unborn
1868
- end
1869
-
1870
- def execute_grep_command(args)
1871
- command_lines('grep', *args)
1872
- rescue Git::FailedError => e
1873
- # `git grep` returns 1 when no lines are selected.
1874
- raise unless e.result.status.exitstatus == 1 && e.result.stderr.empty?
1875
-
1876
- [] # Return an empty array for "no matches found"
1877
- end
1878
-
1879
- def parse_grep_output(lines)
1880
- lines.each_with_object(Hash.new { |h, k| h[k] = [] }) do |line, hsh|
1881
- match = line.match(/\A(.*?):(\d+):(.*)/)
1882
- next unless match
1883
-
1884
- _full, filename, line_num, text = match.to_a
1885
- hsh[filename] << [line_num.to_i, text]
1886
- end
1887
- end
1888
-
1889
- def parse_diff_stats_output(lines)
1890
- file_stats = parse_stat_lines(lines)
1891
- build_final_stats_hash(file_stats)
1892
- end
1893
-
1894
- def parse_stat_lines(lines)
1895
- lines.map do |line|
1896
- insertions_s, deletions_s, filename = split_status_line(line)
1897
- {
1898
- filename: filename,
1899
- insertions: insertions_s.to_i,
1900
- deletions: deletions_s.to_i
1901
- }
1902
- end
1903
- end
1904
-
1905
- def split_status_line(line)
1906
- parts = line.split("\t")
1907
- parts[-1] = unescape_quoted_path(parts[-1]) if parts.any?
1908
- parts
1909
- end
1910
-
1911
- def build_final_stats_hash(file_stats)
1912
- {
1913
- total: build_total_stats(file_stats),
1914
- files: build_files_hash(file_stats)
1915
- }
1916
- end
1917
-
1918
- def build_total_stats(file_stats)
1919
- insertions = file_stats.sum { |s| s[:insertions] }
1920
- deletions = file_stats.sum { |s| s[:deletions] }
1921
- {
1922
- insertions: insertions,
1923
- deletions: deletions,
1924
- lines: insertions + deletions,
1925
- files: file_stats.size
1926
- }
1927
- end
1928
-
1929
- def build_files_hash(file_stats)
1930
- file_stats.to_h { |s| [s[:filename], s.slice(:insertions, :deletions)] }
1931
- end
1932
-
1933
- def parse_ls_remote_output(lines)
1934
- lines.each_with_object(Hash.new { |h, k| h[k] = {} }) do |line, hsh|
1935
- type, name, value = parse_ls_remote_line(line)
1936
- if name
1937
- hsh[type][name] = value
1938
- else # Handles the HEAD entry, which has no name
1939
- hsh[type].update(value)
1940
- end
1941
- end
1942
- end
1943
-
1944
- def parse_ls_remote_line(line)
1945
- sha, info = line.split("\t", 2)
1946
- ref, type, name = info.split('/', 3)
1947
-
1948
- type ||= 'head'
1949
- type = 'branches' if type == 'heads'
1950
-
1951
- value = { ref: ref, sha: sha }
1952
-
1953
- [type, name, value]
1954
- end
1955
-
1956
- def stash_log_lines
1957
- path = File.join(@git_dir, 'logs/refs/stash')
1958
- return [] unless File.exist?(path)
1959
-
1960
- File.readlines(path, chomp: true)
1961
- end
1962
-
1963
- def parse_stash_log_line(line, index)
1964
- full_message = line.split("\t", 2).last
1965
- match_data = full_message.match(/^[^:]+:(.*)$/)
1966
- message = match_data ? match_data[1] : full_message
1967
-
1968
- [index, message.strip]
1969
- end
1970
-
1971
- # Writes the staged content of a conflicted file to an IO stream
1972
- #
1973
- # @param path [String] the path to the file in the index
1974
- #
1975
- # @param stage [Integer] the stage of the file to show (e.g., 2 for 'ours', 3 for 'theirs')
1976
- #
1977
- # @param out_io [IO] the IO object to write the staged content to
1978
- #
1979
- # @return [IO] the IO object that was written to
1980
- #
1981
- def write_staged_content(path, stage, out_io)
1982
- command('show', ":#{stage}:#{path}", out: out_io)
1983
- out_io
1984
- end
1985
-
1986
- def validate_tag_options!(opts)
1987
- is_annotated = opts[:a] || opts[:annotate]
1988
- has_message = opts[:m] || opts[:message]
1989
-
1990
- return unless is_annotated && !has_message
1991
-
1992
- raise ArgumentError, 'Cannot create an annotated tag without a message.'
1993
- end
1994
-
1995
- def normalize_push_args(remote, branch, opts)
1996
- if branch.is_a?(Hash)
1997
- opts = branch
1998
- branch = nil
1999
- elsif remote.is_a?(Hash)
2000
- opts = remote
2001
- remote = nil
2002
- end
2003
-
2004
- opts ||= {}
2005
- # Backwards compatibility for `push(remote, branch, true)`
2006
- opts = { tags: opts } if [true, false].include?(opts)
2007
- [remote, branch, opts]
2008
- end
2009
-
2010
- def build_push_args(remote, branch, opts)
2011
- # Build the simple flags using the ArgsBuilder
2012
- args = build_args(opts, PUSH_OPTION_MAP)
2013
-
2014
- # Manually handle the flag with external dependencies and positional args
2015
- args << '--all' if opts[:all] && remote
2016
- args << remote if remote
2017
- args << branch if branch
2018
- args
2019
- end
2020
-
2021
- def temp_file_name
2022
- tempfile = Tempfile.new('archive')
2023
- file = tempfile.path
2024
- tempfile.close! # Prevents Ruby from deleting the file on garbage collection
2025
- file
2026
- end
2027
-
2028
- def parse_archive_format_options(opts)
2029
- format = opts[:format] || 'zip'
2030
- gzip = opts[:add_gzip] == true || format == 'tgz'
2031
- format = 'tar' if format == 'tgz'
2032
- [format, gzip]
2033
- end
2034
-
2035
- def apply_gzip(file)
2036
- file_content = File.read(file)
2037
- Zlib::GzipWriter.open(file) { |gz| gz.write(file_content) }
2038
- end
2039
-
2040
- def command_lines(cmd, *opts, chdir: nil)
2041
- cmd_op = command(cmd, *opts, chdir: chdir)
2042
- op = if cmd_op.encoding.name == 'UTF-8'
2043
- cmd_op
2044
- else
2045
- cmd_op.encode('UTF-8', 'binary', invalid: :replace, undef: :replace)
2046
- end
2047
- op.split("\n")
2048
- end
2049
-
2050
- # Returns a hash of environment variable overrides for git commands
2051
- #
2052
- # This method builds a hash of environment variables that control git's behavior,
2053
- # such as the git directory, working tree, and index file locations.
2054
- #
2055
- # @param additional_overrides [Hash] additional environment variables to set or unset
2056
- #
2057
- # Keys should be environment variable names (String) and values should be either:
2058
- # * A String value to set the environment variable
2059
- # * `nil` to unset the environment variable
2060
- #
2061
- # Per Process.spawn semantics, setting a key to `nil` will unset that environment
2062
- # variable, removing it from the environment passed to the git command.
2063
- #
2064
- # @return [Hash<String, String|nil>] environment variable overrides
2065
- #
2066
- # @example Basic usage with default environment variables
2067
- # env_overrides
2068
- # # => { 'GIT_DIR' => '/path/to/.git', 'GIT_WORK_TREE' => '/path/to/worktree', ... }
2069
- #
2070
- # @example Adding a custom environment variable
2071
- # env_overrides('GIT_TRACE' => '1')
2072
- # # => { 'GIT_DIR' => '/path/to/.git', ..., 'GIT_TRACE' => '1' }
2073
- #
2074
- # @example Unsetting an environment variable (used by worktree_command_line)
2075
- # env_overrides('GIT_INDEX_FILE' => nil)
2076
- # # => { 'GIT_DIR' => '/path/to/.git', 'GIT_WORK_TREE' => '/path/to/worktree',
2077
- # # 'GIT_INDEX_FILE' => nil, 'GIT_SSH' => <git_ssh_value>, 'LC_ALL' => <pinned_locale> }
2078
- # # When passed to Process.spawn, GIT_INDEX_FILE will be unset in the environment
2079
- #
2080
- # @see https://ruby-doc.org/core/Process.html#method-c-spawn Process.spawn
2081
- #
2082
- # @api private
2083
- #
2084
- def env_overrides(**additional_overrides)
2085
- {
2086
- 'GIT_DIR' => @git_dir,
2087
- 'GIT_WORK_TREE' => @git_work_dir,
2088
- 'GIT_INDEX_FILE' => @git_index_file,
2089
- 'GIT_SSH' => resolved_git_ssh,
2090
- # Pin the locale so git's behavior does not depend on the user's environment.
2091
- # Added for issue #753, where a German user's `git branch` output
2092
- # ("* (HEAD losgelöst bei origin/25.1)") broke branch parsing.
2093
- #
2094
- # The pin has two halves, and both are load-bearing here:
2095
- #
2096
- # - Messages: keeps git's human-readable text in English. `BRANCH_LINE_REGEXP`
2097
- # matches the literal English strings "(HEAD detached at ...)" and
2098
- # "(not a branch)" in `git branch -a` output, which is the exact issue #753
2099
- # failure mode.
2100
- # - Ctype: makes git's regex engine match *characters* rather than *bytes*.
2101
- # Under a C ctype, `grep` and `log --grep` silently return wrong answers —
2102
- # with exit status zero — for any pattern whose metacharacters span
2103
- # non-ASCII text.
2104
- #
2105
- # So do not "simplify" this to `C`: that yields English messages and a broken
2106
- # ctype, which is the worst of both. A pinned locale the host does not have
2107
- # degrades to that same C ctype, which is why each branch below has to name a
2108
- # locale that actually exists on the platform it applies to:
2109
- #
2110
- # - Non-Darwin: `C.UTF-8`. Stock Debian, Ubuntu, and RHEL images generate no
2111
- # `en_US.UTF-8`, so pinning it there produced exactly the silent breakage
2112
- # above. (musl ignores the locale name for ctype, so Alpine is UTF-8 either
2113
- # way.)
2114
- # - Darwin: `en_US.UTF-8`, which every macOS release ships. `C.UTF-8` did not
2115
- # arrive until macOS 15, so macOS 11–14 — including Intel Macs that are
2116
- # hardware-capped below 15 — would break under it. Delete this branch once
2117
- # macOS 14 and earlier are out of support.
2118
- #
2119
- # Windows takes the non-Darwin branch, where the value makes no difference:
2120
- # Git for Windows folds case and runs PCRE in UTF mode under every value, and
2121
- # matches bytes for `.` and POSIX classes under every value — measured on git
2122
- # 2.55.0 against `en_US.UTF-8`, `C.UTF-8`, `C`, and no pin at all.
2123
- #
2124
- # RHEL 7 (glibc 2.17) has neither locale and gets a C ctype whatever is pinned.
2125
- # It is EOL, and there is deliberately no public override for this value.
2126
- 'LC_ALL' => darwin_platform? ? 'en_US.UTF-8' : 'C.UTF-8'
2127
- }.merge(additional_overrides)
2128
- end
2129
-
2130
- # Whether this process is running on macOS
2131
- #
2132
- # Checks `RUBY_DESCRIPTION` as well as `RUBY_PLATFORM` because JRuby reports
2133
- # `RUBY_PLATFORM` as `"java"` on every host and records the real platform only in
2134
- # `RUBY_DESCRIPTION` (as, for example, `"... [arm64-darwin]"`). Testing
2135
- # `RUBY_PLATFORM` alone would put JRuby on macOS onto the non-Darwin branch, which is
2136
- # the one platform pairing that branch must not be given. This is the same detection
2137
- # the test suite uses for Windows, and for the same reason.
2138
- #
2139
- # Test the platform plainly rather than sniffing the Darwin version: `RUBY_PLATFORM`
2140
- # records the version Ruby was *built* against, so a Ruby built on macOS 14 still
2141
- # reports `darwin23` when run on macOS 15.
2142
- #
2143
- # @return [Boolean] true if this process is running on macOS
2144
- #
2145
- # @api private
2146
- #
2147
- def darwin_platform?
2148
- RUBY_PLATFORM.include?('darwin') || RUBY_DESCRIPTION.include?('darwin')
2149
- end
2150
-
2151
- # Resolve the git_ssh value to use for this instance
2152
- #
2153
- # @return [String, nil] the resolved git_ssh value
2154
- #
2155
- # Returns the global config value if @git_ssh is the sentinel :use_global_config,
2156
- # otherwise returns @git_ssh (which may be nil or a string)
2157
- #
2158
- # @api private
2159
- #
2160
- def resolved_git_ssh
2161
- return Git::Base.config.git_ssh if @git_ssh == :use_global_config
2162
-
2163
- @git_ssh
2164
- end
2165
-
2166
- def global_opts
2167
- [].tap do |global_opts|
2168
- global_opts << "--git-dir=#{@git_dir}" unless @git_dir.nil?
2169
- global_opts << "--work-tree=#{@git_work_dir}" unless @git_work_dir.nil?
2170
- global_opts.concat(STATIC_GLOBAL_OPTS)
2171
- end
2172
- end
2173
-
2174
- def command_line
2175
- @command_line ||=
2176
- Git::CommandLine.new(env_overrides, Git::Base.config.binary_path, global_opts, @logger)
2177
- end
2178
-
2179
- # Returns a command line instance without GIT_INDEX_FILE for worktree commands
2180
- #
2181
- # Git worktrees manage their own index files and setting GIT_INDEX_FILE
2182
- # causes corruption of both the main worktree and new worktree indexes.
2183
- #
2184
- # @return [Git::CommandLine]
2185
- # @api private
2186
- #
2187
- def worktree_command_line
2188
- @worktree_command_line ||=
2189
- Git::CommandLine.new(env_overrides('GIT_INDEX_FILE' => nil), Git::Base.config.binary_path, global_opts,
2190
- @logger)
2191
- end
2192
-
2193
- # @overload worktree_command(*args, **options_hash)
2194
- # Runs a git worktree command and returns the output
2195
- #
2196
- # This method is similar to #command but uses a command line instance
2197
- # that excludes GIT_INDEX_FILE from the environment to prevent index corruption.
2198
- #
2199
- # @param args [Array<String>] the command arguments
2200
- # @param options_hash [Hash] the options to pass to the command
2201
- #
2202
- # @return [String] the command's stdout
2203
- #
2204
- # @see #command
2205
- #
2206
- # @api private
2207
- #
2208
- def worktree_command(*, **options_hash)
2209
- options_hash = COMMAND_ARG_DEFAULTS.merge(options_hash)
2210
- options_hash[:timeout] ||= Git.config.timeout
2211
-
2212
- extra_options = options_hash.keys - COMMAND_ARG_DEFAULTS.keys
2213
- raise ArgumentError, "Unknown options: #{extra_options.join(', ')}" if extra_options.any?
2214
-
2215
- result = worktree_command_line.run(*, **options_hash)
2216
- result.stdout
2217
- end
2218
-
2219
- # Runs a git command and returns the output
2220
- #
2221
- # Additional args are passed to the command line. They should exclude the 'git'
2222
- # command itself and global options. Remember to splat the the arguments if given
2223
- # as an array.
2224
- #
2225
- # For example, to run `git log --pretty=oneline`, you would create the array
2226
- # `args = ['log', '--pretty=oneline']` and call `command(*args)`.
2227
- #
2228
- # @param options_hash [Hash] the options to pass to the command
2229
- # @option options_hash [IO, String, #write, nil] :out the destination for captured stdout
2230
- # @option options_hash [IO, String, #write, nil] :err the destination for captured stderr
2231
- # @option options_hash [Boolean] :normalize true to normalize the output encoding to UTF-8
2232
- # @option options_hash [Boolean] :chomp true to remove trailing newlines from the output
2233
- # @option options_hash [Boolean] :merge true to merge stdout and stderr into a single output
2234
- # @option options_hash [String, nil] :chdir the directory to run the command in
2235
- # @option options_hash [Numeric, nil] :timeout the maximum seconds to wait for the command to complete
2236
- #
2237
- # If timeout is nil, the global timeout from {Git::Config} is used.
2238
- #
2239
- # If timeout is zero, the timeout will not be enforced.
2240
- #
2241
- # If the command times out, it is killed via a `SIGKILL` signal and `Git::TimeoutError` is raised.
2242
- #
2243
- # If the command does not respond to SIGKILL, it will hang this method.
2244
- #
2245
- # @see Git::CommandLine#run
2246
- #
2247
- # @return [String] the command's stdout (or merged stdout and stderr if `merge`
2248
- # is true)
2249
- #
2250
- # @raise [ArgumentError] if an unknown option is passed
2251
- #
2252
- # @raise [Git::FailedError] if the command failed
2253
- #
2254
- # @raise [Git::SignaledError] if the command was signaled
2255
- #
2256
- # @raise [Git::TimeoutError] if the command times out
2257
- #
2258
- # @raise [Git::ProcessIOError] if an exception was raised while collecting subprocess output
2259
- #
2260
- # The exception's `result` attribute is a {Git::CommandLineResult} which will
2261
- # contain the result of the command including the exit status, stdout, and
2262
- # stderr.
2263
- #
2264
- # @api private
2265
- #
2266
- def command(*, **options_hash)
2267
- options_hash = COMMAND_ARG_DEFAULTS.merge(options_hash)
2268
- options_hash[:timeout] ||= Git.config.timeout
2269
-
2270
- extra_options = options_hash.keys - COMMAND_ARG_DEFAULTS.keys
2271
- raise ArgumentError, "Unknown options: #{extra_options.join(', ')}" if extra_options.any?
2272
-
2273
- result = command_line.run(*, **options_hash)
2274
- result.stdout
2275
- end
2276
-
2277
- # Takes the diff command line output (as Array) and parse it into a Hash
2278
- #
2279
- # @param [String] diff_command the diff commadn to be used
2280
- # @param [Array] opts the diff options to be used
2281
- # @return [Hash] the diff as Hash
2282
- def diff_as_hash(diff_command, opts = [])
2283
- # update index before diffing to avoid spurious diffs
2284
- command('status')
2285
- command_lines(diff_command, *opts).each_with_object({}) do |line, memo|
2286
- info, file = split_status_line(line)
2287
- mode_src, mode_dest, sha_src, sha_dest, type = info.split
2288
-
2289
- memo[file] = {
2290
- mode_index: mode_dest, mode_repo: mode_src.to_s[1, 7],
2291
- path: file, sha_repo: sha_src, sha_index: sha_dest,
2292
- type: type
2293
- }
2294
- end
2295
- end
2296
-
2297
- # Returns an array holding the common options for the log commands
2298
- #
2299
- # @param [Hash] opts the given options
2300
- # @return [Array] the set of common options that the log command will use
2301
- def log_common_options(opts)
2302
- if opts[:count] && !opts[:count].is_a?(Integer)
2303
- raise ArgumentError, "The log count option must be an Integer but was #{opts[:count].inspect}"
2304
- end
2305
-
2306
- build_args(opts, LOG_OPTION_MAP)
2307
- end
2308
-
2309
- # Retrurns an array holding path options for the log commands
2310
- #
2311
- # @param [Hash] opts the given options
2312
- # @return [Array] the set of path options that the log command will use
2313
- def log_path_options(opts)
2314
- arr_opts = []
2315
-
2316
- arr_opts << opts[:object] if opts[:object].is_a? String
2317
- if opts[:path_limiter]
2318
- arr_opts << '--'
2319
- arr_opts += Array(opts[:path_limiter])
2320
- end
2321
- arr_opts
2322
- end
2323
-
2324
- def log_or_empty_on_unborn
2325
- yield
2326
- rescue Git::FailedError => e
2327
- raise unless e.result.status.exitstatus == 128 &&
2328
- e.result.stderr =~ /does not have any commits yet/
2329
-
2330
- []
2331
- end
2332
- end
2333
- end