hg_git_repository.rb 49.8 KB
Newer Older
1

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

10
11
12
module Gitlab
  module Mercurial
    class HgGitRepository < Gitlab::Git::Repository
13
      include Gitlab::Popen
14

15
      attr_accessor :unit_tests_skip_hooks
16
      attr_writer :hg_project_for_perms
17

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

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
      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>",
        ""].join("\n").freeze

      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",
        ""].join("\n").freeze

52
53
54
55
56
      def initialize(*args)
        super(*args)
        @hg_relative_path = relative_path.sub(/\.git$/, '.hg')
        @hg_storage_root = Gitlab.config.repositories.storages.fetch(storage).hg_disk_path
        @hgpath = File.join(@hg_storage_root, @hg_relative_path)
57
58
59
60
61
62
63

        # `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
64
65
66
67
68
69
70
      end

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

71
72
73
74
75
76
77
78
79
80
81
82
83
      def hg_config_item_bool?(full_dotted_name)
        env = { 'HGRCPATH' => Gitlab::Mercurial.hgrc_path }
        val_str, status = popen(
                   [Gitlab.config.mercurial.bin_path,
                    'config', full_dotted_name],
                   @hgpath, env)
        return false if status == 1  # status 1 means value is missing

        raise HgError, "Could not read `#{full_dotted_name}` config item for #{@hgpath}" unless status == 0

        HG_CONFIG_TRUE.include?(val_str.downcase.strip)
      end

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
      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:)
        Rails.logger.info(
          "Creating Mercurial repository at #{@hg_relative_path} "\
          "namespace path=#{namespace_fs_path} "\
          "in_subgroup: #{in_subgroup}")
        begin
          out, status = popen(
                 [Gitlab.config.mercurial.bin_path, "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:
                 @hg_storage_root,
                 { 'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                 })
          if status != 0
            raise HgError, "Could not execute `hg init` for #{@hgpath}: #{out}"
          end

          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)
            end
          end
        end
        true
      rescue => err
        Rails.logger.error("Failed to add Mercurial repository for #{storage}/#{name}: #{err}")
        false
      end

135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
      def import_repository(url, **create_args)
        raise ArgumentError, "don't use disk paths with import_repository: "\
                             "#{url.inspect}" if url.start_with?('.', '/')

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

        hg_exe = Gitlab.config.mercurial.bin_path
        hg_env = {'HGUSER' => 'Heptapod system',
                  'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes',
                  'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                 }
        Rails.logger.info("#{logprefix} Pulling")
        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
          unless $?.exitstatus.zero?
            msg = "#{logprefix} import failed"
            Rails.logger.error(msg)
            raise HgError, msg
          end
        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
          Rails.logger.error("#{logprefix} Post import optimization "\
                             "failed: #{err}")
        end
      end

      # Perform Mercurial repository optimizations
      #
      # See heptapod#192 for details about implications of various options
      def hg_optim
        hg_env = {'HGUSER' => 'Heptapod system',
                  'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes',
                  'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                 }
        output, status = popen(
                  [Gitlab.config.mercurial.bin_path,
                   "debugupgraderepo",
                   '-o', 're-delta-all',
                   '--run',
                   '--no-backup',
                  ], @hgpath, hg_env)
        unless status.zero?
          raise HgError, "Optimization failed for #{@hgpath}: " + output
        end
      end

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
      # Run `hg recover`.
      # This is idempotent and reasonably fast if there's nothing to recover
      def hg_recover
        hg_env = {'HGUSER' => 'Heptapod system',
                  'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes',
                  'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                 }
        output, status = popen(
                  [Gitlab.config.mercurial.bin_path,
                   "recover",
                  ], @hgpath, hg_env)
        # as usual with hg, code 1 means there's nothing to do
        unless [0, 1].include?(status)
          raise HgError, "`hg recover` failed for #{@hgpath}: " + output
        end
      end

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
      def rename(new_git_relative_path)
        super(new_git_relative_path)
        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

242
243
244
245
246
      def remove
        super
        FileUtils.rm_rf(@hgpath)
      end

247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
      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

      # Return repo size in megabytes (same as `super` as of this writing)
      def size
        super + hg_size
      end

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
      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|
          f.map do |line|
            line.match(/^([0-9a-f]{40}) ([0-9a-f]{40})\n$/) do |match|
              [match[1], match[2]]
            end
          end
          .to_h
        end
      end

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

      def sha_from_hgsha(hgsha)
        return nil unless exists?

        git_sha_map[hgsha]
      end

      def hgsha_from_sha(sha)
        return nil unless exists?

        hg_sha_map[sha]
      end

      def hg_git_invalidate_maps!
        @git_sha_map = nil
        @hg_sha_map = nil
      end

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
      # 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)
        hg_env = {'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                 }

        path = @hgpath if path.nil?
        sha, status = popen([Gitlab.config.mercurial.bin_path,
                             'log', '--limit', '1', '-r', hgrev,
                             '-T', '{node}'],
                            path, hg_env)
        if status != 0
          raise HgRevisionError,
                "Could not find changeset #{hgrev} in #{@hgpath}"
        end
        sha
      end

      # Find the named branch of a Mercurial changeset
      def hg_changeset_branch(hgsha)
        out, status = popen([Gitlab.config.mercurial.bin_path,
                             'log', '-r', hgsha, '-T', '{branch}'],
                            @hgpath,
                            {'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                            })
        if status != 0
          raise HgError, "Could not get hg branch of changeset #{hgsha}: #{out}"
        end
        out.strip
      end

333
      # TODO deprecated compatibility alias, replaced by direct calls
334
      def parse_gitlab_branch_for_hg(gitlab_branch)
335
        Gitlab::Mercurial.parse_gitlab_branch_for_hg(gitlab_branch)
336
337
338
339
340
341
342
343
344
345
      end

      def hg_branchmap_branch(hg_branch, topic)
        if topic.nil?
          hg_branch
        else
          "#{hg_branch}:#{topic}"
        end
      end

346
347
      # Return a suitable environment for write operations (merge etc.)
      def hg_env_for_write(user)
348
349
350
351
352
353
354
355
356
        hg_perm_user =
          if @hg_project_for_perms.nil?
            nil
          else
            access = ::Gitlab::UserAccess.new(user,
                                              project: @hg_project_for_perms)
            access.hg_can_publish? ? 'heptapod-publish' : 'heptapod-write'
          end

357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
        {
          # `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.
          # Of that later information would change for any reason
          # these would still be directly linked to authenticated
          # user info
          'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => "yes",
          'HEPTAPOD_USERINFO_ID' => user.id.to_s,
          'HEPTAPOD_USERINFO_USERNAME' => user.username,
          'HEPTAPOD_USERINFO_NAME' => user.name,
          'HEPTAPOD_USERINFO_EMAIL' => user.email,
          'GL_REPOSITORY' => @gl_repository,  # for Heptapod 0.13
          # for Heptapod 0.12:
          'HEPTAPOD_PROJECT_ID' => @gl_repository.rpartition('-')[-1],
          'HEPTAPOD_PROJECT_PATH' => self.name.chomp('.git'),
          # TODO won't work on hashed storage
          'HEPTAPOD_PROJECT_NAMESPACE_FULL_PATH' => @relative_path.rpartition('/')[0],
          'HGUSER' => nil,
377
          'REMOTE_USER' => hg_perm_user,
378
379
380
381
382
          'HGRCPATH' => Gitlab::Mercurial.hgrc_path
        }
      end

      def hg_prepare_user_encoding(hg_env, user, message)
383
        username = "#{user.name} <#{user.email}>"
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
        # 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)
          Rails.logger.error("Encoding of commit message #{message.encoding.name} differs "\
                             "from user name's #{encname}")
        end
        username
      end

      # Publish a changeset
      #
      # The given `user` information will be passed over to Mercurial
      # in the usual environment variables
      def hg_changeset_publish(user, hgsha, notify_gitlab: false)
        env = hg_env_for_write(user)
407
        env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') if notify_gitlab && !unit_tests_skip_hooks
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
        out, status = popen([Gitlab.config.mercurial.bin_path,
                             'phase', '--public', '-r', hgsha],
                            @hgpath, env)
        raise HgError, "Could not publish changeset #{hgsha}: #{out}" unless status.zero?
      end

      # Perform a Mercurial commit
      #
      # `path` - the working directory path, typically obtained with `hg share`
      # `username` - used as `ui.username`
      # `env` - preparred Hash of environment variables
      #
      # returns Mercurial SHA
      def hg_commit(path, username, message, env, add_remove = false)
        cmd = [Gitlab.config.mercurial.bin_path, 'commit',
423
424
               '--config', 'ui.username=' + username,
               '-m', message]
425
426
        cmd.append('--addremove') if add_remove
        output, status = popen(cmd, path, env)
427
        raise HgError, "Could not commit (status code #{status}): #{output}" if status != 0
428
429
430
431

        hgsha_from_rev('.', path)
      end

432
433
434
435
      def has_tmp_workdir?(prefix)
        !Dir.glob("#{@hgpath}tmp-#{prefix}-*").empty?
      end

436
437
438
439
440
441
      # 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
442
443
      # `prefix`: optional prefix used to check if a share is present
      #           for a given operation.
444
445
      #
      # returns path to the working directory
446
447
448
449
450
451
      def hg_tmp_workdir(update_rev, prefix: nil)
        share_path = @hgpath + "tmp"
        unless prefix.nil?
          share_path += "-" + prefix + '-'
        end
        share_path += SecureRandom.hex
452

453
454
455
456
457
458
459
460
461
        begin
          hg_exe = Gitlab.config.mercurial.bin_path
          env = { 'HGRCPATH' => Gitlab::Mercurial.hgrc_path }
          output, status = popen([hg_exe, 'share',
                                  @hgpath, share_path,
                                  '--noupdate', '--bookmarks'],
                                 nil, env)
          raise HgError, "Could not share repo at #{@hgpath} to #{share_path}: #{output}" if status != 0

462
463
464
465
466
467
468
469
470
471
472
473
474
          %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

475
476
477
478
          unless update_rev.nil?
            output, status = popen([hg_exe, 'up', update_rev], share_path, env)
            raise HgError, "Could not update shared repo to #{update_rev}: #{output}" if status != 0
          end
479
480
481
482

          yield share_path

        ensure
483
          FileUtils.rm_rf(share_path)
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        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.
      def hg_merge_changeset(user, source_hgsha, target_hgsha, message,
                             simulate = false)
        logprefix = "hg_merge_changeset "
        logprefix += "simulation " if simulate
        logprefix += "for #{@relative_path} #{source_hgsha} into #{target_hgsha}"
        logger = Rails.logger  # could need to be adapted for gitaly-ruby (see initialize())
        hg_exe = Gitlab.config.mercurial.bin_path
        hg_env = if user.nil?
                   # TODO time to have a method for minimal hg_env
                   {'HGRCPATH' => Gitlab::Mercurial.hgrc_path}
                 else
                   hg_env_for_write(user)
                 end
507
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') unless unit_tests_skip_hooks
508

509
        hg_tmp_workdir(target_hgsha) do |share_path|
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
          logger.info("#{logprefix} calling #{hg_exe} merge -r #{source_hgsha}")
          output, status = popen([hg_exe, 'merge',
                                  '-t', 'internal:merge3',
                                  '-r', source_hgsha
                                 ],
                                 share_path, hg_env)
          if status != 0
            raise MergeError, "Could not merge hg #{source_hgsha} onto hg #{target_hgsha}: #{output}"
          end

          # note for non-rubyists: 'ensure' condition is still executed
          # with early returns.
          return if simulate

          username = hg_prepare_user_encoding(hg_env, user, message)
          commit_hgsha = hg_commit(share_path, username, message, hg_env)
          logger.info("#{logprefix} merge done, final changeset is #{commit_hgsha}")
527
          commit_hgsha
528
529
530
        end
      end

531
532
533
534
535
536
      # A temporary protection against unwanted publication, see heptapod#284.
      def forbid_merge_in_topic(target_branch)
        target_topic = parse_gitlab_branch_for_hg(target_branch)[1]
        raise ArgumentError, "Merge Requests targeting topics aren't supported yet" unless target_topic.nil?
      end

537
538
539
540
      def merge(user, source_sha, target_branch, message)
        logprefix = "hg_merge for #{@relative_path} "\
                    "source_sha=#{source_sha} target_branch=#{target_branch}"
        logger = Rails.logger  # could need to be adapted for gitaly-ruby (see initialize())
541
        forbid_merge_in_topic(target_branch)
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
        logger.info("#{logprefix} starting")

        begin
          target_sha = find_branch(target_branch).target

          raise 'Invalid merge target' unless target_sha
          raise 'Invalid merge source' unless source_sha

          begin
            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

            with_merge_changeset =
              (target_hg_branch != source_hg_branch) || !(ancestor?(target_sha, source_sha))

            result_hgsha =
              if with_merge_changeset
                hg_merge_changeset(user, source_hgsha, target_hgsha, message)
              else
                logger.info("#{logprefix} this is a merge without merge changeset")
                source_hgsha
              end

            logger.info("#{logprefix} publishing changeset #{result_hgsha}")
            begin
              hg_changeset_publish(user, result_hgsha, notify_gitlab: true)
            rescue HgError => e
              raise MergeError, e.message
            end

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

          hg_git_invalidate_maps!
          commit_id = sha_from_hgsha result_hgsha

          yield commit_id

          Gitlab::Git::OperationService::BranchUpdate.new(commit_id, false, false)

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

      def can_be_merged?(source_sha, target_branch)
594
595
596
        target_topic = parse_gitlab_branch_for_hg(target_branch)[1]
        return false unless target_topic.nil?

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
        logprefix = "Mercurial.can_be_merged? for #{@relative_path} "\
                    "source_sha=#{source_sha} target_branch=#{target_branch}"
        logger = Rails.logger  # could need to be adapted for gitaly-ruby (see initialize())

        return false unless source_sha

        target_sha = find_branch(target_branch)&.target
        if target_sha.nil?
          logger.warn("#{logprefix} could not resolve Git branch #{target_branch}")
          return false
        end
        if ancestor?(target_sha, source_sha)
          # always doable: true fast forward or merge changeset only
          # involving metadata (e.g., branch change)
          logger.info("#{logprefix} is mergeable (direct ancestor)")
          return true
        end

        source_hgsha = hgsha_from_sha(source_sha)
        target_hgsha = hgsha_from_sha(target_sha)
        if source_hgsha.nil?
          logger.warn(
            "#{logprefix} could not find Hg changeset for source Git commit #{source_sha}")
          return false
        end
        if target_hgsha.nil?
          logger.warn(
            "#{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)
          logger.info("#{logprefix} is mergeable (true merge)")
          true
        rescue HgError, MergeError => e
          logger.info("#{logprefix} not mergeable: #{e.class}, #{e.message}")
          false
        end
      end

      def ff_merge(user, source_sha, target_branch)
639
640
        forbid_merge_in_topic(target_branch)

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
        source_hgsha = hg_sha_map[source_sha]
        raise ArgumentError, 'Invalid merge target' unless find_branch(target_branch).target

        hg_branch = begin
                      hg_changeset_branch(source_hgsha)
                    rescue HgError => e
                      raise MergeError, e.message
                    end

        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
          hg_changeset_publish(user, source_hgsha, notify_gitlab: true)
        rescue HgError => e
          raise MergeError, e
        end

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

      # 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).
673
      def squash(user, squash_id, start_sha:, end_sha:, author:, message:)
674
675
676
677
678
679
680
681
682
        logprefix = "hg_squash "
        logger = Rails.logger
        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)

683
        hg_tmp_workdir(nil, prefix: "squash-#{squash_id}") do |share_path|
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
          # 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})"
          logger.info("#{logprefix} calling `hg squash --exact` "\
                      "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(
                    [hg_exe, 'fold', '--exact',
                     '-r', revset,
                     '-m', message,
                     '-u', username,
                     '--config', 'experimental.evolution.allowunstable=no',
                    ],
                    share_path, hg_env)
          if status != 0
            raise HgError, "Could not fold revset `#{revset}` Error: #{output}"
          end
          logger.info("#{logprefix} squash done, finding successor")
          output, status = popen(
                    [hg_exe, 'hpd-unique-successor', '-r', end_hgsha],
                    share_path, hg_env)
          if status != 0
            raise HgError, "Could not retrieve folded changeset "\
                           "(successor of #{end_hgsha})"
          end
          squash_hgsha = output.strip
          logger.info("#{logprefix} squash successor changeset #{squash_hgsha}")

          hg_git_invalidate_maps!
          sha_from_hgsha(squash_hgsha)
        end
      end

      # Mercurial squashes are atomic. We can pretend there's no squash
      # in progress.
      #
      # Actually at this point, reading the resulting changeset is not,
      # but it doesn't matter much: there's no risk of repo corruption.
      def squash_in_progress?(squash_id)
735
        has_tmp_workdir?("squash-#{squash_id}")
736
737
      end

Georges Racinet's avatar
Georges Racinet committed
738
739
740
741
742
743
744
745
      # 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)
746
747
748
749
      def rebase(
        user, rebase_id, branch:, branch_sha:,
        remote_repository:, remote_branch:, push_options: [])

Georges Racinet's avatar
Georges Racinet committed
750
751
752
753
754
755
756
757
758
759
760
761
762
        logprefix = "hg_rebase for #{@relative_path} of git #{branch_sha} "\
                    "(branch #{branch}) onto #{remote_branch}"
        logger = Rails.logger
        raise StandardError, "Rebasing between two different repos is not "\
                             "supported" unless remote_repository == self

        topic = parse_gitlab_branch_for_hg(branch)[1]
        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
763
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') unless unit_tests_skip_hooks
Georges Racinet's avatar
Georges Racinet committed
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785

        # 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}"
786
787
        rebase_hgsha =
          hg_tmp_workdir(nil, prefix: "rebase-#{rebase_id}") do |share_path|
Georges Racinet's avatar
Georges Racinet committed
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
          # 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?

          # `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
          logger.info("#{logprefix} rebase done, finding successor")
          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
        end
        hg_git_invalidate_maps!
        rebase_sha = sha_from_hgsha(rebase_hgsha)
        logger.info("#{logprefix} rebase successor changeset #{rebase_hgsha} "\
                    "(git sha #{rebase_sha})")

        yield rebase_sha
        rebase_sha
      end

      # 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)
835
        has_tmp_workdir?("rebase-#{rebase_id}")
Georges Racinet's avatar
Georges Racinet committed
836
837
      end

838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
      # 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
        hg_env = {'HGUSER' => 'Heptapod system',
                  'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes',
                  'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                 }
        hg_exe = Gitlab.config.mercurial.bin_path
        _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
                )

        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(
                       [hg_exe, 'log', '-T', '{node}:{branch}:{topic}',
                        '-r', query_rev],
                       @hgpath, hg_env)
        if status != 0
          raise HgRevisionError, "Could not log revision #{query_rev}"
        end
        node_branch.split(':')
      end

883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
      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

902
903
904
      # perform multiple write actions in the repository in a single commit
      #
      # typically multiple file writes or renames, followed by a commit
905
906
907
908
909
910
      #
      # 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.
911
912
913
914
915
916
917
918
919
920
921
      def multi_action(user, branch_name:, message:, actions:,
        author_email: nil, author_name: nil,
        start_branch_name: nil, start_sha: nil, start_repository: self,
        force: false)
        logprefix = "hg_multi_action for #{@relative_path} "\
                    "start_branch_name=#{start_branch_name} branch_name=#{branch_name}"
        logger = Rails.logger  # could need to be adapted for gitaly-ruby (see initialize())
        logger.info("#{logprefix} starting")

        hg_exe = Gitlab.config.mercurial.bin_path
        hg_env = hg_env_for_write(user)
922
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') unless unit_tests_skip_hooks
923

924
        username = hg_prepare_user_encoding(hg_env, user, message)
925
926
927
928

        branch_creating = !branch_exists?(branch_name)
        repo_creating = exists?

929
930
        start_branch_name ||= branch_name

931
932
933
934
935
936
937
938
        start_hg_branch, start_topic = parse_gitlab_branch_for_hg(start_branch_name)
        # using the branchmap notation to perform just one update
        start_hg = if empty?
                     nil
                   else
                     hg_branchmap_branch(start_hg_branch, start_topic)
                   end
        commit_hgsha = hg_tmp_workdir(start_hg) do |share_path|
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962

          hg_branch, topic = parse_gitlab_branch_for_hg(branch_name)
          if hg_branch != start_hg_branch
            # doing this inconditionally would be more that just a waste of
            # resources, it could reset the topic
            output, status = popen([hg_exe, 'branch', hg_branch], share_path, hg_env)
            if status != 0
              raise HgError, "Could not switch working dir to branch #{hg_branch}: #{output}"
            end
          end

          if topic != start_topic
            if topic.nil?
              output, status = popen([hg_exe, 'topic', '--clear'], share_path, hg_env)
              if status != 0
                raise HgError, "Could not clear topic: #{output}"
              end
            else
              output, status = popen([hg_exe, 'topic', topic], share_path, hg_env)
              if status != 0
                raise HgError, "Could not set topic to #{topic}: #{output}"
              end
            end
          end
963
964
          logger.info("#{logprefix} Setup done, ready to execute actions "\
                      "in workdir #{share_path}")
965
          actions.each do |action|
966
967
968
969
970
971
972
            if !action[:file_path]
              raise HgError, "All current actions need a file_path argument"
            end

            file_path = File.join(*action[:file_path].split('/'))
            abspath = File.join(share_path, file_path)

973
974
            logger.info(
              "#{logprefix} Performing '#{action[:action]}' for #{file_path}")
975
            case action[:action].to_sym
976
977
            when :create
              if File.exists?(abspath)
978
                raise ActionError, "A file with this name already exists"
979
980
981
              end
              parent_abspath = File.split(abspath)[0]
              if File.file?(parent_abspath)
982
983
                raise ActionError, "A file with same name as parent directory "\
                                  "already exists."
984
985
              end
              FileUtils.mkdir_p(parent_abspath)
986
              write_file(abspath, action[:content])
987
988
            when :update
              unless File.file?(abspath)
989
                raise ActionError, "A file with this name doesn't exist"
990
              end
991
              write_file(abspath, action[:content])
992
993
            when :create_dir
              if File.file?(abspath)
994
                raise ActionError, "A file with this name already exists "
995
996
              end
              if File.directory?(abspath)
997
                raise ActionError, "A directory with this name already exists"
998
999
1000
              end
              FileUtils.mkdir_p(abspath)
              File.write(File.join(abspath, '.hg_keep'), '')
1001
            when :move
1002
1003
              previous_path = File.join(action[:previous_path].split('/'))
              new_path = file_path
1004
1005
1006
1007
1008
1009
              unless File.exists?(File.join(share_path, previous_path))
                raise ActionError, "A file with this name doesn't exist"
              end
              if File.exists?(abspath)
                raise ActionError, "A file with this name already exists"
              end
1010
              # hg mv will take care of creating parent dir if needed
1011
1012
1013
1014
1015
1016
1017
1018
              output, status = popen([hg_exe, 'mv', previous_path, new_path], share_path, hg_env)
              # TODO should check if file is tracked and do a simple `mv` if not
              if status != 0
                raise HgError, "Could not `hg mv #{previous_path} #{new_path}`: #{output}"
              end
            when :delete
              # Let's support chains of actions that could be simplified (use-case: generated).
              # We're currently never just 'adding' a file, but let's be future proof.
1019
1020
1021
              unless File.exists?(abspath)
                raise ActionError, "A file with this name doesn't exist"
              end
1022
1023
1024
1025
1026
              output, status = popen([hg_exe, 'rm', '-f', file_path], share_path, hg_env)
              if ![0, 1].include?(status)  # status 1 happens with untracked files
                raise HgError, "Could not `hg rm -f #{file_path}`: #{output}"
              end
              # needed if the rm was actually just a forget:
1027
              FileUtils.rm_f(abspath)
1028
1029
1030
1031
1032
            else
              raise HgError,  "Notimplemented action #{action}"
            end
          end

1033
          logger.info("#{logprefix} Actions, done, now committing.")
1034
1035
1036
          commit_hgsha = hg_commit(share_path, username, message, hg_env, true)
          logger.info("#{logprefix} commit done, changeset is #{commit_hgsha}")

1037
1038
          if topic.nil? && hg_config_item_bool?('experimental.topic.publish-bare-branch')
            hg_changeset_publish(user, commit_hgsha, notify_gitlab: true)
1039
            logger.info("#{logprefix} published changeset #{commit_hgsha}")
1040
          end
1041
          commit_hgsha
1042
1043
1044
1045
1046
1047
1048
1049
1050
        end
        hg_git_invalidate_maps!
        commit_gitsha = sha_from_hgsha commit_hgsha

        # Same kind of return as gitaly_operation_client.user_commit_files(),
        # itself called from `multi_action()`
        Gitlab::Git::OperationService::BranchUpdate.new(commit_gitsha, repo_creating, branch_creating)
      end

1051
      # Compute path to a repo namespace HGRC, ready for inclusion from repo's HGRC.
1052
1053
      # namespace_path: must be relative to the storage root, as @relative_path
      # is.
1054
1055
1056
      #
      # Returns: path as a string
      def hgrc_inherit_path(namespace_path)
1057
1058
        Pathname(namespace_path).join('hgrc')
          .relative_path_from(File.join(@hg_relative_path, '.hg')).to_s
1059
1060
      end

1061
      # Absolute path to the repo HGRC directly read by Mercurial
1062
1063
1064
1065
      def hgrc_main_path
        File.join(@hgpath, '.hg', 'hgrc')
      end

1066
      # Absolute path to the repo HGRC managed by the Rails app
1067
1068
1069
1070
1071
      def hgrc_managed
        managed = 'hgrc.managed'
        [managed, File.join(@hgpath, '.hg', managed)]
      end

1072
      HGRC_INCL_INHERIT_RX = /%include (.*)\/hgrc/.freeze
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157

      # write the repository-local HGRC files.
      #
      # all configuration values are written in a separate `hgrc.managed`
      # file that is completely overwritten.
      #
      # in the main `hgrc`, only inclusions are managed
      #
      # inherit: if true, include directive for the namespace HGRC is included
      #          first if not already there.
      #          if false, it is removed if present
      #          if nil, nothing happens
      # values: two-level Hash, with String leaf values
      #
      # Newlines in values are prohibited (use plain whitespace if needed),
      # as well as in keys (section and item names).
      def set_hgrc(user, inherit, namespace_path, values)
        key_rx = /^\w*$/

        write_main = false
        main_path = hgrc_main_path
        managed, managed_path = hgrc_managed
        incl_managed = "%include " + managed

        main_lines = File.readlines(main_path)
        main_stripped_lines = main_lines.map { |l| l.strip }
        if !main_stripped_lines.include?(incl_managed)
          main_lines.push("\n", incl_managed + "\n")
          write_main = true
        end

        by_line = "by user #{user.username} (id=#{user.id}) at #{Time.new}"
        if inherit.nil?
        elsif inherit
          if match_idx(main_stripped_lines, HGRC_INCL_INHERIT_RX).nil?
            main_lines.insert(0,
                              "%include " + hgrc_inherit_path(namespace_path))
            main_lines.insert(0, "# inheritance restored #{by_line}")
            write_main = true
          end
        else
          inh_idx = match_idx(main_stripped_lines, HGRC_INCL_INHERIT_RX)
          if !inh_idx.nil?
            main_lines[inh_idx] = "# inheritance removed #{by_line}"
            write_main = true
          end
        end

        File.open(managed_path, 'w') do |hgrcf|
          hgrcf.puts(
            "# This file is entirely managed through the GitLab Rails app")
          hgrcf.puts("# last update #{by_line}")

          if !values.nil?
            values.each do |section, items|
              raise InvalidHgSetting(section) unless key_rx.match(section)
              hgrcf.puts("[#{section}]")
              items.each do |item, value|
                raise InvalidHgSetting(item) unless key_rx.match(section)
                raise InvalidHgSetting(value) if value.include?('\n')
                hgrcf.puts("#{item} = #{value}")
              end
              hgrcf.puts()
            end
          end
        end

        if write_main
          File.open(main_path, 'w') do |mainf|
            for line in main_lines
              # note for not-rubyists: puts() adds "\n"  only if needeed
              mainf.puts(line)
            end
          end
        end
      end

      # Read the HGRC configuration files *for this repo*
      #
      # Return a Hash:
      #  'inherit' => bool
      #  'content' => raw content of the managed file
      def get_hgrc
        main_lines = File.readlines(hgrc_main_path)
        main_stripped_lines = main_lines.map { |l| l.strip }
1158
1159
        managed_path = hgrc_managed[1]
        content = File.exist?(managed_path) ? File.read(managed_path) : nil
1160
1161
        {
          'inherit' => !match_idx(main_stripped_lines, HGRC_INCL_INHERIT_RX).nil?,
1162
          'content' => content,
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
        }
      end

      # Check HGRC inheritance from group path and fix it if needed.
      #
      # This is especially useful in cases of repository relocation:
      # - rename
      # - transfer
      # - hashed storage migration
      def check_fix_hgrc_inheritance(namespace_path)
        hgrc_path = hgrc_main_path
        Rails.logger.info("check_fix_hgrc_inheritance called with namespace_path=#{namespace_path} for #{hgrc_path}")
        main_lines = File.readlines(hgrc_path)

        inherit_idx = match_idx(main_lines, HGRC_INCL_INHERIT_RX)
        return if inherit_idx.nil?

        inherit_line = "%include " + hgrc_inherit_path(namespace_path)
        return unless inherit_line != main_lines[inherit_idx].strip

        main_lines[inherit_idx] = inherit_line
        File.open(hgrc_path, 'w') do |mainf|
          for line in main_lines
            # note for not-rubyists: puts() adds "\n"  only if needeed
            mainf.puts(line)
          end
        end
      end

1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
      # Return path to namespace, if namespace's HGRC included from the repo's
      #
      # The returned path is relative to storage root.
      # In case the namespace HGRC is not included from the repo's, the return
      # value is `nil`.
      #
      # TODO inelegant, we're using the regexp twice, only to finally
      # give back to a caller that will create a new instance and call
      # check_fix_hgrc_inheritance, redoing the whole scan.
      def rpath_to_namespace_if_hgrc_included(new_disk_path)
        hgrc_lines = File.readlines(hgrc_main_path)
        inherit_idx = match_idx(hgrc_lines, HGRC_INCL_INHERIT_RX)
        return if inherit_idx.nil?

        # TODO unnecessary reapplication of the regexp
        previous_line = hgrc_lines[inherit_idx]
        previous_namespace_rpath = HGRC_INCL_INHERIT_RX.match(previous_line)[1]
        Pathname(@hg_relative_path).join(".hg", previous_namespace_rpath)
      end

1212
1213
1214
1215
1216
      SAFE_HG_HEPTAPOD_CONFIG = {'allow-multiple-heads' => 'bool',
                                 'allow-bookmarks' => 'bool',
                                 'auto-publish' => 'str'}.freeze
      HG_CONFIG_TRUE = ["1", "yes",  "true", "on"].freeze

1217
      def get_hg_heptapod_config(local: false)
1218
1219
        hg_env = {'HGUSER' => 'Heptapod system',
                  'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes',
1220
                  'HGRCPATH' => local ? "" : Gitlab::Mercurial.hgrc_path,
1221
1222
1223
1224
                 }
        hg_exe = Gitlab.config.mercurial.bin_path
        out, status = popen([hg_exe, 'config', 'heptapod'],
                            @hgpath, hg_env)
1225
1226
1227
        return {} if status == 1  # as usual, code 1 is not an error for hg

        raise StandardError, "Can't read hg repository config" unless status.zero?
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
        config = {}
        out.lines.each do |line|
          key, value = line.split('=', 2)
          key = key.strip
          next unless key.start_with?('heptapod.')
          key = key[9..]
          # no attempt to convert back, that's up to the user
          # (we'd have to know the type for that)
          value = value.strip
          vtype = SAFE_HG_HEPTAPOD_CONFIG[key]
          next if vtype.nil?  # not a safe item
          config[key] = converted = case vtype
                      when 'bool'
                        HG_CONFIG_TRUE.include?(value)
                      when 'str'
                        value
                      else
                        next
                      end
        end
        config
      end
1250

1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
      protected

      def mask_password_in_url(url)
        # TODO there must be a generic helper doing the same thing to use
        # instead somewhere in GitLab and its dependencies!
        result = URI(url)
        result.password = "*****" unless result.password.nil?
        result.user = "*****" unless result.user.nil? #it's needed for oauth access_token
        result
      rescue
        url
      end

1264
1265
1266
    end
  end
end