hg_git_repository.rb 61.7 KB
Newer Older
1
# frozen_string_literal: true
2

3
4
5
# Index of the line in lines matching a given regexp
def match_idx(lines, rx)
  lines.each_with_index do |line, i|
6
    return i if rx.match(line) # rubocop:disable Cop/AvoidReturnFromBlocks
7
8
9
10
  end
  nil
end

11
12
13
module Gitlab
  module Mercurial
    class HgGitRepository < Gitlab::Git::Repository
14
      include Gitlab::Popen
15
      extend ::Gitlab::Utils::Override
16

17
      attr_accessor :unit_tests_skip_hooks
18
      attr_writer :hg_project_for_perms
19

20
21
22
23
      MergeError = Class.new(StandardError)
      HgError = Class.new(StandardError)
      InvalidHgSetting = Class.new(StandardError)
      HgRevisionError = Class.new(StandardError)
24
25
26
      # In general, GitLab expects `multi_action` to raise IndexError,
      # so let's subclass it.
      ActionError = Class.new(Gitlab::Git::Index::IndexError)
27

28
29
      UNIX_EOL = Gitlab::Utils::LineEndings::UNIX

30
31
32
33
34
35
36
37
38
39
40
      DEFAULT_HGRC = [
        "# This is the specific configuration for this repository",
        "# You may modify it freely at your will.",
        "#",
        "# By default, it includes the configuration from the enclosing group",
        "# but all the settings defined in the present file will take precedence",
        "# as long as they are below the %include line",
        "# You may also remove the %include line altogether if you prefer.",
        "",
        "# group-level configuration",
        "%include <GROUP_HGRC_RPATH>",
41
42
        ""
      ].join("\n").freeze
43
44
45
46
47
48
49
50
51
52
53
54

      DEFAULT_SUBGROUP_HGRC = [
        "# This is the Mercurial configuration for this subgroup.",
        "# You may modify it freely at your will.",
        "#",
        "# By default, it includes the configuration from the enclosing",
        "# group, but all the settings defined in the present file will",
        "# take precedence as long as they are below the %include line",
        "# You may also remove the %include line altogether if you prefer.",
        "",
        "# enclosing group configuration",
        "%include ../hgrc",
55
56
        ""
      ].join("\n").freeze
57

58
59
      LOGGER = Gitlab::AppLogger

60
61
62
      def initialize(*args)
        super(*args)
        @hg_relative_path = relative_path.sub(/\.git$/, '.hg')
63
64
65
66
67
        # storage can actually be in VCS-qualified form (see CommitService)
        # so we need to handle that.
        bare_storage = Gitlab::GitalyClient.vcs_storage_split(@storage)[0]
        @hg_storage_root = Gitlab.config.repositories.storages.fetch(
          bare_storage).hg_disk_path
68
        @hgpath = File.join(@hg_storage_root, @hg_relative_path)
69
70
71
72
73
74
75

        # `nil` is the language default for instance variables,
        # but we want to be explicit in that case: it will mean no check
        # in Mercurial process for write operations (besides what's been done
        # at the Model level already, and is enough in the Git case).
        # It should stay nil only for Wikis and similar.
        @hg_project_for_perms = nil
76
        @unit_tests_skip_hooks = ENV["GITALY_TESTING_NO_GIT_HOOKS"] == '1'
77
78
79
80
81
82
83
      end

      # Mercurial path will stay until HGitaly is ready
      def hg_full_path
        @hgpath
      end

84
      def hg_config_item_bool?(section, item)
85
        hgitaly_hg_repo_client.config_item_bool(section, item)
86
87
      end

88
      override :create_repository
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
      def create_repository(**named_args)
        # at the time being all named_args are Mercurial specific. Still,
        # passing explicitely is more future proof
        super(**named_args)
        create_hg_repository(**named_args)
      end

      # Create the Mercurial repository only
      #
      # This is what a FS based native Mercurial class would do
      #
      # - namespace_fs_path: the path of the directory for the parent
      #                      namespace config files
      # - in_subgroup: true is the parent namespace is a subgroup
      def create_hg_repository(namespace_fs_path:, in_subgroup:)
104
        LOGGER.info(
105
106
107
          "Creating Mercurial repository at #{@hg_relative_path} "\
          "namespace path=#{namespace_fs_path} "\
          "in_subgroup: #{in_subgroup}")
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

        hg_call(["init", @hgpath],
                # Rails.root can be a Mercurial repo, that can lead to
                # complications. Let's run from a path that's very unlikely
                # to be one:
                path: @hg_storage_root,
                env: hg_env_minimal)

        File.write(File.join(@hgpath, '.hg', 'hgrc'),
                   DEFAULT_HGRC.sub('<GROUP_HGRC_RPATH>',
                                    hgrc_inherit_path(namespace_fs_path)))

        if in_subgroup
          ns_path = Pathname(@hg_storage_root).join(namespace_fs_path)
          ns_hgrcf = ns_path.join('hgrc')
          unless File.exist?(ns_hgrcf)
            FileUtils.mkdir_p(ns_path)
            File.write(ns_hgrcf, DEFAULT_SUBGROUP_HGRC)
126
127
          end
        end
128

129
        true
130
      rescue StandardError => err
131
132
        LOGGER.error("Failed to add Mercurial repository "\
                     "for #{storage}/#{name}: #{err}")
133
134
135
        false
      end

136
      override :import_repository
137
      def import_repository(url, **create_args)
138
139
140
141
        if url.start_with?('.', '/')
          raise ArgumentError, "don't use disk paths with import_repository: "\
                               "#{url.inspect}"
        end
142
143
144
145

        logprefix = "#{self.class.name} import_repository "\
                    "for #{mask_password_in_url(url)} "\
                    "into #{@hgpath}"
146
        LOGGER.info("#{logprefix} creating repository(ies) before pull")
147
148
149
        create_repository(**create_args)

        hg_exe = Gitlab.config.mercurial.bin_path
150
151
152
        hg_env = hg_env_minimal
        hg_env.update({ 'HGUSER' => 'Heptapod system',
                        'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes' })
153
        LOGGER.info("#{logprefix} Pulling")
154
155
156
157
158
159
160
161
162
163
        pid = Process.spawn(hg_env,
                            hg_exe, "pull", "-q",
                             "--config", "heptapod.initial-import=yes",
                            "-R", @hgpath, url)

        timeout = Gitlab.config.gitlab_shell.git_timeout
        begin
          Timeout.timeout(timeout) do
            Process.wait(pid)
          end
164

165
          unless $?.exitstatus == 0
166
            msg = "#{logprefix} import failed"
167
            LOGGER.error(msg)
168
169
            raise HgError, msg
          end
170

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        rescue Timeout::Error
          msg = "#{logprefix} failed due to timeout: pull not finished after "\
                "the #{timeout} seconds set in configuration"
          Process.kill('KILL', pid)
          Process.wait
          FileUtils.rm_rf(@hgpath)
          # Removing the Git auxiliary repo as well for consistency
          FileUtils.rm_rf(@hgpath[0..-4] + ".git")
          raise HgError, msg
        end

        begin
          hg_optim
        rescue StandardError => err
          # let's not abord the import because optimization failed
186
          LOGGER.error("#{logprefix} Post import optimization "\
187
188
189
190
191
192
193
194
                             "failed: #{err}")
        end
      end

      # Perform Mercurial repository optimizations
      #
      # See heptapod#192 for details about implications of various options
      def hg_optim
195
196
197
        hg_env = hg_env_minimal
        hg_env.update({ 'HGUSER' => 'Heptapod system',
                        'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes' })
198
199
        hg_call(%w[debugupgraderepo -o re-delta-all --run --no-backup'],
                env: hg_env)
200
201
      end

202
203
204
      # Run `hg recover`.
      # This is idempotent and reasonably fast if there's nothing to recover
      def hg_recover
205
206
207
        hg_env = hg_env_minimal
        hg_env.update({ 'HGUSER' => 'Heptapod system',
                        'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes' })
208
        hg_call(%w[recover], env: hg_env, success_code_can_be_one: true)
209
210
      end

211
      override :rename
212
213
      def rename(new_git_relative_path)
        super(new_git_relative_path)
214
215
216
217
        hg_rename(new_git_relative_path)
      end

      def hg_rename(new_git_relative_path)
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
        new_hg_relative_path = new_git_relative_path.sub(/\.git$/, '.hg')
        new_hgpath = File.join(@hg_storage_root, new_hg_relative_path)

        namespace_rpath = rpath_to_namespace_if_hgrc_included(
          new_hg_relative_path)
        # here (merge with GitLab 12.10),
        # it seems to be the caller's responsibility to check existence
        # and rescue from exceptions.
        FileUtils.mv(@hgpath, new_hgpath)
        return if namespace_rpath.nil?

        @hgpath = new_hgpath
        @hg_relative_path = new_hg_relative_path
        check_fix_hgrc_inheritance(namespace_rpath)
      end

234
      override :remove
235
236
      def remove
        super
237
238
239
240
        hg_remove
      end

      def hg_remove
241
242
243
        FileUtils.rm_rf(@hgpath)
      end

244
245
246
247
248
249
250
251
252
253
254
      def hg_size
        cmd = ["du", "-ks", @hgpath]
        kilobytes, status = popen(cmd)
        if status != 0
          raise StandardError,
                "Could not run command #{command}"
        end
        # rounded to 2 decimal places is what Git::Repository does
        (kilobytes.to_f / 1024).round(2)
      end

255
      override :size
256
257
258
259
260
      # Return repo size in megabytes (same as `super` as of this writing)
      def size
        super + hg_size
      end

261
262
263
264
      def hg_sha_map
        @git_sha_map = nil unless @hg_sha_map
        # Get the entries of the git-mapfile and store them in a git => hg Hash
        @hg_sha_map ||= File.open(File.join(@hgpath, '.hg', 'git-mapfile')) do |f|
265
          f.to_h do |line|
266
267
268
269
270
            line.match(/^([0-9a-f]{40}) ([0-9a-f]{40})\n$/) do |match|
              [match[1], match[2]]
            end
          end
        end
271
272
273
274
275
276
277
278
279
280
281
282
283
      rescue Errno::ENOENT
        # This can happen on rare occasions.
        #
        # Logically that means the correspondence is empty, but let's not cache it
        # so that we won't need exceptional cache invalidations
        #
        # For instance, Lfs::FileTransformer.lfs_file?
        # (called from Files::CreateService) queries tree/blob attributes while
        # it's not guaranteed yet that the repo isn't empty. In the current state
        # of Mercurial native projects (before HGitaly2 developments have even
        # started), this goes through Git Tree/Blob lookups... and a conversion
        # of Mercurial SHAs to Git that must not raise unexpected exceptions.
        {}
284
285
286
287
      end

      def git_sha_map
        # Reverse the entries, so that it is a hg => git Hash
288
        @git_sha_map ||= hg_sha_map.to_a.to_h {|x| x.reverse }
289
290
      end

291
292
293
294
295
296
297
298
299
300
      # Useful for repetitive calls, and will cache only the `true` result
      # Rationale: repetitive calls are typically for existing repositories.
      # (disabling the cop because that's really what we want, and there's
      # another cop preventing us to use a more explicit style)
      # rubocop:disable Gitlab/PredicateMemoization
      def cached_exists?
        @cache_exists ||= exists?
      end
      # rubocop:enable Gitlab/PredicateMemoization

301
      def sha_from_hgsha(hgsha)
302
        return unless cached_exists?
303
304
305
306
307

        git_sha_map[hgsha]
      end

      def hgsha_from_sha(sha)
308
        return unless cached_exists?
309
310
311
312

        hg_sha_map[sha]
      end

313
      override :archive_sha
314
315
316
317
      def archive_sha(sha)
        hgsha_from_sha(sha)
      end

318
319
320
321
322
323
324
325
      def commit_id_to_display_id(commit_id)
        hgsha_from_sha(commit_id)
      end

      def commit_id_from_display_id(display_id)
        sha_from_hgsha(display_id)
      end

326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
      def batch_by_hgsha(sha_prefixes)
        # TODO stupid algorithm. Above a certain size, it's more efficient
        # to call hg with a the `sha_prefixes.join('+')` revset but then, we
        # actually need a specific command so that ambiguous (too short)
        # prefixes don't turn in hard errors that make just one ambiguous
        # among many break the lookup of all.
        res = []
        git_sha_map.each_pair do |hgsha, gitsha|
          sha_prefixes.each do |pref|
            res << gitsha if hgsha.start_with?(pref)
          end
        end
        res
      end

341
342
343
344
345
      def hg_git_invalidate_maps!
        @git_sha_map = nil
        @hg_sha_map = nil
      end

346
347
348
349
350
351
352
      # Retrieve the Mercurial SHA from a symbolic revision
      #
      # `path` can be specified to use something else than
      # the main repository path, typically a temporary working dir
      # obtained through `hg share`, hence taking advantage of working dir
      # revisions (`.`)
      def hgsha_from_rev(hgrev, path = nil)
353
354
355
        hg_call(['log', '--limit', '1', '-r', hgrev, '-T', '{node}'],
                path: path).first.strip
      rescue HgError
356
        raise HgRevisionError, "Could not find changeset #{hgrev} in #{path || @hgpath}"
357
358
359
360
      end

      # Find the named branch of a Mercurial changeset
      def hg_changeset_branch(hgsha)
361
362
363
364
365
366
367
368
369
370
371
        if Gitlab::Mercurial.full_hex_hash?(hgsha)
          begin
            hg_call(['log', '--hidden', '-r', hgsha, '-T', '{branch}']).first.strip
          rescue HgError => e
            raise HgError, "Could not get hg branch of changeset #{hgsha}: "\
                           "#{e.message}"
          end
        else
          raise HgError, "hg_changeset_branch() is only applicable "\
                         "to full hexadecimal hashes (got #{hgsha})"
        end
372
373
      end

374
      def hg_changeset_branch_topic(hgsha)
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
        if Gitlab::Mercurial.full_hex_hash?(hgsha)
          begin
            out = hg_call(['log', '--hidden', '-r', hgsha, '-T', '{branch}:{topic}'])
                    .first.strip
            # legacy branches with colons are possible (restriction for all
            # names appeared in 2012), topics are not (introduced in 2015)
            branch, _sep, topic = out.rpartition(':')
            topic = nil if topic.empty? # our general convention
            [branch, topic]
          rescue HgError => e
            raise HgError, "Could not get hg branch and topic "\
                           "of changeset #{hgsha}: #{e.message}"
          end
        else
          raise HgError, "hg_changeset_branch_topic() is only applicable "\
                         "to full hexadecimal hashes (got #{hgsha})"
        end
392
393
      end

394
      def hg_env_minimal
395
396
        env = { 'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                'HEPTAPOD_HG_NATIVE' => 'no' }
397
398
399
        hg_mod_pol = Gitlab.config.mercurial.module_policy
        env['HGMODULEPOLICY'] = hg_mod_pol unless hg_mod_pol.nil?
        env
400
401
      end

402
      # Return a suitable environment for write operations (merge etc.)
403
404
405
      #
      # This method assumes that write permission is already granted,
      # it adds the publish permission if the given user has the appropriate
406
      # role.
407
      def hg_env_for_write(user, force_system_user: false)
408
        if user.nil? && !force_system_user
409
410
411
412
          raise Gitlab::HgAccess::ForbiddenError,
                "write operation without user not allowed "\
                "without force_system_user flag"
        end
413

414
415
        env = hg_env_minimal
        env.update({
416
417
418
419
          # `name` and `email` are as in `committer` (which
          # does not have `username`) but the purpose here is
          # different: we want to pass them
          # along regardless of what should be a commit authorship.
420
          # If that latter information would change for any reason
421
422
423
          # these would still be directly linked to authenticated
          # user info
          'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => "yes",
424
425
426
427
          'HEPTAPOD_USERINFO_ID' => user&.id.to_s,
          'HEPTAPOD_USERINFO_USERNAME' => user&.username,
          'HEPTAPOD_USERINFO_NAME' => user&.name,
          'HEPTAPOD_USERINFO_EMAIL' => user&.email,
428
          'GL_REPOSITORY' => @gl_repository,
429
430
          'HGUSER' => nil
        })
431

432
433
434
435
436
437
438
439
        unless @hg_project_for_perms.nil?
          env.update(
            {
              'HEPTAPOD_PROJECT_PATH' => @hg_project_for_perms.path,
              'HEPTAPOD_PROJECT_NAMESPACE_FULL_PATH' => @hg_project_for_perms.namespace.full_path
            })
        end

440
441
442
443
        if force_system_user
          # we need a real user for pre-receive hooks to succeed
          # we'll change the display name for clarity, but `id` must
          # match for GitLab to retrieve it in the hooks payload
444
          # (`username` is probably necessary as well)
445
446
447
448
449
450
451
452
          unless sys_user = User.admins.order_id_asc.first
            raise StandardError, "Running with force_system_user, "\
                                 "but no system user found"
          end

          env.update(
            {
              'HGUSER' => 'Heptapod system',
453
              'REMOTE_USER' => nil, # bypass Mercurial permission hooks
454
              'HEPTAPOD_USERINFO_ID' => sys_user.id.to_s,
455
456
              'HEPTAPOD_USERINFO_USERNAME' => sys_user.username,
              'HEPTAPOD_USERINFO_NAME' => "Heptapod system",
457
              'HEPTAPOD_USERINFO_EMAIL' => Gitlab.config.gitlab.email_from
458
459
            }
          )
460
          env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') unless unit_tests_skip_hooks
461
462
        elsif !@hg_project_for_perms.nil?
          env['REMOTE_USER'] =
463
464
465
466
467
468
            if ::Gitlab::UserAccess.new(user, container: @hg_project_for_perms)
                 .hg_can_publish?
              'heptapod-publish'
            else
              'heptapod-write'
            end
469
470
471
        end

        env
472
473
474
      end

      def hg_prepare_user_encoding(hg_env, user, message)
475
        username = "#{user.name} <#{user.email}>"
476
477
478
479
480
481
482
483
484
485
486
        # we take the encoding from one of the two strings
        # it would be very surprising for them to differ, and
        # hg couldn't cope with that anyway (usually, it's UTF8)
        encname = username.encoding.name
        hg_env["HGENCODING"] = encname

        if message.encoding.name != encname
          # this would be very suprising, but if it ever happens
          # people debugging the case will be glad to have this log
          # (Mercurial could cope with that only in cases one of the
          # strings is actually pure ASCII (decoding is trivial)
487
          LOGGER.error("Encoding of commit message #{message.encoding.name} differs "\
488
489
                             "from user name's #{encname}")
        end
490

491
492
493
494
495
496
497
        username
      end

      # Publish a changeset
      #
      # The given `user` information will be passed over to Mercurial
      # in the usual environment variables
498
      def hg_changeset_publish(user, hgsha, notify_gitlab: false, for_mr_iid: nil)
499
        env = hg_env_for_write(user)
500
501
502
503
        unless unit_tests_skip_hooks
          env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') if notify_gitlab
        end

504
        env['HEPTAPOD_ACCEPT_MR_IID'] = for_mr_iid.to_s unless for_mr_iid.nil?
505
        hg_call(['phase', '--public', '-r', hgsha], env: env)
506
507
      end

508
509
510
      # Perform a Mercurial command
      #
      # `args` - list of command arguments for `hg` executable
511
512
513
      # `user` - user object responsible for running the hg command.
      #          Not necessary if `env` is passed nor if `for_write`
      #          is `false`.
514
515
516
517
      # `path` - the working directory path, typically obtained with
      #          `hg_share`.
      #          If not provided or `nil`, the path to the repo (`@hgpath`)
      #          will be used.
518
519
520
521
522
523
      # `env`  - prepared environment variables (useful when using several
      #          times
      # `for_write` - if true, we prepare the env of write access to the
      #               repo store for user. Not necessary for writes to
      #               working directory, nor to dirstate mutations such
      #               as preparing branch or topic for future commits.
524
525
      # `success_code_can_be_one` - flags that success return code for hg command being run, can be 1
      # `force_system_user` - force to use system user over Rails user
526
527
      #
      # return: [output, status]
528
      def hg_call(
529
530
        args,
        user: nil,
531
        path: nil,
532
533
534
535
536
        env: nil,
        for_write: false,
        success_code_can_be_one: false,
        force_system_user: false
      )
537

538
        if env.nil?
539
          env = for_write ? hg_env_for_write(user, force_system_user: force_system_user) : hg_env_minimal
540
        end
541

542
543
544
545
        if path.nil?
          path = @hgpath
        end

546
547
548
549
550
551
552
553
554
555
556
        cmd = [Gitlab.config.mercurial.bin_path] + args
        username =
          if force_system_user
            "Heptapod system"
          elsif !user.nil?
            hg_prepare_user_encoding(env, user, "")
          else
            nil
          end

        unless username.nil?
557
          cmd.append('--config', 'ui.username=' + username)
558
559
        end

560
        output, status = popen(cmd, path, env)
561

562
563
564
565
566
567
568
569
        if status != 0
          if status == 1 && success_code_can_be_one
            # cmd passed with return code 1
          else
            raise HgError, "Command failed (status code #{status}): "\
                           "'#{output}' command was: #{cmd}"
          end
        end
570
571

        [output, status]
572
573
      end

574
575
576
577
      # Perform a Mercurial commit
      #
      # `path` - the working directory path, typically obtained with `hg share`
      # `username` - used as `ui.username`
578
      # `env` - prepared Hash of environment variables
579
580
581
      #
      # returns Mercurial SHA
      def hg_commit(path, username, message, env, add_remove = false)
582
        cmd = ['commit', '--config', 'ui.username=' + username,
583
               '-m', message]
584
        cmd.append('--addremove') if add_remove
585
        hg_call(cmd, env: env, path: path)
586
587
588
        hgsha_from_rev('.', path)
      end

Georges Racinet's avatar
Georges Racinet committed
589
590
591
592
593
594
595
596
597
      # Perform a Mercurial pull
      #
      # `gitlab_branches` - optional Array to make a precise pull, using as
      #     many times `--rev` as needed. The remote revs are to be
      #     given in GitLab branch notation, e.g., as `branch/default`.
      #     If `nil`, a full pull will be performed.
      #     If `[]`, nothing will happen
      # `env` - optionally allows to reuse a precomputed Hash of environment
      #         variables.
598
599
600
      # `force_system_user` - can be set to true to perform with full Mercurial
      #     permissions and allow `user` to be `nil`.
      #     Ignored if `env` is not `nil`
601
602
603
604
      def hg_pull(
        user, remote_url,
        gitlab_branches: nil, env: nil, force_system_user: false
      )
Georges Racinet's avatar
Georges Racinet committed
605
606
        return if gitlab_branches&.empty?

607
        args = ['pull', remote_url]
608

Georges Racinet's avatar
Georges Racinet committed
609
610
        unless gitlab_branches.nil?
          gitlab_branches.each do |glb|
611
612
            args << '--rev'
            args << Gitlab::Mercurial.branchmap_key_for_gitlab_branch(glb)
Georges Racinet's avatar
Georges Racinet committed
613
614
          end
        end
615

616
        unless hg_config_item_bool?('heptapod', 'allow-bookmarks')
617
          args.append('--config', 'heptapod.exchange-ignore-bookmarks=yes')
618
        end
619

620
621
622
623
624
625
        _, status = hg_call(args,
                            force_system_user: force_system_user,
                            user: user,
                            env: env,
                            for_write: true,
                            success_code_can_be_one: true)
626

Georges Racinet's avatar
Georges Racinet committed
627
628
629
630
631
632
633
        if status == 1
          prefix, complements =
            if gitlab_branches.nil?
              ["Full pull", ""]
            else
              ["Partial pull", " for GitLab branches #{gitlab_branches}"]
            end
634

635
          LOGGER.info("#{prefix} from #{remote_url}#{complements} "\
Georges Racinet's avatar
Georges Racinet committed
636
637
                            "retrieved no changeset")
        end
638

639
        hg_git_invalidate_maps!
640
641
642
643

        # there's only one possible field at this point: `divergent_ref` (not
        # really meaningful for hg)
        Gitaly::UpdateRemoteMirrorResponse.new
Georges Racinet's avatar
Georges Racinet committed
644
645
      end

646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
      # Low level method to create a tag.
      #
      # This is *not* meant to be a full override of Git::Repository::tag.
      #
      # Returns the Node ID of the tagging commit.
      #
      # Optional parameters:
      # - env: allows to reuse a Hash of environment variables.
      #        If not specified, the standard one for given user is computed
      # - tag_parent_revision: (tags have to be created on repository heads)
      #        A revision to update the workdir to, before creating the tag.
      #        It will indeed be the parent of the tagging commit.
      def hg_tag(user, tag_name, revision, env: nil, tag_parent_revision: "default")
        env = hg_env_for_write(user) if env.nil?
        username = hg_prepare_user_encoding(env, user, "")
        hg_tmp_workdir(tag_parent_revision) do |share_path|
662
663
          hg_call(['tag', tag_name, '--config', 'ui.username=' + username],
                  path: share_path, env: env)
664
665
666
667
          hgsha_from_rev('.', share_path)
        end
      end

668
669
670
671
      def has_tmp_workdir?(prefix)
        !Dir.glob("#{@hgpath}tmp-#{prefix}-*").empty?
      end

672
673
674
675
676
677
      # Create an independent working directory
      #
      # this relies onto `hg share`, of which that's one of the main use
      # cases.
      #
      # `update_rev`: revision to update the new working directoy to
678
679
      # `prefix`: optional prefix used to check if a share is present
      #           for a given operation.
680
681
      #
      # returns path to the working directory
682
683
684
685
686
      def hg_tmp_workdir(update_rev, prefix: nil)
        share_path = @hgpath + "tmp"
        unless prefix.nil?
          share_path += "-" + prefix + '-'
        end
687

688
        share_path += SecureRandom.hex
689

690
        begin
691
          hg_call(['share', @hgpath, share_path, '--noupdate', '--bookmarks'])
692

693
694
695
696
697
698
699
700
701
702
703
704
705
          %w[hgrc hgrc.managed].each do |fname|
            src_hgrc_path = File.join(@hgpath, '.hg', fname)
            if File.exist?(src_hgrc_path)
              # FileUtils.copy_file happily overrides any existing file,
              # and is just what FileUtils.cp calls in its loop (but `cp`
              # for both files would expect them both to exist)
              FileUtils.copy_file(src_hgrc_path,
                                  File.join(share_path, '.hg', fname))
            end
          rescue StandardError => exc
            raise HgError, "Could not copy HGRC file .hg/#{fname} from #{@hgpath} to #{share_path}: #{exc.message}"
          end

706
          unless update_rev.nil?
707
            hg_call(['up', update_rev], path: share_path)
708
          end
709
710
711
712

          yield share_path

        ensure
713
          FileUtils.rm_rf(share_path)
714
715
716
717
718
719
720
721
722
723
        end
      end

      # Produce a Mercurial merge changeset
      #
      # This method works with Mercurial SHAs only, and performs `merge` and `commit` in
      # insulation, by working in a temporary repository created with `share`.
      #
      # For `hg_git` repositories, the resulting writes to the Git repository are
      # protected by the Mercurial store lock, which is always held on the share source.
724
725
      def hg_merge_changeset(
        user, source_hgsha, target_hgsha, message,
726
727
        simulate = false,
        semi_linear: false
728
      )
729
730
731
732
        logprefix = "hg_merge_changeset "
        logprefix += "simulation " if simulate
        logprefix += "for #{@relative_path} #{source_hgsha} into #{target_hgsha}"
        hg_exe = Gitlab.config.mercurial.bin_path
733
734
        hg_env =
          if user.nil?
735
            hg_env_minimal
736
737
738
739
          else
            hg_env_for_write(user)
          end

740
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') unless unit_tests_skip_hooks
741

742
        hg_tmp_workdir(target_hgsha) do |share_path|
743
          LOGGER.info("#{logprefix} calling #{hg_exe} merge -r #{source_hgsha}")
744
745
746
747
748
749
750
751
752
753
754
755
756
          cmd = [hg_exe, 'merge',
                 '-t', 'internal:merge3',
                 '-r', source_hgsha]

          if semi_linear
            cmd.concat(
              [
                '--config',
                'experimental.topic.linear-merge=allow-from-bare-branch'
              ])
          end

          output, status = popen(cmd, share_path, hg_env)
757

758
759
760
761
          if status != 0
            raise MergeError, "Could not merge hg #{source_hgsha} onto hg #{target_hgsha}: #{output}"
          end

762
          next if simulate
763
764
765

          username = hg_prepare_user_encoding(hg_env, user, message)
          commit_hgsha = hg_commit(share_path, username, message, hg_env)
766
767
          LOGGER.info("#{logprefix} merge done, "\
                      "final changeset is #{commit_hgsha}")
768
          commit_hgsha
769
770
771
        end
      end

772
773
      # A temporary protection against unwanted publication, see heptapod#284.
      def forbid_merge_in_topic(target_branch)
774
775
        target_topic = Gitlab::Mercurial.parse_gitlab_branch_for_hg(
          target_branch)[1]
776
777
778
        raise ArgumentError, "Merge Requests targeting topics aren't supported yet" unless target_topic.nil?
      end

779
      override :merge
780
      def merge(user, source_sha, target_branch, message, for_mr_iid: nil, hg_semi_linear: false)
781
782
        logprefix = "hg_merge for #{@relative_path} "\
                    "source_sha=#{source_sha} target_branch=#{target_branch}"
783
        forbid_merge_in_topic(target_branch)
784
        LOGGER.info("#{logprefix} starting")
785

786
        target_sha = find_branch(target_branch).target
787

788
789
        raise 'Invalid merge target' unless target_sha
        raise 'Invalid merge source' unless source_sha
790

791
792
793
794
795
796
797
798
799
800
801
        source_hgsha = hgsha_from_sha(source_sha)
        target_hgsha = hgsha_from_sha(target_sha)
        begin
          target_hg_branch = hg_changeset_branch(target_hgsha)
          source_hg_branch = hg_changeset_branch(source_hgsha)
        rescue HgError => e
          raise MergeError, e.message
        end
        same_branches = target_hg_branch == source_hg_branch
        if hg_semi_linear
          raise MergeError, 'Cannot fast-forward' unless ancestor?(target_sha, source_sha) && same_branches
802

803
804
805
806
807
808
809
810
811
812
813
          with_merge_changeset = true
        else
          with_merge_changeset = !(same_branches && ancestor?(target_sha, source_sha))
        end

        result_hgsha =
          if with_merge_changeset
            hg_merge_changeset(user, source_hgsha, target_hgsha, message, semi_linear: hg_semi_linear)
          else
            LOGGER.info("#{logprefix} this is a merge without merge changeset")
            source_hgsha
814
815
          end

816
817
818
819
820
821
822
823
        LOGGER.info("#{logprefix} publishing changeset #{result_hgsha}")
        begin
          hg_changeset_publish(user, result_hgsha, notify_gitlab: true, for_mr_iid: for_mr_iid)
        rescue HgError => e
          raise MergeError, e.message
        end

        LOGGER.info("#{logprefix} merge done, final changeset is #{result_hgsha}")
824

825
826
827
828
829
830
        hg_git_invalidate_maps!
        commit_id = sha_from_hgsha result_hgsha

        yield commit_id

        Gitlab::Git::OperationService::BranchUpdate.new(commit_id, false, false)
831
832
833
834
835

      rescue Gitlab::Git::CommitError # when merge_index.conflicts?
        nil
      end

836
      override :can_be_merged?
837
      def can_be_merged?(source_sha, target_branch)
838
839
        target_topic = Gitlab::Mercurial.parse_gitlab_branch_for_hg(
          target_branch)[1]
840
841
        return false unless target_topic.nil?

842
843
844
845
846
847
        logprefix = "Mercurial.can_be_merged? for #{@relative_path} "\
                    "source_sha=#{source_sha} target_branch=#{target_branch}"

        return false unless source_sha

        target_sha = find_branch(target_branch)&.target
848

849
        if target_sha.nil?
850
          LOGGER.warn("#{logprefix} could not resolve Git branch #{target_branch}")
851
852
          return false
        end
853

854
855
856
        if ancestor?(target_sha, source_sha)
          # always doable: true fast forward or merge changeset only
          # involving metadata (e.g., branch change)
857
          LOGGER.info("#{logprefix} is mergeable (direct ancestor)")
858
859
860
861
862
          return true
        end

        source_hgsha = hgsha_from_sha(source_sha)
        target_hgsha = hgsha_from_sha(target_sha)
863

864
        if source_hgsha.nil?
865
          LOGGER.warn(
866
867
868
            "#{logprefix} could not find Hg changeset for source Git commit #{source_sha}")
          return false
        end
869

870
        if target_hgsha.nil?
871
          LOGGER.warn(
872
873
874
875
876
877
            "#{logprefix} could not find Hg changeset for target Git commit #{target_sha}")
          return false
        end

        begin
          hg_merge_changeset(nil, source_hgsha, target_hgsha, nil, true)
878
          LOGGER.info("#{logprefix} is mergeable (true merge)")
879
880
          true
        rescue HgError, MergeError => e
881
          LOGGER.info("#{logprefix} not mergeable: #{e.class}, #{e.message}")
882
883
884
885
          false
        end
      end

886
      override :ff_merge
887
      def ff_merge(user, source_sha, target_branch, for_mr_iid: nil)
888
889
        forbid_merge_in_topic(target_branch)

890
        source_hgsha = hgsha_from_sha(source_sha)
891
892
893
        raise ArgumentError, 'Invalid merge target' unless find_branch(target_branch).target

        hg_branch = begin
894
895
896
897
          hg_changeset_branch(source_hgsha)
        rescue HgError => e
          raise MergeError, e.message
        end
898
899
900
901
902
903
904
905
906

        if target_branch != "branch/" + hg_branch
          # TODO how to return the proper error 406 seen from API?
          raise MergeError, "Being on branch #{hg_branch}, "\
                            "changeset #{source_hgsha} cannot be published "\
                            "within #{target_branch}"
        end

        begin
907
908
          hg_changeset_publish(user, source_hgsha, notify_gitlab: true,
                               for_mr_iid: for_mr_iid)
909
910
911
912
913
914
915
916
917
        rescue HgError => e
          raise MergeError, e
        end

        Gitlab::Git::OperationService::BranchUpdate.new(source_sha, false, false)
      rescue Gitlab::Git::CommitError
        nil
      end

918
      override :squash
919
920
921
922
923
      # Squash a linear range of changesets.
      #
      # In typical usage (merge requests), start_sha is ill-named:
      # it is the head of the target branch (perhaps not really the head any
      # more).
924
      def squash(user, start_sha:, end_sha:, author:, message:)
925
926
927
928
929
930
931
932
        logprefix = "hg_squash "
        hg_exe = Gitlab.config.mercurial.bin_path
        hg_env = hg_env_for_write(user)

        start_hgsha = hgsha_from_sha(start_sha)
        end_hgsha = hgsha_from_sha(end_sha)
        username = hg_prepare_user_encoding(hg_env, author, message)

933
        hg_tmp_workdir(nil, prefix: "squash") do |share_path|
934
935
936
937
938
939
940
941
          # TODO: gracinet not 100% sure we need a workdir, but I don't see
          # an explicit "inmemory" option as there is for `hg rebase`

          # If we update to target_hgsha, then the fold will look like
          # an extra head and be rejected (probably because it is kept active by being the
          # working dir parent). Let's not update anywhere.
          revset = "ancestor(#{start_hgsha}, #{end_hgsha})::#{end_hgsha} "\
                   "- ancestor(#{start_hgsha}, #{end_hgsha})"
942
          LOGGER.info("#{logprefix} calling `hg squash --exact` "\
943
944
945
946
947
948
949
950
951
952
                      "on revset `#{revset}` #{message.nil?} for #{username}")
          # Note that hg fold --exact will fail unless the revset is
          # "an unbroken linear chain". That fits the idea of a Merge Request
          # neatly, and should be unsuprising to users: it's natural to expect
          # squashes to stay simple.
          # In particular, if there's a merge of a side topic, it will be
          # unsquashable.
          # `allowunstable=no` protects us against all instabilities,
          # in particular against orphaning dependent topics.
          output, status = popen(
953
954
955
956
957
958
959
            [hg_exe, 'fold', '--exact',
             '-r', revset,
             '-m', message,
             '-u', username,
             '--config', 'experimental.evolution.allowunstable=no'],
            share_path, hg_env)

960
961
962
          if status != 0
            raise HgError, "Could not fold revset `#{revset}` Error: #{output}"
          end
963

964
          LOGGER.info("#{logprefix} squash done, finding successor")
965
          output, status = popen(
966
967
968
            [hg_exe, 'hpd-unique-successor', '-r', end_hgsha],
            share_path, hg_env)

969
970
971
972
          if status != 0
            raise HgError, "Could not retrieve folded changeset "\
                           "(successor of #{end_hgsha})"
          end
973

974
          squash_hgsha = output.strip
975
          LOGGER.info("#{logprefix} squash successor changeset #{squash_hgsha}")
976
977
978
979
980
981

          hg_git_invalidate_maps!
          sha_from_hgsha(squash_hgsha)
        end
      end

Georges Racinet's avatar
Georges Racinet committed
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
      def hg_bundle_path(git_bundle_path)
        git_bundle_path.sub(/\.bundle$/, '.hg.bundle')
      end

      # Heptapod 0.18 note: in GitLab, restoration has to be made
      # with the exact same version.
      # We may therefore change (compared to 0.17) the inner path to better
      # suit current Heptapod.
      def hg_backup_config_path(git_bundle_path)
        git_bundle_path.sub(/\.bundle$/, '.hg.config.tar')
      end

      override :bundle_to_disk
      # param `save_path`: the save_path *if it were a Git repo*
      # actual paths for Mercurial (bundle and config) are deduced from it
      # In the changes for GitLab 13.5 (Heptapod 0.18), we chose
      # to include the dump of state and configuration that aren't
      # in the bundle by this method for uniformity of the caller, even
      # though is is semantically poor: thanks to this we don't need anything
      # Heptapod-specific in Backup:Repositories
      def bundle_to_disk(save_path)
        super(save_path)
1004
1005
        hg_bundle_to_disk(save_path)
      end
Georges Racinet's avatar
Georges Racinet committed
1006

1007
      def hg_bundle_to_disk(save_path)
1008
        FileUtils.mkdir_p(Pathname.new(save_path).parent)
1009
        hg_call(["bundle", "--all", '--hidden', hg_bundle_path(save_path)],
1010
                force_system_user: true)
1011
        backup_additional(save_path)
1012
        true
Georges Racinet's avatar
Georges Racinet committed
1013
1014
      end

1015
      # Backup data (config and state) that is not part of the bundle
1016
1017
1018
      # TODO provide a command in py-heptapod and/or include state files in
      # order for it to stay close to the definitions, and have an easy
      # way to test thoroughly
1019
      def backup_additional(save_path)
1020
1021
1022
        output, status = hg_call(["hpd-backup-additional",
                                  hg_backup_config_path(save_path)],
                                 force_system_user: true)
Georges Racinet's avatar
Georges Racinet committed
1023
1024
1025
1026
1027
1028
1029
1030
        raise StandardError, output.strip unless status == 0
      end

      override :create_from_bundle
      # param `path_to_bundle`: the bundle to restore *if it were a Git repo*
      # actual paths for Mercurial (bundle and config) are deduced from it
      # See also doc-comment for #bundle_to_disk.
      def create_from_bundle(path_to_bundle)
1031
        super(path_to_bundle)
1032
1033
        hg_create_from_bundle(path_to_bundle)
      end
1034

1035
      def hg_create_from_bundle(path_to_bundle)
1036
1037
1038
1039
        # same path used as cwd as in hg_create_repository()
        # we don't know namespace arguments that would be used to
        # call the latter, but it doesn't matter, since all config will
        # be restored
1040
1041
        hg_call(["init", @hgpath],
                path: @hg_storage_root,
1042
                for_write: true, force_system_user: true)
1043
        restore_additional(path_to_bundle)
1044
        hg_call(["unbundle", hg_bundle_path(path_to_bundle)],
1045
                for_write: true, force_system_user: true)
Georges Racinet's avatar
Georges Racinet committed
1046
1047
      end

1048
1049
      # Restore additional files (config and state) that are not part of bundle
      def restore_additional(path_to_bundle)
1050
1051
1052
        output, status = hg_call(["hpd-restore-additional",
                                  hg_backup_config_path(path_to_bundle)],
                                 force_system_user: true)
Georges Racinet's avatar
Georges Racinet committed
1053
1054
1055
        raise StandardError, output.strip unless status == 0
      end

1056
      override :rebase
Georges Racinet's avatar
Georges Racinet committed
1057
1058
1059
1060
1061
1062
1063
1064
      # Perform a rebase, only for topics.
      #
      # We may be subject to the same race condition than explained in
      # https://gitlab.com/gitlab-org/gitlab/-/issues/5966#note_150894306
      # in short, there's a chance that the PostReceive gets executed
      # before the resulting commit is written in the database.
      # That's the kind of thing we will be able to fix once these
      # methods are reimplemented in HGitaly (should be after Heptapod 1.0)
1065
1066
1067
1068
      def rebase(
        user, rebase_id, branch:, branch_sha:,
        remote_repository:, remote_branch:, push_options: [])

Georges Racinet's avatar
Georges Racinet committed
1069
1070
        logprefix = "hg_rebase for #{@relative_path} of git #{branch_sha} "\
                    "(branch #{branch}) onto #{remote_branch}"
1071
1072
1073
1074
1075

        unless remote_repository == self
          raise StandardError, "Rebasing between two different repos is not "\
                               "supported"
        end
Georges Racinet's avatar
Georges Racinet committed
1076

1077
        topic = Gitlab::Mercurial.parse_gitlab_branch_for_hg(branch)[1]
Georges Racinet's avatar
Georges Racinet committed
1078
1079
1080
1081
1082
1083
        raise HgError, "Only topics can be rebased" if topic.nil?

        hg_exe = Gitlab.config.mercurial.bin_path
        hg_env = hg_env_for_write(user)
        # we need to notify GitLab: the merge request update is done at
        # the receiving end of the post-receive hook
1084
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') unless unit_tests_skip_hooks
Georges Racinet's avatar
Georges Racinet committed
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106

        # don't see an option to rebase with an obsmarker note
        username = hg_prepare_user_encoding(hg_env, user, "")

        end_hgsha = hgsha_from_sha(branch_sha)
        raise HgError, "Could not find hg changeset for Git #{branch_sha}" if end_hgsha.nil?

        # For consistency in corner cases (multiple heads) let's query the
        # Git sha for the target branch, even though we could also parse
        # and use Mercurial
        dest_sha = find_branch(remote_branch)&.target
        dest_hgsha = hgsha_from_sha(dest_sha)
        raise HgError, "Could not find hg changeset for Git #{branch_sha}" if dest_hgsha.nil?

        # revset insisting on using branch_sha because
        # - the topic could actually span several named branches (we could also
        #   use the branch knowledge)
        # - if branch_sha is not the branch/topic head, that means something
        #   is wrong. Instead of rebasing the whole, let's have the error
        #   we get by refusing instabilities
        # topic naming rules make sure that we need no escaping
        revset = "topic(#{topic}) and ::#{end_hgsha}"
1107
        rebase_hgsha =
Georges Racinet's avatar
Georges Racinet committed
1108
1109
1110
1111
          # TODO would be nice to experiment with in-memory rebase (wouldn't
          # need a working dir) but not sure what the good use cases are.
          # For instance, is a small rebase on a big repo much more efficient
          # in memory or should that precisely be avoided?
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
          hg_tmp_workdir(nil, prefix: "rebase-#{rebase_id}") do |share_path|
            # `allowunstable=no` protects us against all instabilities,
            # in particular against orphaning dependent topics.
            output, status = popen(
              [hg_exe, 'rebase',
               '-r', revset,
               '-d', dest_hgsha,
               '--tool', 'internal:merge3',
               # extension activation should also end up in py-heptapod's
               # required.hgrc, but let's make it work straight away
               '--config', 'extensions.rebase=',
               '--config', 'rebase.singletransaction=yes',
               '--config', 'experimental.evolution.allowunstable=no',
               '--config', 'ui.username=' + username],
              share_path, hg_env)

            if status != 0
              raise HgError, "Could not rebase revset `#{revset}` "\
                             "onto #{dest_hgsha} Error: #{output}"
            end
Georges Racinet's avatar
Georges Racinet committed
1132

1133
            LOGGER.info("#{logprefix} rebase done, finding successor")
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144

            output, status = popen(
              [hg_exe, 'hpd-unique-successor', '-r', end_hgsha],
              share_path, hg_env)

            if status != 0
              raise HgError, "Could not retrieve topic head after rebase "\
                             "(successor of #{end_hgsha})"
            end

            output.strip
Georges Racinet's avatar
Georges Racinet committed
1145
1146
1147
1148
          end

        hg_git_invalidate_maps!
        rebase_sha = sha_from_hgsha(rebase_hgsha)
1149
        LOGGER.info("#{logprefix} rebase successor changeset #{rebase_hgsha} "\
Georges Racinet's avatar
Georges Racinet committed
1150
1151
1152
1153
1154
1155
                    "(git sha #{rebase_sha})")

        yield rebase_sha
        rebase_sha
      end

1156
      override :rebase_in_progress
Georges Racinet's avatar
Georges Racinet committed
1157
1158
1159
      # first approx, but it'd be better to have a way to tell
      # TODO use rebase_id in tmp workdir name (same for squash)
      def rebase_in_progress?(rebase_id)
1160
        has_tmp_workdir?("rebase-#{rebase_id}")
Georges Racinet's avatar
Georges Racinet committed
1161
1162
      end

1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
      # Pull a given revision from URL forcing topic on all new changesets
      #
      # Return:
      #   [full node, branch name, topic name]
      #
      # It is not guaranteed that the returned full node carries the given
      # topic. This happens for instance if it was already known and public.
      # In that case, the returned topic is empty
      def pull_force_topic(url, hgsha, topic)
        # necessary to amend changesets
        # TODO do better and think of encoding, as well
1174
1175
1176
        hg_env = hg_env_minimal
        hg_env.update({ 'HGUSER' => 'Heptapod system',
                        'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes' })
1177
        hg_exe = Gitlab.config.mercurial.bin_path
1178
1179
1180
1181
1182
1183
1184
1185
1186
        _output, status = popen([
           hg_exe,
           'pull-force-topic', '-q', '-r', hgsha, topic, url,
           '--config', 'experimental.single-head-per-branch=no',
           '--config', 'topic.publish-bare-branch=no',
           '--config', 'experimental.hg-git.accept-slash-in-topic-name=yes',
           '--config', 'experimental.hg-git.bookmarks-on-named-branches= yes'
           ],
           @hgpath, hg_env)
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197

        if status == 1
          query_rev = hgsha
        elsif status != 0
          raise StandardError, "Could not pull-force-topic #{hgsha} from #{url}"
        else
          query_rev = topic
        end

        hg_git_invalidate_maps!
        node_branch, status = popen(
1198
1199
1200
1201
          [hg_exe, 'log', '-T', '{node}:{branch}:{topic}', '-r', query_rev],
          @hgpath, hg_env
        )

1202
1203
1204
        if status != 0
          raise HgRevisionError, "Could not log revision #{query_rev}"
        end
1205

1206
1207
1208
        node_branch.split(':')
      end

1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
      def write_file(abspath, content)
        if content.is_a?(UploadedFile)
          # TODO mv would be more efficient, but it's unclear how much the
          # UploadedFile would be then broken and whether it matters.
          # (probably not much, the tempfile is an open file anyway).
          # Another option if on same FS (case where mv is efficient)
          # would be to make a hardlink. Playing safe for now.
          FileUtils.cp(content.path, abspath)
        else
          # File.write uses text mode, which forces conversion to
          # Encoding.external_encoding ('UTF-8') and gives an error.
          # On the other hand, a file explicitely open in binary mode
          # is happy to receive an UTF-8 string
          File.open(abspath, "wb") do |f|
            f.write(content)
          end
        end
      end

1228
      override :multi_action
1229
1230
1231
      # perform multiple write actions in the repository in a single commit
      #
      # typically multiple file writes or renames, followed by a commit
1232
1233
1234
1235
1236
1237
      #
      # actions details (should be the same as with Git::Repository):
      #
      # - create: ensures there's not a file at the same `file_path` already
      #           and take care of intermediate directories
      # - update: ensures the file at `file_path` already exists.
1238
1239
1240
      # rubocop:disable Metrics/ParameterLists
      def multi_action(
        user, branch_name:, message:, actions:,
1241
        author_email: nil, author_name: nil,
1242
1243
1244
1245
        start_branch_n