hg_git_repository.rb 42.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
16
17
18
      MergeError = Class.new(StandardError)
      HgError = Class.new(StandardError)
      InvalidHgSetting = Class.new(StandardError)
      HgRevisionError = Class.new(StandardError)
19
20
21
      # In general, GitLab expects `multi_action` to raise IndexError,
      # so let's subclass it.
      ActionError = Class.new(Gitlab::Git::Index::IndexError)
22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
      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

49
50
51
52
53
54
55
56
57
58
59
60
      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)
      end

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

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
      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

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
      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

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
      # 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

182
      # TODO duplication use the one from Mercurial module
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
      def parse_gitlab_branch_for_hg(gitlab_branch)
        if gitlab_branch.start_with?('branch/')
          [gitlab_branch[7..], nil]
        elsif gitlab_branch.start_with?('topic/')
          branch, _slash, topic = gitlab_branch[6..].rpartition('/')
          [branch, topic]
        else
          raise StandardError, "bookmarks not supported (got #{gitlab_branch})"
        end
      end

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

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
      # Return a suitable environment for write operations (merge etc.)
      def hg_env_for_write(user)
        {
          # `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,
          'HGRCPATH' => Gitlab::Mercurial.hgrc_path
        }
      end

      def hg_prepare_user_encoding(hg_env, user, message)
        committer = Gitlab::Git.committer_hash(email: user.email, name: user.name)
        username = "#{committer[:name]} <#{committer[:email]}>"
        # 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)
        env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS') if notify_gitlab
        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',
         '--config', 'ui.username=' + username,
         '-m', message,
              ]
        cmd.append('--addremove') if add_remove
        output, status = popen(cmd, path, env)
        raise HgError, "Could not commit: #{output}"  if status != 0

        hgsha_from_rev('.', path)
      end

280
281
282
283
      def has_tmp_workdir?(prefix)
        !Dir.glob("#{@hgpath}tmp-#{prefix}-*").empty?
      end

284
285
286
287
288
289
      # 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
290
291
      # `prefix`: optional prefix used to check if a share is present
      #           for a given operation.
292
293
      #
      # returns path to the working directory
294
295
296
297
298
299
      def hg_tmp_workdir(update_rev, prefix: nil)
        share_path = @hgpath + "tmp"
        unless prefix.nil?
          share_path += "-" + prefix + '-'
        end
        share_path += SecureRandom.hex
300

301
302
303
304
305
306
307
308
        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
309

310
311
312
313
          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
314
315
316
317

          yield share_path

        ensure
318
          FileUtils.rm_rf(share_path)
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        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
342
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS')
343

344
        hg_tmp_workdir(target_hgsha) do |share_path|
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
          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}")
362
          commit_hgsha
363
364
365
        end
      end

366
367
368
369
370
371
      # 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

372
373
374
375
      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())
376
        forbid_merge_in_topic(target_branch)
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
        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)
429
430
431
        target_topic = parse_gitlab_branch_for_hg(target_branch)[1]
        return false unless target_topic.nil?

432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
        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)
474
475
        forbid_merge_in_topic(target_branch)

476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
        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).
      def squash(user, squash_id, branch:, start_sha:, end_sha:, author:, message:)
        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)

518
        hg_tmp_workdir(nil, prefix: "squash-#{squash_id}") do |share_path|
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
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
          # 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)
570
        has_tmp_workdir?("squash-#{squash_id}")
571
572
      end

Georges Racinet's avatar
Georges Racinet committed
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619

      # 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)
      def rebase(user, rebase_id, branch:, branch_sha:,
                 remote_repository:, remote_branch:)
        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
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS')

        # 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}"
620
621
        rebase_hgsha =
          hg_tmp_workdir(nil, prefix: "rebase-#{rebase_id}") do |share_path|
Georges Racinet's avatar
Georges Racinet committed
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
          # 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)
669
        has_tmp_workdir?("rebase-#{rebase_id}")
Georges Racinet's avatar
Georges Racinet committed
670
671
      end

672
673
674
675
676
677
678
679
680
681
682
683
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
      # 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

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
      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

736
737
738
      # perform multiple write actions in the repository in a single commit
      #
      # typically multiple file writes or renames, followed by a commit
739
740
741
742
743
744
      #
      # 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.
745
746
747
748
749
750
751
752
753
754
755
      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)
756
        hg_env.delete('HEPTAPOD_SKIP_ALL_GITLAB_HOOKS')
757
758
759
760
761
762
763
764
765
766
767
768

        committer = Gitlab::Git.committer_hash(email: user.email, name: user.name)
        username = "#{committer[:name]} <#{committer[:email]}>"
        # 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

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

769
770
        start_branch_name ||= branch_name

771
772
773
774
775
776
777
778
        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|
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802

          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
803
804
          logger.info("#{logprefix} Setup done, ready to execute actions "\
                      "in workdir #{share_path}")
805
          actions.each do |action|
806
807
808
809
810
811
812
            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)

813
814
            logger.info(
              "#{logprefix} Performing '#{action[:action]}' for #{file_path}")
815
            case action[:action].to_sym
816
817
            when :create
              if File.exists?(abspath)
818
                raise ActionError, "A file with this name already exists"
819
820
821
              end
              parent_abspath = File.split(abspath)[0]
              if File.file?(parent_abspath)
822
823
                raise ActionError, "A file with same name as parent directory "\
                                  "already exists."
824
825
              end
              FileUtils.mkdir_p(parent_abspath)
826
              write_file(abspath, action[:content])
827
828
            when :update
              unless File.file?(abspath)
829
                raise ActionError, "A file with this name doesn't exist"
830
              end
831
              write_file(abspath, action[:content])
832
833
            when :create_dir
              if File.file?(abspath)
834
                raise ActionError, "A file with this name already exists "
835
836
              end
              if File.directory?(abspath)
837
                raise ActionError, "A directory with this name already exists"
838
839
840
              end
              FileUtils.mkdir_p(abspath)
              File.write(File.join(abspath, '.hg_keep'), '')
841
            when :move
842
843
              previous_path = File.join(action[:previous_path].split('/'))
              new_path = file_path
844
845
846
847
848
849
              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
850
              # hg mv will take care of creating parent dir if needed
851
852
853
854
855
856
857
858
              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.
859
860
861
              unless File.exists?(abspath)
                raise ActionError, "A file with this name doesn't exist"
              end
862
863
864
865
866
              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:
867
              FileUtils.rm_f(abspath)
868
869
870
871
872
873
874
875
876
877
878
879
880
            else
              raise HgError,  "Notimplemented action #{action}"
            end
          end

          if !message.nil? && 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)
            logger.error("Encoding of commit message #{message.encoding.name} differs "\
                         "from user name's #{encname}")
          end
881
          logger.info("#{logprefix} Actions, done, now committing.")
882
883
884
885
886
887
          commit_hgsha = hg_commit(share_path, username, message, hg_env, true)
          logger.info("#{logprefix} commit done, changeset is #{commit_hgsha}")

          if topic.nil?
            publish_str, status = popen([hg_exe, 'config', 'experimental.topic.publish-bare-branch'], share_path, hg_env)
            publish = ['yes', 'true', 'on', '1'].include?(publish_str.downcase.strip)
888
            hg_changeset_publish(user, commit_hgsha, notify_gitlab: true) if publish
889
          end
890
          commit_hgsha
891
892
893
894
895
896
897
898
899
        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

900
      # Compute path to a repo namespace HGRC, ready for inclusion from repo's HGRC.
901
902
      # namespace_path: must be relative to the storage root, as @relative_path
      # is.
903
904
905
      #
      # Returns: path as a string
      def hgrc_inherit_path(namespace_path)
906
907
        Pathname(namespace_path).join('hgrc')
          .relative_path_from(File.join(@hg_relative_path, '.hg')).to_s
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
      end

      def hgrc_main_path
        File.join(@hgpath, '.hg', 'hgrc')
      end

      def hgrc_managed
        managed = 'hgrc.managed'
        [managed, File.join(@hgpath, '.hg', managed)]
      end

      HGRC_INCL_INHERIT_RX = /%include .*\/hgrc/.freeze

      # 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 }
        {
          'inherit' => !match_idx(main_stripped_lines, HGRC_INCL_INHERIT_RX).nil?,
          'content' => File.read(hgrc_managed[1])
        }
      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

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

      def get_hg_heptapod_config
        hg_env = {'HGUSER' => 'Heptapod system',
                  'HEPTAPOD_SKIP_ALL_GITLAB_HOOKS' => 'yes',
                  'HGRCPATH' => Gitlab::Mercurial.hgrc_path,
                 }
        hg_exe = Gitlab.config.mercurial.bin_path
        out, status = popen([hg_exe, 'config', 'heptapod'],
                            @hgpath, hg_env)
        raise StandardError("Can't read hg repository config") unless status.zero?
        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
1073

1074
1075
1076
    end
  end
end