repository_spec.rb 80.8 KB
Newer Older
1
# coding: utf-8
Robert Speicher's avatar
Robert Speicher committed
2 3 4
require "spec_helper"

describe Gitlab::Git::Repository, seed_helper: true do
5
  include Gitlab::EncodingHelper
6
  using RSpec::Parameterized::TableSyntax
Robert Speicher's avatar
Robert Speicher committed
7

8 9 10 11 12 13 14 15 16 17 18 19 20 21
  shared_examples 'wrapping gRPC errors' do |gitaly_client_class, gitaly_client_method|
    it 'wraps gRPC not found error' do
      expect_any_instance_of(gitaly_client_class).to receive(gitaly_client_method)
        .and_raise(GRPC::NotFound)
      expect { subject }.to raise_error(Gitlab::Git::Repository::NoRepository)
    end

    it 'wraps gRPC unknown error' do
      expect_any_instance_of(gitaly_client_class).to receive(gitaly_client_method)
        .and_raise(GRPC::Unknown)
      expect { subject }.to raise_error(Gitlab::Git::CommandError)
    end
  end

22
  let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '') }
23
  let(:storage_path) { TestEnv.repos_path }
24
  let(:user) { build(:user) }
Robert Speicher's avatar
Robert Speicher committed
25

26
  describe '.create_hooks' do
27
    let(:repo_path) { File.join(storage_path, 'hook-test.git') }
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    let(:hooks_dir) { File.join(repo_path, 'hooks') }
    let(:target_hooks_dir) { Gitlab.config.gitlab_shell.hooks_path }
    let(:existing_target) { File.join(repo_path, 'foobar') }

    before do
      FileUtils.rm_rf(repo_path)
      FileUtils.mkdir_p(repo_path)
    end

    context 'hooks is a directory' do
      let(:existing_file) { File.join(hooks_dir, 'my-file') }

      before do
        FileUtils.mkdir_p(hooks_dir)
        FileUtils.touch(existing_file)
        described_class.create_hooks(repo_path, target_hooks_dir)
      end

      it { expect(File.readlink(hooks_dir)).to eq(target_hooks_dir) }
      it { expect(Dir[File.join(repo_path, "hooks.old.*/my-file")].count).to eq(1) }
    end

    context 'hooks is a valid symlink' do
      before do
        FileUtils.mkdir_p existing_target
        File.symlink(existing_target, hooks_dir)
        described_class.create_hooks(repo_path, target_hooks_dir)
      end

      it { expect(File.readlink(hooks_dir)).to eq(target_hooks_dir) }
    end

    context 'hooks is a broken symlink' do
      before do
        FileUtils.rm_f(existing_target)
        File.symlink(existing_target, hooks_dir)
        described_class.create_hooks(repo_path, target_hooks_dir)
      end

      it { expect(File.readlink(hooks_dir)).to eq(target_hooks_dir) }
    end
  end

Robert Speicher's avatar
Robert Speicher committed
71 72 73 74 75 76 77 78
  describe "Respond to" do
    subject { repository }

    it { is_expected.to respond_to(:rugged) }
    it { is_expected.to respond_to(:root_ref) }
    it { is_expected.to respond_to(:tags) }
  end

79 80
  describe '#root_ref' do
    context 'with gitaly disabled' do
81 82 83
      before do
        allow(Gitlab::GitalyClient).to receive(:feature_enabled?).and_return(false)
      end
84 85 86 87 88 89 90

      it 'calls #discover_default_branch' do
        expect(repository).to receive(:discover_default_branch)
        repository.root_ref
      end
    end

91
    it 'returns UTF-8' do
92
      expect(repository.root_ref).to be_utf8
93 94
    end

95
    it 'gets the branch name from GitalyClient' do
Andrew Newdigate's avatar
Andrew Newdigate committed
96
      expect_any_instance_of(Gitlab::GitalyClient::RefService).to receive(:default_branch_name)
97 98
      repository.root_ref
    end
99

Andrew Newdigate's avatar
Andrew Newdigate committed
100
    it_behaves_like 'wrapping gRPC errors', Gitlab::GitalyClient::RefService, :default_branch_name do
101
      subject { repository.root_ref }
102
    end
103 104
  end

105
  describe "#rugged" do
106
    describe 'when storage is broken', :broken_storage  do
107
      it 'raises a storage exception when storage is not available' do
108
        broken_repo = described_class.new('broken', 'a/path.git', '')
109 110 111 112 113 114

        expect { broken_repo.rugged }.to raise_error(Gitlab::Git::Storage::Inaccessible)
      end
    end

    it 'raises a no repository exception when there is no repo' do
115
      broken_repo = described_class.new('default', 'a/path.git', '')
116 117 118 119

      expect { broken_repo.rugged }.to raise_error(Gitlab::Git::Repository::NoRepository)
    end

120 121 122
    describe 'alternates keyword argument' do
      context 'with no Git env stored' do
        before do
123
          allow(Gitlab::Git::HookEnv).to receive(:all).and_return({})
124
        end
125

126 127
        it "is passed an empty array" do
          expect(Rugged::Repository).to receive(:new).with(repository.path, alternates: [])
128

129 130
          repository.rugged
        end
131 132
      end

133 134
      context 'with absolute and relative Git object dir envvars stored' do
        before do
135
          allow(Gitlab::Git::HookEnv).to receive(:all).and_return({
136 137 138
            'GIT_OBJECT_DIRECTORY_RELATIVE' => './objects/foo',
            'GIT_ALTERNATE_OBJECT_DIRECTORIES_RELATIVE' => ['./objects/bar', './objects/baz'],
            'GIT_OBJECT_DIRECTORY' => 'ignored',
139
            'GIT_ALTERNATE_OBJECT_DIRECTORIES' => %w[ignored ignored],
140 141 142 143 144 145 146 147 148 149
            'GIT_OTHER' => 'another_env'
          })
        end

        it "is passed the relative object dir envvars after being converted to absolute ones" do
          alternates = %w[foo bar baz].map { |d| File.join(repository.path, './objects', d) }
          expect(Rugged::Repository).to receive(:new).with(repository.path, alternates: alternates)

          repository.rugged
        end
150 151 152 153
      end
    end
  end

Robert Speicher's avatar
Robert Speicher committed
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
  describe "#discover_default_branch" do
    let(:master) { 'master' }
    let(:feature) { 'feature' }
    let(:feature2) { 'feature2' }

    it "returns 'master' when master exists" do
      expect(repository).to receive(:branch_names).at_least(:once).and_return([feature, master])
      expect(repository.discover_default_branch).to eq('master')
    end

    it "returns non-master when master exists but default branch is set to something else" do
      File.write(File.join(repository.path, 'HEAD'), 'ref: refs/heads/feature')
      expect(repository).to receive(:branch_names).at_least(:once).and_return([feature, master])
      expect(repository.discover_default_branch).to eq('feature')
      File.write(File.join(repository.path, 'HEAD'), 'ref: refs/heads/master')
    end

    it "returns a non-master branch when only one exists" do
      expect(repository).to receive(:branch_names).at_least(:once).and_return([feature])
      expect(repository.discover_default_branch).to eq('feature')
    end

    it "returns a non-master branch when more than one exists and master does not" do
      expect(repository).to receive(:branch_names).at_least(:once).and_return([feature, feature2])
      expect(repository.discover_default_branch).to eq('feature')
    end

    it "returns nil when no branch exists" do
      expect(repository).to receive(:branch_names).at_least(:once).and_return([])
      expect(repository.discover_default_branch).to be_nil
    end
  end

187
  describe '#branch_names' do
Robert Speicher's avatar
Robert Speicher committed
188 189 190 191 192
    subject { repository.branch_names }

    it 'has SeedRepo::Repo::BRANCHES.size elements' do
      expect(subject.size).to eq(SeedRepo::Repo::BRANCHES.size)
    end
193 194

    it 'returns UTF-8' do
195
      expect(subject.first).to be_utf8
196 197
    end

Robert Speicher's avatar
Robert Speicher committed
198 199
    it { is_expected.to include("master") }
    it { is_expected.not_to include("branch-from-space") }
200

201
    it 'gets the branch names from GitalyClient' do
Andrew Newdigate's avatar
Andrew Newdigate committed
202
      expect_any_instance_of(Gitlab::GitalyClient::RefService).to receive(:branch_names)
203 204
      subject
    end
205

Andrew Newdigate's avatar
Andrew Newdigate committed
206
    it_behaves_like 'wrapping gRPC errors', Gitlab::GitalyClient::RefService, :branch_names
Robert Speicher's avatar
Robert Speicher committed
207 208
  end

209
  describe '#tag_names' do
Robert Speicher's avatar
Robert Speicher committed
210 211 212
    subject { repository.tag_names }

    it { is_expected.to be_kind_of Array }
213

Robert Speicher's avatar
Robert Speicher committed
214 215 216 217
    it 'has SeedRepo::Repo::TAGS.size elements' do
      expect(subject.size).to eq(SeedRepo::Repo::TAGS.size)
    end

218
    it 'returns UTF-8' do
219
      expect(subject.first).to be_utf8
220 221
    end

Robert Speicher's avatar
Robert Speicher committed
222 223 224 225 226 227
    describe '#last' do
      subject { super().last }
      it { is_expected.to eq("v1.2.1") }
    end
    it { is_expected.to include("v1.0.0") }
    it { is_expected.not_to include("v5.0.0") }
228

229
    it 'gets the tag names from GitalyClient' do
Andrew Newdigate's avatar
Andrew Newdigate committed
230
      expect_any_instance_of(Gitlab::GitalyClient::RefService).to receive(:tag_names)
231 232
      subject
    end
233

Andrew Newdigate's avatar
Andrew Newdigate committed
234
    it_behaves_like 'wrapping gRPC errors', Gitlab::GitalyClient::RefService, :tag_names
Robert Speicher's avatar
Robert Speicher committed
235 236 237
  end

  shared_examples 'archive check' do |extenstion|
238
    it { expect(metadata['ArchivePath']).to match(%r{tmp/gitlab-git-test.git/gitlab-git-test-master-#{SeedRepo::LastCommit::ID}}) }
Robert Speicher's avatar
Robert Speicher committed
239 240 241
    it { expect(metadata['ArchivePath']).to end_with extenstion }
  end

242 243 244 245 246 247 248 249
  describe '#archive_prefix' do
    let(:project_name) { 'project-name'}

    before do
      expect(repository).to receive(:name).once.and_return(project_name)
    end

    it 'returns parameterised string for a ref containing slashes' do
250
      prefix = repository.archive_prefix('test/branch', 'SHA', append_sha: nil)
251 252 253

      expect(prefix).to eq("#{project_name}-test-branch-SHA")
    end
254 255

    it 'returns correct string for a ref containing dots' do
256
      prefix = repository.archive_prefix('test.branch', 'SHA', append_sha: nil)
257 258 259

      expect(prefix).to eq("#{project_name}-test.branch-SHA")
    end
260 261 262 263 264 265

    it 'returns string with sha when append_sha is false' do
      prefix = repository.archive_prefix('test.branch', 'SHA', append_sha: false)

      expect(prefix).to eq("#{project_name}-test.branch")
    end
266 267 268
  end

  describe '#archive' do
269
    let(:metadata) { repository.archive_metadata('master', '/tmp', append_sha: true) }
Robert Speicher's avatar
Robert Speicher committed
270 271 272 273

    it_should_behave_like 'archive check', '.tar.gz'
  end

274
  describe '#archive_zip' do
275
    let(:metadata) { repository.archive_metadata('master', '/tmp', 'zip', append_sha: true) }
Robert Speicher's avatar
Robert Speicher committed
276 277 278 279

    it_should_behave_like 'archive check', '.zip'
  end

280
  describe '#archive_bz2' do
281
    let(:metadata) { repository.archive_metadata('master', '/tmp', 'tbz2', append_sha: true) }
Robert Speicher's avatar
Robert Speicher committed
282 283 284 285

    it_should_behave_like 'archive check', '.tar.bz2'
  end

286
  describe '#archive_fallback' do
287
    let(:metadata) { repository.archive_metadata('master', '/tmp', 'madeup', append_sha: true) }
Robert Speicher's avatar
Robert Speicher committed
288 289 290 291

    it_should_behave_like 'archive check', '.tar.gz'
  end

292
  describe '#size' do
Robert Speicher's avatar
Robert Speicher committed
293 294 295 296 297
    subject { repository.size }

    it { is_expected.to be < 2 }
  end

298
  describe '#empty?' do
299
    it { expect(repository).not_to be_empty }
Robert Speicher's avatar
Robert Speicher committed
300 301
  end

302
  describe '#ref_names' do
Robert Speicher's avatar
Robert Speicher committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    let(:ref_names) { repository.ref_names }
    subject { ref_names }

    it { is_expected.to be_kind_of Array }

    describe '#first' do
      subject { super().first }
      it { is_expected.to eq('feature') }
    end

    describe '#last' do
      subject { super().last }
      it { is_expected.to eq('v1.2.1') }
    end
  end

319
  describe '#submodule_url_for' do
320
    let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '') }
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    let(:ref) { 'master' }

    def submodule_url(path)
      repository.submodule_url_for(ref, path)
    end

    it { expect(submodule_url('six')).to eq('git://github.com/randx/six.git') }
    it { expect(submodule_url('nested/six')).to eq('git://github.com/randx/six.git') }
    it { expect(submodule_url('deeper/nested/six')).to eq('git://github.com/randx/six.git') }
    it { expect(submodule_url('invalid/path')).to eq(nil) }

    context 'uncommitted submodule dir' do
      let(:ref) { 'fix-existing-submodule-dir' }

      it { expect(submodule_url('submodule-existing-dir')).to eq(nil) }
    end

    context 'tags' do
      let(:ref) { 'v1.2.1' }

      it { expect(submodule_url('six')).to eq('git://github.com/randx/six.git') }
    end

344 345 346 347 348 349 350
    context 'no .gitmodules at commit' do
      let(:ref) { '9596bc54a6f0c0c98248fe97077eb5ccf48a98d0' }

      it { expect(submodule_url('six')).to eq(nil) }
    end

    context 'no gitlink entry' do
351 352 353 354 355 356
      let(:ref) { '6d39438' }

      it { expect(submodule_url('six')).to eq(nil) }
    end
  end

357
  context '#submodules' do
358
    let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '') }
Robert Speicher's avatar
Robert Speicher committed
359 360

    context 'where repo has submodules' do
361
      let(:submodules) { repository.send(:submodules, 'master') }
Robert Speicher's avatar
Robert Speicher committed
362 363 364 365 366 367 368 369 370
      let(:submodule) { submodules.first }

      it { expect(submodules).to be_kind_of Hash }
      it { expect(submodules.empty?).to be_falsey }

      it 'should have valid data' do
        expect(submodule).to eq([
          "six", {
            "id" => "409f37c4f05865e4fb208c771485f211a22c4c2d",
371
            "name" => "six",
Robert Speicher's avatar
Robert Speicher committed
372 373 374 375 376 377 378
            "url" => "git://github.com/randx/six.git"
          }
        ])
      end

      it 'should handle nested submodules correctly' do
        nested = submodules['nested/six']
379
        expect(nested['name']).to eq('nested/six')
Robert Speicher's avatar
Robert Speicher committed
380 381 382 383 384 385
        expect(nested['url']).to eq('git://github.com/randx/six.git')
        expect(nested['id']).to eq('24fb71c79fcabc63dfd8832b12ee3bf2bf06b196')
      end

      it 'should handle deeply nested submodules correctly' do
        nested = submodules['deeper/nested/six']
386
        expect(nested['name']).to eq('deeper/nested/six')
Robert Speicher's avatar
Robert Speicher committed
387 388 389 390 391 392 393 394 395
        expect(nested['url']).to eq('git://github.com/randx/six.git')
        expect(nested['id']).to eq('24fb71c79fcabc63dfd8832b12ee3bf2bf06b196')
      end

      it 'should not have an entry for an invalid submodule' do
        expect(submodules).not_to have_key('invalid/path')
      end

      it 'should not have an entry for an uncommited submodule dir' do
396
        submodules = repository.send(:submodules, 'fix-existing-submodule-dir')
Robert Speicher's avatar
Robert Speicher committed
397 398 399 400
        expect(submodules).not_to have_key('submodule-existing-dir')
      end

      it 'should handle tags correctly' do
401
        submodules = repository.send(:submodules, 'v1.2.1')
Robert Speicher's avatar
Robert Speicher committed
402 403 404 405

        expect(submodules.first).to eq([
          "six", {
            "id" => "409f37c4f05865e4fb208c771485f211a22c4c2d",
406
            "name" => "six",
Robert Speicher's avatar
Robert Speicher committed
407 408 409 410
            "url" => "git://github.com/randx/six.git"
          }
        ])
      end
411 412 413 414 415 416 417 418 419 420 421 422 423

      it 'should not break on invalid syntax' do
        allow(repository).to receive(:blob_content).and_return(<<-GITMODULES.strip_heredoc)
          [submodule "six"]
          path = six
          url = git://github.com/randx/six.git

          [submodule]
          foo = bar
        GITMODULES

        expect(submodules).to have_key('six')
      end
Robert Speicher's avatar
Robert Speicher committed
424 425 426
    end

    context 'where repo doesn\'t have submodules' do
427
      let(:submodules) { repository.send(:submodules, '6d39438') }
Robert Speicher's avatar
Robert Speicher committed
428 429 430 431 432 433
      it 'should return an empty hash' do
        expect(submodules).to be_empty
      end
    end
  end

434
  describe '#commit_count' do
435
    shared_examples 'simple commit counting' do
436 437
      it { expect(repository.commit_count("master")).to eq(25) }
      it { expect(repository.commit_count("feature")).to eq(9) }
438
      it { expect(repository.commit_count("does-not-exist")).to eq(0) }
439 440 441
    end

    context 'when Gitaly commit_count feature is enabled' do
442
      it_behaves_like 'simple commit counting'
Andrew Newdigate's avatar
Andrew Newdigate committed
443
      it_behaves_like 'wrapping gRPC errors', Gitlab::GitalyClient::CommitService, :commit_count do
444 445 446 447
        subject { repository.commit_count('master') }
      end
    end

448
    context 'when Gitaly commit_count feature is disabled', :skip_gitaly_mock  do
449
      it_behaves_like 'simple commit counting'
450
    end
Robert Speicher's avatar
Robert Speicher committed
451 452
  end

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
  describe '#has_local_branches?' do
    shared_examples 'check for local branches' do
      it { expect(repository.has_local_branches?).to eq(true) }

      context 'mutable' do
        let(:repository) { Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '') }

        after do
          ensure_seeds
        end

        it 'returns false when there are no branches' do
          # Sanity check
          expect(repository.has_local_branches?).to eq(true)

          FileUtils.rm_rf(File.join(repository.path, 'packed-refs'))
          heads_dir = File.join(repository.path, 'refs/heads')
          FileUtils.rm_rf(heads_dir)
          FileUtils.mkdir_p(heads_dir)

          expect(repository.has_local_branches?).to eq(false)
        end
      end
    end

    context 'with gitaly' do
      it_behaves_like 'check for local branches'
    end

482
    context 'without gitaly', :skip_gitaly_mock do
483 484 485 486
      it_behaves_like 'check for local branches'
    end
  end

Robert Speicher's avatar
Robert Speicher committed
487
  describe "#delete_branch" do
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    shared_examples "deleting a branch" do
      let(:repository) { Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '') }

      after do
        ensure_seeds
      end

      it "removes the branch from the repo" do
        branch_name = "to-be-deleted-soon"

        repository.create_branch(branch_name)
        expect(repository.rugged.branches[branch_name]).not_to be_nil

        repository.delete_branch(branch_name)
        expect(repository.rugged.branches[branch_name]).to be_nil
      end

      context "when branch does not exist" do
        it "raises a DeleteBranchError exception" do
          expect { repository.delete_branch("this-branch-does-not-exist") }.to raise_error(Gitlab::Git::Repository::DeleteBranchError)
        end
      end
Robert Speicher's avatar
Robert Speicher committed
510 511
    end

512 513
    context "when Gitaly delete_branch is enabled" do
      it_behaves_like "deleting a branch"
Robert Speicher's avatar
Robert Speicher committed
514 515
    end

516
    context "when Gitaly delete_branch is disabled", :skip_gitaly_mock do
517
      it_behaves_like "deleting a branch"
Robert Speicher's avatar
Robert Speicher committed
518 519 520 521
    end
  end

  describe "#create_branch" do
522 523
    shared_examples 'creating a branch' do
      let(:repository) { Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '') }
Robert Speicher's avatar
Robert Speicher committed
524

525 526 527
      after do
        ensure_seeds
      end
Robert Speicher's avatar
Robert Speicher committed
528

529 530 531
      it "should create a new branch" do
        expect(repository.create_branch('new_branch', 'master')).not_to be_nil
      end
Robert Speicher's avatar
Robert Speicher committed
532

533 534 535 536 537 538 539 540 541 542 543 544
      it "should create a new branch with the right name" do
        expect(repository.create_branch('another_branch', 'master').name).to eq('another_branch')
      end

      it "should fail if we create an existing branch" do
        repository.create_branch('duplicated_branch', 'master')
        expect {repository.create_branch('duplicated_branch', 'master')}.to raise_error("Branch duplicated_branch already exists")
      end

      it "should fail if we create a branch from a non existing ref" do
        expect {repository.create_branch('branch_based_in_wrong_ref', 'master_2_the_revenge')}.to raise_error("Invalid reference master_2_the_revenge")
      end
Robert Speicher's avatar
Robert Speicher committed
545 546
    end

547 548
    context 'when Gitaly create_branch feature is enabled' do
      it_behaves_like 'creating a branch'
Robert Speicher's avatar
Robert Speicher committed
549 550
    end

551
    context 'when Gitaly create_branch feature is disabled', :skip_gitaly_mock do
552
      it_behaves_like 'creating a branch'
Robert Speicher's avatar
Robert Speicher committed
553 554 555
    end
  end

556
  describe '#delete_refs' do
557 558
    shared_examples 'deleting refs' do
      let(:repo) { Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '') }
559

560 561 562
      after do
        ensure_seeds
      end
563

564 565
      it 'deletes the ref' do
        repo.delete_refs('refs/heads/feature')
566

567 568 569 570 571 572 573 574 575 576 577
        expect(repo.rugged.references['refs/heads/feature']).to be_nil
      end

      it 'deletes all refs' do
        refs = %w[refs/heads/wip refs/tags/v1.1.0]
        repo.delete_refs(*refs)

        refs.each do |ref|
          expect(repo.rugged.references[ref]).to be_nil
        end
      end
578

579 580
      it 'raises an error if it failed' do
        expect { repo.delete_refs('refs\heads\fix') }.to raise_error(Gitlab::Git::Repository::GitError)
581 582 583
      end
    end

584 585
    context 'when Gitaly delete_refs feature is enabled' do
      it_behaves_like 'deleting refs'
586 587
    end

588 589
    context 'when Gitaly delete_refs feature is disabled', :disable_gitaly do
      it_behaves_like 'deleting refs'
590 591 592
    end
  end

593 594 595 596
  describe '#branch_names_contains_sha' do
    shared_examples 'returning the right branches' do
      let(:head_id) { repository.rugged.head.target.oid }
      let(:new_branch) { head_id }
597
      let(:utf8_branch) { 'branch-é' }
598 599 600

      before do
        repository.create_branch(new_branch, 'master')
601
        repository.create_branch(utf8_branch, 'master')
602 603 604 605
      end

      after do
        repository.delete_branch(new_branch)
606
        repository.delete_branch(utf8_branch)
607 608 609
      end

      it 'displays that branch' do
610
        expect(repository.branch_names_contains_sha(head_id)).to include('master', new_branch, utf8_branch)
611 612 613 614 615 616 617 618 619 620 621 622
      end
    end

    context 'when Gitaly is enabled' do
      it_behaves_like 'returning the right branches'
    end

    context 'when Gitaly is disabled', :disable_gitaly do
      it_behaves_like 'returning the right branches'
    end
  end

Robert Speicher's avatar
Robert Speicher committed
623
  describe "#refs_hash" do
624
    subject { repository.refs_hash }
Robert Speicher's avatar
Robert Speicher committed
625 626 627 628

    it "should have as many entries as branches and tags" do
      expected_refs = SeedRepo::Repo::BRANCHES + SeedRepo::Repo::TAGS
      # We flatten in case a commit is pointed at by more than one branch and/or tag
629 630 631 632 633
      expect(subject.values.flatten.size).to eq(expected_refs.size)
    end

    it 'has valid commit ids as keys' do
      expect(subject.keys).to all( match(Commit::COMMIT_SHA_PATTERN) )
Robert Speicher's avatar
Robert Speicher committed
634 635 636
    end
  end

637
  describe "#remove_remote" do
Robert Speicher's avatar
Robert Speicher committed
638
    before(:all) do
639
      @repo = Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
640
      @repo.remove_remote("expendable")
Robert Speicher's avatar
Robert Speicher committed
641 642 643 644 645 646 647 648 649 650 651
    end

    it "should remove the remote" do
      expect(@repo.rugged.remotes).not_to include("expendable")
    end

    after(:all) do
      ensure_seeds
    end
  end

652
  describe "#remote_update" do
Robert Speicher's avatar
Robert Speicher committed
653
    before(:all) do
654
      @repo = Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
655
      @repo.remote_update("expendable", url: TEST_NORMAL_REPO_PATH)
Robert Speicher's avatar
Robert Speicher committed
656 657 658
    end

    it "should add the remote" do
659 660 661
      expect(@repo.rugged.remotes["expendable"].url).to(
        eq(TEST_NORMAL_REPO_PATH)
      )
Robert Speicher's avatar
Robert Speicher committed
662 663 664 665 666 667 668
    end

    after(:all) do
      ensure_seeds
    end
  end

669
  describe '#fetch_repository_as_mirror' do
670 671
    let(:new_repository) do
      Gitlab::Git::Repository.new('default', 'my_project.git', '')
Robert Speicher's avatar
Robert Speicher committed
672 673
    end

674
    subject { new_repository.fetch_repository_as_mirror(repository) }
675 676

    before do
677
      Gitlab::Shell.new.create_repository('default', 'my_project')
Robert Speicher's avatar
Robert Speicher committed
678 679
    end

680
    after do
681
      Gitlab::Shell.new.remove_repository(storage_path, 'my_project')
682 683
    end

684 685 686
    shared_examples 'repository mirror fecthing' do
      it 'fetches a repository as a mirror remote' do
        subject
687

688 689
        expect(refs(new_repository.path)).to eq(refs(repository.path))
      end
690

691 692 693 694
      context 'with keep-around refs' do
        let(:sha) { SeedRepo::Commit::ID }
        let(:keep_around_ref) { "refs/keep-around/#{sha}" }
        let(:tmp_ref) { "refs/tmp/#{SecureRandom.hex}" }
695

696 697 698 699
        before do
          repository.rugged.references.create(keep_around_ref, sha, force: true)
          repository.rugged.references.create(tmp_ref, sha, force: true)
        end
700

701 702
        it 'includes the temporary and keep-around refs' do
          subject
703

704 705 706
          expect(refs(new_repository.path)).to include(keep_around_ref)
          expect(refs(new_repository.path)).to include(tmp_ref)
        end
707 708
      end
    end
709 710 711 712 713 714 715 716

    context 'with gitaly enabled' do
      it_behaves_like 'repository mirror fecthing'
    end

    context 'with gitaly enabled', :skip_gitaly_mock do
      it_behaves_like 'repository mirror fecthing'
    end
717 718 719
  end

  describe '#remote_tags' do
720
    let(:remote_name) { 'upstream' }
721
    let(:target_commit_id) { SeedRepo::Commit::ID }
722 723 724 725 726
    let(:tag_name) { 'v0.0.1' }
    let(:tag_message) { 'My tag' }
    let(:remote_repository) do
      Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
    end
727

728
    subject { repository.remote_tags(remote_name) }
729

730 731 732 733
    before do
      repository.add_remote(remote_name, remote_repository.path)
      remote_repository.add_tag(tag_name, user: user, target: target_commit_id)
    end
734

735 736 737 738 739
    after do
      ensure_seeds
    end

    it 'gets the remote tags' do
740
      expect(subject.first).to be_an_instance_of(Gitlab::Git::Tag)
741
      expect(subject.first.name).to eq(tag_name)
742
      expect(subject.first.dereferenced_target.id).to eq(target_commit_id)
Robert Speicher's avatar
Robert Speicher committed
743 744 745 746
    end
  end

  describe "#log" do
747 748 749 750 751 752 753 754 755 756
    shared_examples 'repository log' do
      let(:commit_with_old_name) do
        Gitlab::Git::Commit.decorate(repository, @commit_with_old_name_id)
      end
      let(:commit_with_new_name) do
        Gitlab::Git::Commit.decorate(repository, @commit_with_new_name_id)
      end
      let(:rename_commit) do
        Gitlab::Git::Commit.decorate(repository, @rename_commit_id)
      end
Robert Speicher's avatar
Robert Speicher committed
757

758 759 760 761 762 763 764
      before(:context) do
        # Add new commits so that there's a renamed file in the commit history
        repo = Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '').rugged
        @commit_with_old_name_id = new_commit_edit_old_file(repo)
        @rename_commit_id = new_commit_move_file(repo)
        @commit_with_new_name_id = new_commit_edit_new_file(repo)
      end
Robert Speicher's avatar
Robert Speicher committed
765

766 767 768 769
      after(:context) do
        # Erase our commits so other tests get the original repo
        repo = Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '').rugged
        repo.references.update("refs/heads/master", SeedRepo::LastCommit::ID)
Robert Speicher's avatar
Robert Speicher committed
770 771
      end

772 773 774 775 776 777
      context "where 'follow' == true" do
        let(:options) { { ref: "master", follow: true } }

        context "and 'path' is a directory" do
          it "does not follow renames" do
            log_commits = repository.log(options.merge(path: "encoding"))
778 779 780 781

            aggregate_failures do
              expect(log_commits).to include(commit_with_new_name)
              expect(log_commits).to include(rename_commit)
782
              expect(log_commits).not_to include(commit_with_old_name)
783
            end
784
          end
Robert Speicher's avatar
Robert Speicher committed
785 786
        end

787 788 789 790
        context "and 'path' is a file that matches the new filename" do
          context 'without offset' do
            it "follows renames" do
              log_commits = repository.log(options.merge(path: "encoding/CHANGELOG"))
791

792 793 794 795 796
              aggregate_failures do
                expect(log_commits).to include(commit_with_new_name)
                expect(log_commits).to include(rename_commit)
                expect(log_commits).to include(commit_with_old_name)
              end
797
            end
798 799
          end

800 801 802
          context 'with offset=1' do
            it "follows renames and skip the latest commit" do
              log_commits = repository.log(options.merge(path: "encoding/CHANGELOG", offset: 1))
803

804 805 806 807 808 809
              aggregate_failures do
                expect(log_commits).not_to include(commit_with_new_name)
                expect(log_commits).to include(rename_commit)
                expect(log_commits).to include(commit_with_old_name)
              end
            end
810 811
          end

812 813 814
          context 'with offset=1', 'and limit=1' do
            it "follows renames, skip the latest commit and return only one commit" do
              log_commits = repository.log(options.merge(path: "encoding/CHANGELOG", offset: 1, limit: 1))
815

816
              expect(log_commits).to contain_exactly(rename_commit)
817
            end
818 819
          end

820 821 822
          context 'with offset=1', 'and limit=2' do
            it "follows renames, skip the latest commit and return only two commits" do
              log_commits = repository.log(options.merge(path: "encoding/CHANGELOG", offset: 1, limit: 2))
823

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
              aggregate_failures do
                expect(log_commits).to contain_exactly(rename_commit, commit_with_old_name)
              end
            end
          end

          context 'with offset=2' do
            it "follows renames and skip the latest commit" do
              log_commits = repository.log(options.merge(path: "encoding/CHANGELOG", offset: 2))

              aggregate_failures do
                expect(log_commits).not_to include(commit_with_new_name)
                expect(log_commits).not_to include(rename_commit)
                expect(log_commits).to include(commit_with_old_name)
              end
            end
          end

          context 'with offset=2', 'and limit=1' do
            it "follows renames, skip the two latest commit and return only one commit" do
              log_commits = repository.log(options.merge(path: "encoding/CHANGELOG", offset: 2, limit: 1))

              expect(log_commits).to contain_exactly(commit_with_old_name)
847
            end
848 849
          end

850 851 852
          context 'with offset=2', 'and limit=2' do
            it "follows renames, skip the two latest commit and return only one commit" do
              log_commits = repository.log(options.merge(path: "encoding/CHANGELOG", offset: 2, limit: 2))
853

854 855 856 857 858 859
              aggregate_failures do
                expect(log_commits).not_to include(commit_with_new_name)
                expect(log_commits).not_to include(rename_commit)
                expect(log_commits).to include(commit_with_old_name)
              end
            end
860 861 862
          end
        end

863 864 865
        context "and 'path' is a file that matches the old filename" do
          it "does not follow renames" do
            log_commits = repository.log(options.merge(path: "CHANGELOG"))
866 867 868

            aggregate_failures do
              expect(log_commits).not_to include(commit_with_new_name)
869
              expect(log_commits).to include(rename_commit)
870 871
              expect(log_commits).to include(commit_with_old_name)
            end
872
          end
Robert Speicher's avatar
Robert Speicher committed
873 874
        end

875 876 877
        context "unknown ref" do
          it "returns an empty array" do
            log_commits = repository.log(options.merge(ref: 'unknown'))
Robert Speicher's avatar
Robert Speicher committed
878

879
            expect(log_commits).to eq([])
880
          end
Robert Speicher's avatar
Robert Speicher committed
881 882 883
        end
      end

884 885
      context "where 'follow' == false" do
        options = { follow: false }
Robert Speicher's avatar
Robert Speicher committed
886

887 888 889 890
        context "and 'path' is a directory" do
          let(:log_commits) do
            repository.log(options.merge(path: "encoding"))
          end
Robert Speicher's avatar
Robert Speicher committed
891

892 893 894 895 896
          it "does not follow renames" do
            expect(log_commits).to include(commit_with_new_name)
            expect(log_commits).to include(rename_commit)
            expect(log_commits).not_to include(commit_with_old_name)
          end
Robert Speicher's avatar
Robert Speicher committed
897 898
        end

899 900 901 902
        context "and 'path' is a file that matches the new filename" do
          let(:log_commits) do
            repository.log(options.merge(path: "encoding/CHANGELOG"))
          end
Robert Speicher's avatar
Robert Speicher committed
903

904 905 906 907 908
          it "does not follow renames" do
            expect(log_commits).to include(commit_with_new_name)
            expect(log_commits).to include(rename_commit)
            expect(log_commits).not_to include(commit_with_old_name)
          end
Robert Speicher's avatar
Robert Speicher committed
909 910
        end

911 912 913 914
        context "and 'path' is a file that matches the old filename" do
          let(:log_commits) do
            repository.log(options.merge(path: "CHANGELOG"))
          end
Robert Speicher's avatar
Robert Speicher committed
915

916 917 918 919 920
          it "does not follow renames" do
            expect(log_commits).to include(commit_with_old_name)
            expect(log_commits).to include(rename_commit)
            expect(log_commits).not_to include(commit_with_new_name)
          end
Robert Speicher's avatar
Robert Speicher committed
921 922
        end

923 924 925 926 927 928 929 930
        context "and 'path' includes a directory that used to be a file" do
          let(:log_commits) do
            repository.log(options.merge(ref: "refs/heads/fix-blob-path", path: "files/testdir/file.txt"))
          end

          it "returns a list of commits" do
            expect(log_commits.size).to eq(1)
          end
Robert Speicher's avatar
Robert Speicher committed
931 932 933
        end
      end

934 935
      context "where provides 'after' timestamp" do
        options = { after: Time.iso8601('2014-03-03T20:15:01+00:00') }
Robert Speicher's avatar
Robert Speicher committed
936

937 938 939 940 941 942 943
        it "should returns commits on or after that timestamp" do
          commits = repository.log(options)

          expect(commits.size).to be > 0
          expect(commits).to satisfy do |commits|
            commits.all? { |commit| commit.committed_date >= options[:after] }
          end
Robert Speicher's avatar
Robert Speicher committed
944 945 946
        end
      end

947 948
      context "where provides 'before' timestamp" do
        options = { before: Time.iso8601('2014-03-03T20:15:01+00:00') }
Robert Speicher's avatar
Robert Speicher committed
949

950 951
        it "should returns commits on or before that timestamp" do
          commits = repository.log(options)
Robert Speicher's avatar
Robert Speicher committed
952

953 954 955 956
          expect(commits.size).to be > 0
          expect(commits).to satisfy do |commits|
            commits.all? { |commit| commit.committed_date <= options[:before] }
          end
Robert Speicher's avatar
Robert Speicher committed
957 958 959
        end
      end

960 961
      context 'when multiple paths are provided' do
        let(:options) { { ref: 'master', path: ['PROCESS.md', 'README.md'] } }
Robert Speicher's avatar
Robert Speicher committed
962

963 964 965 966
        def commit_files(commit)
          commit.rugged_diff_from_parent.deltas.flat_map do |delta|
            [delta.old_file[:path], delta.new_file[:path]].uniq.compact
          end
967 968
        end

969 970
        it 'only returns commits matching at least one path' do
          commits = repository.log(options)
971

972 973 974 975
          expect(commits.size).to be > 0
          expect(commits).to satisfy do |commits|
            commits.none? { |commit| (commit_files(commit) & options[:path]).empty? }
          end
976 977 978
        end
      end

979 980 981 982
      context 'limit validation' do
        where(:limit) do
          [0, nil, '', 'foo']
        end
983

984 985
        with_them do
          it { expect { repository.log(limit: limit) }.to raise_error(ArgumentError) }
Robert Speicher's avatar
Robert Speicher committed
986 987
        end
      end
988

989 990 991
      context 'with all' do
        it 'returns a list of commits' do
          commits = repository.log({ all: true, limit: 50 })
992

993 994
          expect(commits.size).to eq(37)
        end
995 996
      end
    end
Tiago Botelho's avatar
Tiago Botelho committed
997

998 999 1000
    context 'when Gitaly find_commits feature is enabled' do
      it_behaves_like 'repository log'
    end
Tiago Botelho's avatar
Tiago Botelho committed
1001

1002 1003
    context 'when Gitaly find_commits feature is disabled', :disable_gitaly do
      it_behaves_like 'repository log'
Tiago Botelho's avatar
Tiago Botelho committed
1004
    end
Robert Speicher's avatar
Robert Speicher committed
1005 1006
  end

1007
  describe "#rugged_commits_between" do
Robert Speicher's avatar
Robert Speicher committed
1008 1009 1010 1011 1012
    context 'two SHAs' do
      let(:first_sha) { 'b0e52af38d7ea43cf41d8a6f2471351ac036d6c9' }
      let(:second_sha) { '0e50ec4d3c7ce42ab74dda1d422cb2cbffe1e326' }

      it 'returns the number of commits between' do
1013
        expect(repository.rugged_commits_between(first_sha, second_sha).count).to eq(3)
Robert Speicher's avatar
Robert Speicher committed
1014 1015 1016 1017 1018 1019 1020 1021
      end
    end

    context 'SHA and master branch' do
      let(:sha) { 'b0e52af38d7ea43cf41d8a6f2471351ac036d6c9' }
      let(:branch) { 'master' }

      it 'returns the number of commits between a sha and a branch' do
1022
        expect(repository.rugged_commits_between(sha, branch).count).to eq(5)
Robert Speicher's avatar
Robert Speicher committed
1023 1024 1025
      end

      it 'returns the number of commits between a branch and a sha' do
1026
        expect(repository.rugged_commits_between(branch, sha).count).to eq(0) # sha is before branch
Robert Speicher's avatar
Robert Speicher committed
1027 1028 1029 1030 1031 1032 1033 1034
      end
    end

    context 'two branches' do
      let(:first_branch) { 'feature' }
      let(:second_branch) { 'master' }

      it 'returns the number of commits between' do
1035
        expect(repository.rugged_commits_between(first_branch, second_branch).count).to eq(17)
Robert Speicher's avatar
Robert Speicher committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
      end
    end
  end

  describe '#count_commits_between' do
    subject { repository.count_commits_between('feature', 'master') }

    it { is_expected.to eq(17) }
  end

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
  describe '#merge_base' do
    shared_examples '#merge_base' do
      where(:from, :to, :result) do
        '570e7b2abdd848b95f2f578043fc23bd6f6fd24d' | '40f4a7a617393735a95a0bb67b08385bc1e7c66d' | '570e7b2abdd848b95f2f578043fc23bd6f6fd24d'
        '40f4a7a617393735a95a0bb67b08385bc1e7c66d' | '570e7b2abdd848b95f2f578043fc23bd6f6fd24d' | '570e7b2abdd848b95f2f578043fc23bd6f6fd24d'
        '40f4a7a617393735a95a0bb67b08385bc1e7c66d' | 'foobar' | nil
        'foobar' | '40f4a7a617393735a95a0bb67b08385bc1e7c66d' | nil
      end

      with_them do
        it { expect(repository.merge_base(from, to)).to eq(result) }
      end
    end

    context 'with gitaly' do
      it_behaves_like '#merge_base'
    end

    context 'without gitaly', :skip_gitaly_mock do
      it_behaves_like '#merge_base'
    end
  end

1069
  describe '#count_commits' do
1070 1071 1072
    shared_examples 'extended commit counting' do
      context 'with after timestamp' do
        it 'returns the number of commits after timestamp' do
1073
          options = { ref: 'master', after: Time.iso8601('2013-03-03T20:15:01+00:00') }
1074

1075 1076
          expect(repository.count_commits(options)).to eq(25)
        end
1077 1078
      end

1079 1080
      context 'with before timestamp' do
        it 'returns the number of commits before timestamp' do
1081
          options = { ref: 'feature', before: Time.iso8601('2015-03-03T20:15:01+00:00') }
1082

1083 1084
          expect(repository.count_commits(options)).to eq(9)
        end
1085 1086
      end

1087 1088 1089 1090 1091 1092 1093 1094
      context 'with max_count' do
        it 'returns the number of commits with path ' do
          options = { ref: 'master', max_count: 5 }

          expect(repository.count_commits(options)).to eq(5)
        end
      end

1095 1096
      context 'with path' do
        it 'returns the number of commits with path ' do
1097 1098 1099 1100 1101 1102 1103 1104 1105
          options = { ref: 'master', path: 'encoding' }

          expect(repository.count_commits(options)).to eq(2)
        end
      end

      context 'with option :from and option :to' do
        it 'returns the number of commits ahead for fix-mode..fix-blob-path' do
          options = { from: 'fix-mode', to: 'fix-blob-path' }
1106

1107 1108
          expect(repository.count_commits(options)).to eq(2)
        end
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130

        it 'returns the number of commits ahead for fix-blob-path..fix-mode' do
          options = { from: 'fix-blob-path', to: 'fix-mode' }

          expect(repository.count_commits(options)).to eq(1)
        end

        context 'with option :left_right' do
          it 'returns the number of commits for fix-mode...fix-blob-path' do
            options = { from: 'fix-mode', to: 'fix-blob-path', left_right: true }

            expect(repository.count_commits(options)).to eq([1, 2])
          end

          context 'with max_count' do
            it 'returns the number of commits with path ' do
              options = { from: 'fix-mode', to: 'fix-blob-path', left_right: true, max_count: 1 }

              expect(repository.count_commits(options)).to eq([1, 1])
            end
          end
        end
1131
      end
1132 1133 1134 1135 1136 1137 1138 1139

      context 'with max_count' do
        it 'returns the number of commits up to the passed limit' do
          options = { ref: 'master', max_count: 10, after: Time.iso8601('2013-03-03T20:15:01+00:00') }

          expect(repository.count_commits(options)).to eq(10)
        end
      end
Tiago Botelho's avatar
Tiago Botelho committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150

      context "with all" do
        it "returns the number of commits in the whole repository" do
          options = { all: true }

          expect(repository.count_commits(options)).to eq(34)
        end
      end

      context 'without all or ref being specified' do
        it "raises an ArgumentError" do
1151
          expect { repository.count_commits({}) }.to raise_error(ArgumentError)
Tiago Botelho's avatar
Tiago Botelho committed
1152 1153
        end
      end
1154
    end
1155 1156 1157 1158 1159 1160 1161 1162

    context 'when Gitaly count_commits feature is enabled' do
      it_behaves_like 'extended commit counting'
    end

    context 'when Gitaly count_commits feature is disabled', :disable_gitaly do
      it_behaves_like 'extended commit counting'
    end
1163 1164
  end

Robert Speicher's avatar
Robert Speicher committed
1165 1166
  describe '#autocrlf' do
    before(:all) do
1167
      @repo = Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
Robert Speicher's avatar
Robert Speicher committed
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
      @repo.rugged.config['core.autocrlf'] = true
    end

    it 'return the value of the autocrlf option' do
      expect(@repo.autocrlf).to be(true)
    end

    after(:all) do
      @repo.rugged.config.delete('core.autocrlf')
    end
  end

  describe '#autocrlf=' do
    before(:all) do
1182
      @repo = Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
Robert Speicher's avatar
Robert Speicher committed
1183 1184 1185 1186 1187 1188
      @repo.rugged.config['core.autocrlf'] = false
    end

    it 'should set the autocrlf option to the provided option' do
      @repo.autocrlf = :input

1189
      File.open(File.join(SEED_STORAGE_PATH, TEST_MUTABLE_REPO_PATH, 'config')) do |config_file|
Robert Speicher's avatar
Robert Speicher committed
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
        expect(config_file.read).to match('autocrlf = input')
      end
    end

    after(:all) do
      @repo.rugged.config.delete('core.autocrlf')
    end
  end

  describe '#find_branch' do
1200 1201 1202
    shared_examples 'finding a branch' do
      it 'should return a Branch for master' do
        branch = repository.find_branch('master')
Robert Speicher's avatar
Robert Speicher committed
1203

1204 1205 1206
        expect(branch).to be_a_kind_of(Gitlab::Git::Branch)
        expect(branch.name).to eq('master')
      end
Robert Speicher's avatar
Robert Speicher committed
1207

1208 1209
      it 'should handle non-existent branch' do
        branch = repository.find_branch('this-is-garbage')
Robert Speicher's avatar
Robert Speicher committed
1210

1211 1212
        expect(branch).to eq(nil)
      end
Robert Speicher's avatar
Robert Speicher committed
1213 1214
    end

1215 1216 1217
    context 'when Gitaly find_branch feature is enabled' do
      it_behaves_like 'finding a branch'
    end
Robert Speicher's avatar
Robert Speicher committed
1218

1219
    context 'when Gitaly find_branch feature is disabled', :skip_gitaly_mock do
1220
      it_behaves_like 'finding a branch'
Robert Speicher's avatar
Robert Speicher committed
1221

1222 1223 1224
      context 'force_reload is true' do
        it 'should reload Rugged::Repository' do
          expect(Rugged::Repository).to receive(:new).twice.and_call_original
1225

1226 1227
          repository.find_branch('master')
          branch = repository.find_branch('master', force_reload: true)
1228

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
          expect(branch).to be_a_kind_of(Gitlab::Git::Branch)
          expect(branch.name).to eq('master')
        end
      end

      context 'force_reload is false' do
        it 'should not reload Rugged::Repository' do
          expect(Rugged::Repository).to receive(:new).once.and_call_original

          branch = repository.find_branch('master', force_reload: false)

          expect(branch).to be_a_kind_of(Gitlab::Git::Branch)
          expect(branch.name).to eq('master')
        end
1243
      end
Robert Speicher's avatar
Robert Speicher committed
1244
    end
1245 1246
  end

1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
  describe '#ref_name_for_sha' do
    let(:ref_path) { 'refs/heads' }
    let(:sha) { repository.find_branch('master').dereferenced_target.id }
    let(:ref_name) { 'refs/heads/master' }

    it 'returns the ref name for the given sha' do
      expect(repository.ref_name_for_sha(ref_path, sha)).to eq(ref_name)
    end

    it "returns an empty name if the ref doesn't exist" do
      expect(repository.ref_name_for_sha(ref_path, "000000")).to eq("")
    end

    it "raise an exception if the ref is empty" do
      expect { repository.ref_name_for_sha(ref_path, "") }.to raise_error(ArgumentError)
    end

    it "raise an exception if the ref is nil" do
      expect { repository.ref_name_for_sha(ref_path, nil) }.to raise_error(ArgumentError)
    end
  end

1269 1270 1271 1272 1273
  describe '#branches' do
    subject { repository.branches }

    context 'with local and remote branches' do
      let(:repository) do
1274
        Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
      end

      before do
        create_remote_branch(repository, 'joe', 'remote_branch', 'master')
        repository.create_branch('local_branch', 'master')
      end

      after do
        ensure_seeds
      end

      it 'returns the local and remote branches' do
        expect(subject.any? { |b| b.name == 'joe/remote_branch' }).to eq(true)
        expect(subject.any? { |b| b.name == 'local_branch' }).to eq(true)
      end
Robert Speicher's avatar
Robert Speicher committed
1290 1291
    end

1292 1293 1294 1295
    # With Gitaly enabled, Gitaly just doesn't return deleted branches.
    context 'with deleted branch with Gitaly disabled' do
      before do
        allow(Gitlab::GitalyClient).to receive(:feature_enabled?).and_return(false)
1296 1297 1298
      end

      it 'returns no results' do
1299 1300 1301 1302 1303 1304 1305
        ref = double()
        allow(ref).to receive(:name) { 'bad-branch' }
        allow(ref).to receive(:target) { raise Rugged::ReferenceError }
        branches = double()
        allow(branches).to receive(:each) { [ref].each }
        allow(repository.rugged).to receive(:branches) { branches }

1306 1307
        expect(subject).to be_empty
      end
Robert Speicher's avatar
Robert Speicher committed
1308
    end
1309 1310

    it_behaves_like 'wrapping gRPC errors', Gitlab::GitalyClient::RefService, :branches
Robert Speicher's avatar
Robert Speicher committed
1311 1312 1313 1314
  end

  describe '#branch_count' do
    it 'returns the number of branches' do
1315
      expect(repository.branch_count).to eq(10)
Robert Speicher's avatar
Robert Speicher committed
1316
    end
1317 1318 1319

    context 'with local and remote branches' do
      let(:repository) do
1320
        Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
      end

      before do
        create_remote_branch(repository, 'joe', 'remote_branch', 'master')
        repository.create_branch('local_branch', 'master')
      end

      after do
        ensure_seeds
      end

      it 'returns the count of local branches' do
        expect(repository.branch_count).to eq(repository.local_branches.count)
      end

      context 'with Gitaly disabled' do
        before do
          allow(Gitlab::GitalyClient).to receive(:feature_enabled?).and_return(false)
        end

        it 'returns the count of local branches' do
          expect(repository.branch_count).to eq(repository.local_branches.count)
        end
      end
    end
Robert Speicher's avatar
Robert Speicher committed
1346 1347
  end

1348
  describe '#merged_branch_names' do
1349 1350 1351 1352
    shared_examples 'finding merged branch names' do
      context 'when branch names are passed' do
        it 'only returns the names we are asking' do
          names = repository.merged_branch_names(%w[merge-test])
1353

1354 1355
          expect(names).to contain_exactly('merge-test')
        end
1356

1357 1358
        it 'does not return unmerged branch names' do
          names = repository.merged_branch_names(%w[feature])
1359

1360 1361
          expect(names).to be_empty
        end
1362 1363
      end

1364 1365 1366
      context 'when no root ref is available' do
        it 'returns empty list' do
          project = create(:project, :empty_repo)
1367

1368
          names = project.repository.merged_branch_names(%w[feature])
1369

1370 1371
          expect(names).to be_empty
        end
1372 1373
      end

1374 1375 1376 1377
      context 'when no branch names are specified' do
        before do
          repository.create_branch('identical', 'master')
        end
1378

1379 1380 1381
        after do
          ensure_seeds
        end
1382

1383 1384
        it 'returns all merged branch names except for identical one' do
          names = repository.merged_branch_names
1385

1386 1387 1388 1389 1390
          expect(names).to include('merge-test')
          expect(names).to include('fix-mode')
          expect(names).not_to include('feature')
          expect(names).not_to include('identical')
        end
1391 1392
      end
    end
1393 1394 1395 1396 1397 1398 1399 1400

    context 'when Gitaly merged_branch_names feature is enabled' do
      it_behaves_like 'finding merged branch names'
    end

    context 'when Gitaly merged_branch_names feature is disabled', :disable_gitaly do
      it_behaves_like 'finding merged branch names'
    end
1401 1402
  end

Robert Speicher's avatar
Robert Speicher committed
1403 1404
  describe "#ls_files" do
    let(:master_file_paths) { repository.ls_files("master") }
1405
    let(:utf8_file_paths) { repository.ls_files("ls-files-utf8") }
Robert Speicher's avatar
Robert Speicher committed
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
    let(:not_existed_branch) { repository.ls_files("not_existed_branch") }

    it "read every file paths of master branch" do
      expect(master_file_paths.length).to equal(40)
    end

    it "reads full file paths of master branch" do
      expect(master_file_paths).to include("files/html/500.html")
    end

1416
    it "does not read submodule directory and empty directory of master branch" do
Robert Speicher's avatar
Robert Speicher committed
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
      expect(master_file_paths).not_to include("six")
    end

    it "does not include 'nil'" do
      expect(master_file_paths).not_to include(nil)
    end

    it "returns empty array when not existed branch" do
      expect(not_existed_branch.length).to equal(0)
    end
1427 1428 1429 1430

    it "returns valid utf-8 data" do
      expect(utf8_file_paths.map { |file| file.force_encoding('utf-8') }).to all(be_valid_encoding)
    end
Robert Speicher's avatar
Robert Speicher committed
1431 1432 1433
  end

  describe "#copy_gitattributes" do
1434 1435
    shared_examples 'applying git attributes' do
      let(:attributes_path) { File.join(SEED_STORAGE_PATH, TEST_REPO_PATH, 'info/attributes') }
Robert Speicher's avatar
Robert Speicher committed
1436

1437 1438
      after do
        FileUtils.rm_rf(attributes_path) if Dir.exist?(attributes_path)
Robert Speicher's avatar
Robert Speicher committed
1439 1440
      end

1441 1442
      it "raises an error with invalid ref" do
        expect { repository.copy_gitattributes("invalid") }.to raise_error(Gitlab::Git::Repository::InvalidRef)
Robert Speicher's avatar
Robert Speicher committed
1443 1444
      end

1445 1446
      context 'when forcing encoding issues' do
        let(:branch_name) { "ʕ•ᴥ•ʔ" }
Robert Speicher's avatar
Robert Speicher committed
1447

1448 1449 1450
        before do
          repository.create_branch(branch_name, "master")
        end
Robert Speicher's avatar
Robert Speicher committed
1451

1452 1453 1454
        after do
          repository.rm_branch(branch_name, user: build(:admin))
        end
Robert Speicher's avatar
Robert Speicher committed
1455

1456 1457
        it "doesn't raise with a valid unicode ref" do
          expect { repository.copy_gitattributes(branch_name) }.not_to raise_error
Robert Speicher's avatar
Robert Speicher committed
1458

1459 1460
          repository
        end
Robert Speicher's avatar
Robert Speicher committed
1461 1462
      end

1463 1464 1465 1466
      context "with no .gitattrbutes" do
        before do
          repository.copy_gitattributes("master")
        end
Robert Speicher's avatar
Robert Speicher committed
1467

1468 1469 1470
        it "does not have an info/attributes" do
          expect(File.exist?(attributes_path)).to be_falsey
        end
Robert Speicher's avatar
Robert Speicher committed
1471 1472
      end

1473 1474 1475 1476
      context "with .gitattrbutes" do
        before do
          repository.copy_gitattributes("gitattributes")
        end
Robert Speicher's avatar
Robert Speicher committed
1477

1478 1479 1480
        it "has an info/attributes" do
          expect(File.exist?(attributes_path)).to be_truthy
        end
Robert Speicher's avatar
Robert Speicher committed
1481

1482 1483 1484 1485
        it "has the same content in info/attributes as .gitattributes" do
          contents = File.open(attributes_path, "rb") { |f| f.read }
          expect(contents).to eq("*.md binary\n")
        end
Robert Speicher's avatar
Robert Speicher committed
1486 1487
      end

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
      context "with updated .gitattrbutes" do
        before do
          repository.copy_gitattributes("gitattributes")
          repository.copy_gitattributes("gitattributes-updated")
        end

        it "has an info/attributes" do
          expect(File.exist?(attributes_path)).to be_truthy
        end

        it "has the updated content in info/attributes" do
          contents = File.read(attributes_path)
          expect(contents).to eq("*.txt binary\n")
        end
Robert Speicher's avatar
Robert Speicher committed
1502 1503
      end

1504 1505 1506 1507 1508 1509 1510 1511 1512
      context "with no .gitattrbutes in HEAD but with previous info/attributes" do
        before do
          repository.copy_gitattributes("gitattributes")
          repository.copy_gitattributes("master")
        end

        it "does not have an info/attributes" do
          expect(File.exist?(attributes_path)).to be_falsey
        end
Robert Speicher's avatar
Robert Speicher committed
1513 1514
      end
    end
1515 1516 1517 1518 1519 1520 1521 1522

    context 'when gitaly is enabled' do
      it_behaves_like 'applying git attributes'
    end

    context 'when gitaly is disabled', :disable_gitaly do
      it_behaves_like 'applying git attributes'
    end
Robert Speicher's avatar
Robert Speicher committed
1523 1524
  end

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
  describe '#ref_exists?' do
    shared_examples 'checks the existence of refs' do
      it 'returns true for an existing tag' do
        expect(repository.ref_exists?('refs/heads/master')).to eq(true)
      end

      it 'returns false for a non-existing tag' do
        expect(repository.ref_exists?('refs/tags/THIS_TAG_DOES_NOT_EXIST')).to eq(false)
      end

      it 'raises an ArgumentError for an empty string' do
        expect { repository.ref_exists?('') }.to raise_error(ArgumentError)
      end

      it 'raises an ArgumentError for an invalid ref' do
        expect { repository.ref_exists?('INVALID') }.to raise_error(ArgumentError)
      end
    end

    context 'when Gitaly ref_exists feature is enabled' do
      it_behaves_like 'checks the existence of refs'
    end

1548
    context 'when Gitaly ref_exists feature is disabled', :skip_gitaly_mock do
1549 1550 1551 1552
      it_behaves_like 'checks the existence of refs'
    end
  end

Robert Speicher's avatar
Robert Speicher committed
1553
  describe '#tag_exists?' do
1554 1555 1556
    shared_examples 'checks the existence of tags' do
      it 'returns true for an existing tag' do
        tag = repository.tag_names.first
Robert Speicher's avatar
Robert Speicher committed
1557

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
        expect(repository.tag_exists?(tag)).to eq(true)
      end

      it 'returns false for a non-existing tag' do
        expect(repository.tag_exists?('v9000')).to eq(false)
      end
    end

    context 'when Gitaly ref_exists_tags feature is enabled' do
      it_behaves_like 'checks the existence of tags'
Robert Speicher's avatar
Robert Speicher committed
1568 1569
    end

1570
    context 'when Gitaly ref_exists_tags feature is disabled', :skip_gitaly_mock do
1571
      it_behaves_like 'checks the existence of tags'
Robert Speicher's avatar
Robert Speicher committed
1572 1573 1574 1575
    end
  end

  describe '#branch_exists?' do
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
    shared_examples 'checks the existence of branches' do
      it 'returns true for an existing branch' do
        expect(repository.branch_exists?('master')).to eq(true)
      end

      it 'returns false for a non-existing branch' do
        expect(repository.branch_exists?('kittens')).to eq(false)
      end

      it 'returns false when using an invalid branch name' do
        expect(repository.branch_exists?('.bla')).to eq(false)
      end
Robert Speicher's avatar
Robert Speicher committed
1588 1589
    end

1590 1591
    context 'when Gitaly ref_exists_branches feature is enabled' do
      it_behaves_like 'checks the existence of branches'
Robert Speicher's avatar
Robert Speicher committed
1592 1593
    end

1594
    context 'when Gitaly ref_exists_branches feature is disabled', :skip_gitaly_mock do
1595
      it_behaves_like 'checks the existence of branches'
Robert Speicher's avatar
Robert Speicher committed
1596 1597 1598
    end
  end

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
  describe '#batch_existence' do
    let(:refs) { ['deadbeef', SeedRepo::RubyBlob::ID, '909e6157199'] }

    it 'returns existing refs back' do
      result = repository.batch_existence(refs)

      expect(result).to eq([SeedRepo::RubyBlob::ID])
    end

    context 'existing: true' do
      it 'inverts meaning and returns non-existing refs' do
        result = repository.batch_existence(refs, existing: false)

        expect(result).to eq(%w(deadbeef 909e6157199))
      end
    end
  end

Robert Speicher's avatar
Robert Speicher committed
1617 1618
  describe '#local_branches' do
    before(:all) do
1619
      @repo = Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
Robert Speicher's avatar
Robert Speicher committed
1620 1621 1622 1623 1624 1625 1626
    end

    after(:all) do
      ensure_seeds
    end

    it 'returns the local branches' do
1627
      create_remote_branch(@repo, 'joe', 'remote_branch', 'master')
Robert Speicher's avatar
Robert Speicher committed
1628 1629 1630 1631 1632
      @repo.create_branch('local_branch', 'master')

      expect(@repo.local_branches.any? { |branch| branch.name == 'remote_branch' }).to eq(false)
      expect(@repo.local_branches.any? { |branch| branch.name == 'local_branch' }).to eq(true)
    end
1633

1634 1635 1636 1637
    it 'returns a Branch with UTF-8 fields' do
      branches = @repo.local_branches.to_a
      expect(branches.size).to be > 0
      branches.each do |branch|
1638 1639
        expect(branch.name).to be_utf8
        expect(branch.target).to be_utf8 unless branch.target.nil?
1640
      end
1641
    end
1642

1643
    it 'gets the branches from GitalyClient' do
Andrew Newdigate's avatar
Andrew Newdigate committed
1644
      expect_any_instance_of(Gitlab::GitalyClient::RefService).to receive(:local_branches)
1645 1646 1647
        .and_return([])
      @repo.local_branches
    end
1648

Andrew Newdigate's avatar
Andrew Newdigate committed
1649
    it_behaves_like 'wrapping gRPC errors', Gitlab::GitalyClient::RefService, :local_branches do
1650
      subject { @repo.local_branches }
1651
    end
Robert Speicher's avatar
Robert Speicher committed
1652 1653
  end

1654 1655 1656 1657 1658 1659 1660
  describe '#languages' do
    shared_examples 'languages' do
      it 'returns exactly the expected results' do
        languages = repository.languages('4b4918a572fa86f9771e5ba40fbd48e1eb03e2c6')
        expected_languages = [
          { value: 66.63, label: "Ruby", color: "#701516", highlight: "#701516" },
          { value: 22.96, label: "JavaScript", color: "#f1e05a", highlight: "#f1e05a" },
1661
          { value: 7.9, label: "HTML", color: "#e34c26", highlight: "#e34c26" },
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
          { value: 2.51, label: "CoffeeScript", color: "#244776", highlight: "#244776" }
        ]

        expect(languages.size).to eq(expected_languages.size)

        expected_languages.size.times do |i|
          a = expected_languages[i]
          b = languages[i]

          expect(a.keys.sort).to eq(b.keys.sort)
          expect(a[:value]).to be_within(0.1).of(b[:value])

          non_float_keys = a.keys - [:value]
          expect(a.values_at(*non_float_keys)).to eq(b.values_at(*non_float_keys))
        end
      end

      it "uses the repository's HEAD when no ref is passed" do
        lang = repository.languages.first

        expect(lang[:label]).to eq('Ruby')
      end
    end

    it_behaves_like 'languages'

1688
    context 'with rugged', :skip_gitaly_mock do
1689 1690 1691 1692
      it_behaves_like 'languages'
    end
  end

1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
  describe '#license_short_name' do
    shared_examples 'acquiring the Licensee license key' do
      subject { repository.license_short_name }

      context 'when no license file can be found' do
        let(:project) { create(:project, :repository) }
        let(:repository) { project.repository.raw_repository }

        before do
          project.repository.delete_file(project.owner, 'LICENSE', message: 'remove license', branch_name: 'master')
        end

        it { is_expected.to be_nil }
      end

      context 'when an mit license is found' do
        it { is_expected.to eq('mit') }
      end
    end

    context 'when gitaly is enabled' do
      it_behaves_like 'acquiring the Licensee license key'
    end

    context 'when gitaly is disabled', :disable_gitaly do
      it_behaves_like 'acquiring the Licensee license key'
    end
  end

1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
  describe '#with_repo_branch_commit' do
    context 'when comparing with the same repository' do
      let(:start_repository) { repository }

      context 'when the branch exists' do
        let(:start_branch_name) { 'master' }

        it 'yields the commit' do
          expect { |b| repository.with_repo_branch_commit(start_repository, start_branch_name, &b) }
            .to yield_with_args(an_instance_of(Gitlab::Git::Commit))
        end
      end

      context 'when the branch does not exist' do
        let(:start_branch_name) { 'definitely-not-master' }

        it 'yields nil' do
          expect { |b| repository.with_repo_branch_commit(start_repository, start_branch_name, &b) }
            .to yield_with_args(nil)
        end
      end
    end

    context 'when comparing with another repository' do
      let(:start_repository) { Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '') }

      context 'when the branch exists' do
        let(:start_branch_name) { 'master' }

        it 'yields the commit' do
          expect { |b| repository.with_repo_branch_commit(start_repository, start_branch_name, &b) }
            .to yield_with_args(an_instance_of(Gitlab::Git::Commit))
        end
      end

      context 'when the branch does not exist' do
        let(:start_branch_name) { 'definitely-not-master' }

        it 'yields nil' do
          expect { |b| repository.with_repo_branch_commit(start_repository, start_branch_name, &b) }
            .to yield_with_args(nil)
        end
      end
    end
  end

1768
  describe '#fetch_source_branch!' do
1769 1770 1771 1772
    shared_examples '#fetch_source_branch!' do
      let(:local_ref) { 'refs/merge-requests/1/head' }
      let(:repository) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '') }
      let(:source_repository) { Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '') }
1773

1774 1775 1776
      after do
        ensure_seeds
      end
1777

1778 1779 1780 1781 1782
      context 'when the branch exists' do
        context 'when the commit does not exist locally' do
          let(:source_branch) { 'new-branch-for-fetch-source-branch' }
          let(:source_rugged) { source_repository.rugged }
          let(:new_oid) { new_commit_edit_old_file(source_rugged).oid }
1783

1784 1785 1786
          before do
            source_rugged.branches.create(source_branch, new_oid)
          end
1787

1788 1789 1790 1791 1792
          it 'writes the ref' do
            expect(repository.fetch_source_branch!(source_repository, source_branch, local_ref)).to eq(true)
            expect(repository.commit(local_ref).sha).to eq(new_oid)
          end
        end
1793

1794 1795 1796
        context 'when the commit exists locally' do
          let(:source_branch) { 'master' }
          let(:expected_oid) { SeedRepo::LastCommit::ID }
1797

1798 1799 1800
          it 'writes the ref' do
            # Sanity check: the commit should already exist
            expect(repository.commit(expected_oid)).not_to be_nil
1801

1802 1803 1804 1805
            expect(repository.fetch_source_branch!(source_repository, source_branch, local_ref)).to eq(true)
            expect(repository.commit(local_ref).sha).to eq(expected_oid)
          end
        end
1806 1807
      end

1808 1809 1810 1811 1812 1813 1814
      context 'when the branch does not exist' do
        let(:source_branch) { 'definitely-not-master' }

        it 'does not write the ref' do
          expect(repository.fetch_source_branch!(source_repository, source_branch, local_ref)).to eq(false)
          expect(repository.commit(local_ref)).to be_nil
        end
1815 1816
      end
    end
1817 1818 1819 1820 1821 1822

    it_behaves_like '#fetch_source_branch!'

    context 'without gitaly', :skip_gitaly_mock do
      it_behaves_like '#fetch_source_branch!'
    end
1823 1824
  end

1825 1826 1827 1828 1829 1830 1831
  describe '#rm_branch' do
    shared_examples "user deleting a branch" do
      let(:project) { create(:project, :repository) }
      let(:repository) { project.repository.raw }
      let(:branch_name) { "to-be-deleted-soon" }

      before do
1832
        project.add_developer(user)
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
        repository.create_branch(branch_name)
      end

      it "removes the branch from the repo" do
        repository.rm_branch(branch_name, user: user)

        expect(repository.rugged.branches[branch_name]).to be_nil
      end
    end

    context "when Gitaly user_delete_branch is enabled" do
      it_behaves_like "user deleting a branch"
    end

1847
    context "when Gitaly user_delete_branch is disabled", :skip_gitaly_mock do
1848 1849 1850 1851
      it_behaves_like "user deleting a branch"
    end
  end

1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
  describe '#write_ref' do
    context 'validations' do
      using RSpec::Parameterized::TableSyntax

      where(:ref_path, :ref) do
        'foo bar' | '123'
        'foobar'  | "12\x003"
      end

      with_them do
        it 'raises ArgumentError' do
          expect { repository.write_ref(ref_path, ref) }.to raise_error(ArgumentError)
        end
      end
    end
  end

1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
  describe '#write_config' do
    before do
      repository.rugged.config["gitlab.fullpath"] = repository.path
    end

    shared_examples 'writing repo config' do
      context 'is given a path' do
        it 'writes it to disk' do
          repository.write_config(full_path: "not-the/real-path.git")

          config = File.read(File.join(repository.path, "config"))

          expect(config).to include("[gitlab]")
          expect(config).to include("fullpath = not-the/real-path.git")
        end
      end

      context 'it is given an empty path' do
        it 'does not write it to disk' do
          repository.write_config(full_path: "")

          config = File.read(File.join(repository.path, "config"))

          expect(config).to include("[gitlab]")
          expect(config).to include("fullpath = #{repository.path}")
        end
      end
    end

    context "when gitaly_write_config is enabled" do
      it_behaves_like "writing repo config"
    end

    context "when gitaly_write_config is disabled", :disable_gitaly do
      it_behaves_like "writing repo config"
    end
  end

1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
  describe '#merge' do
    let(:repository) do
      Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
    end
    let(:source_sha) { '913c66a37b4a45b9769037c55c2d238bd0942d2e' }
    let(:target_branch) { 'test-merge-target-branch' }

    before do
      repository.create_branch(target_branch, '6d394385cf567f80a8fd85055db1ab4c5295806f')
    end

    after do
      ensure_seeds
    end

    shared_examples '#merge' do
      it 'can perform a merge' do
        merge_commit_id = nil
        result = repository.merge(user, source_sha, target_branch, 'Test merge') do |commit_id|
          merge_commit_id = commit_id
        end

        expect(result.newrev).to eq(merge_commit_id)
        expect(result.repo_created).to eq(false)
        expect(result.branch_created).to eq(false)
      end
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943

      it 'returns nil if there was a concurrent branch update' do
        concurrent_update_id = '33f3729a45c02fc67d00adb1b8bca394b0e761d9'
        result = repository.merge(user, source_sha, target_branch, 'Test merge') do
          # This ref update should make the merge fail
          repository.write_ref(Gitlab::Git::BRANCH_REF_PREFIX + target_branch, concurrent_update_id)
        end

        # This 'nil' signals that the merge was not applied
        expect(result).to be_nil

Jacob Vosmaer's avatar
Jacob Vosmaer committed
1944
        # Our concurrent ref update should not have been undone
1945 1946
        expect(repository.find_branch(target_branch).target).to eq(concurrent_update_id)
      end
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
    end

    context 'with gitaly' do
      it_behaves_like '#merge'
    end

    context 'without gitaly', :skip_gitaly_mock do
      it_behaves_like '#merge'
    end
  end

1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
  describe '#ff_merge' do
    let(:repository) do
      Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
    end
    let(:branch_head) { '6d394385cf567f80a8fd85055db1ab4c5295806f' }
    let(:source_sha) { 'cfe32cf61b73a0d5e9f13e774abde7ff789b1660' }
    let(:target_branch) { 'test-ff-target-branch' }

    before do
      repository.create_branch(target_branch, branch_head)
    end

    after do
      ensure_seeds
    end

    subject { repository.ff_merge(user, source_sha, target_branch) }

1976 1977 1978 1979 1980
    shared_examples '#ff_merge' do
      it 'performs a ff_merge' do
        expect(subject.newrev).to eq(source_sha)
        expect(subject.repo_created).to be(false)
        expect(subject.branch_created).to be(false)
1981

1982 1983
        expect(repository.commit(target_branch).id).to eq(source_sha)
      end
1984

1985 1986
      context 'with a non-existing target branch' do
        subject { repository.ff_merge(user, source_sha, 'this-isnt-real') }
1987

1988 1989 1990
        it 'throws an ArgumentError' do
          expect { subject }.to raise_error(ArgumentError)
        end
1991 1992
      end

1993 1994
      context 'with a non-existing source commit' do
        let(:source_sha) { 'f001' }
1995

1996 1997 1998
        it 'throws an ArgumentError' do
          expect { subject }.to raise_error(ArgumentError)
        end
1999 2000
      end

2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
      context 'when the source sha is not a descendant of the branch head' do
        let(:source_sha) { '1a0b36b3cdad1d2ee32457c102a8c0b7056fa863' }

        it "doesn't perform the ff_merge" do
          expect { subject }.to raise_error(Gitlab::Git::CommitError)

          expect(repository.commit(target_branch).id).to eq(branch_head)
        end
      end
    end
2011

2012 2013 2014 2015 2016
    context 'with gitaly' do
      it "calls Gitaly's OperationService" do
        expect_any_instance_of(Gitlab::GitalyClient::OperationService)
          .to receive(:user_ff_branch).with(user, source_sha, target_branch)
          .and_return(nil)
2017

2018
        subject
2019
      end
2020 2021 2022 2023 2024 2025

      it_behaves_like '#ff_merge'
    end

    context 'without gitaly', :skip_gitaly_mock do
      it_behaves_like '#ff_merge'
2026 2027 2028
    end
  end

2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
  describe '#delete_all_refs_except' do
    let(:repository) do
      Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
    end

    before do
      repository.write_ref("refs/delete/a", "0b4bc9a49b562e85de7cc9e834518ea6828729b9")
      repository.write_ref("refs/also-delete/b", "12d65c8dd2b2676fa3ac47d955accc085a37a9c1")
      repository.write_ref("refs/keep/c", "6473c90867124755509e100d0d35ebdc85a0b6ae")
      repository.write_ref("refs/also-keep/d", "0b4bc9a49b562e85de7cc9e834518ea6828729b9")
    end

    after do
      ensure_seeds
    end

    it 'deletes all refs except those with the specified prefixes' do
      repository.delete_all_refs_except(%w(refs/keep refs/also-keep refs/heads))
      expect(repository.ref_exists?("refs/delete/a")).to be(false)
      expect(repository.ref_exists?("refs/also-delete/b")).to be(false)
      expect(repository.ref_exists?("refs/keep/c")).to be(true)
      expect(repository.ref_exists?("refs/also-keep/d")).to be(true)
      expect(repository.ref_exists?("refs/heads/master")).to be(true)
    end
  end

2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
  describe 'remotes' do
    let(:repository) do
      Gitlab::Git::Repository.new('default', TEST_MUTABLE_REPO_PATH, '')
    end
    let(:remote_name) { 'my-remote' }

    after do
      ensure_seeds
    end

    describe '#add_remote' do
      let(:url) { 'http://my-repo.git' }
      let(:mirror_refmap) { '+refs/*:refs/*' }

      it 'creates a new remote via Gitaly' do
        expect_any_instance_of(Gitlab::GitalyClient::RemoteService)
          .to receive(:add_remote).with(remote_name, url, mirror_refmap)

        repository.add_remote(remote_name, url, mirror_refmap: mirror_refmap)
      end

      context 'with Gitaly disabled', :skip_gitaly_mock do
        it 'creates a new remote via Rugged' do
          expect_any_instance_of(Rugged::RemoteCollection).to receive(:create)
            .with(remote_name, url)
          expect_any_instance_of(Rugged::Config).to receive(:[]=)
          .with("remote.#{remote_name}.mirror", true)
          expect_any_instance_of(Rugged::Config).to receive(:[]=)
          .with("remote.#{remote_name}.prune", true)
          expect_any_instance_of(Rugged::Config).to receive(:[]=)
            .with("remote.#{remote_name}.fetch", mirror_refmap)

          repository.add_remote(remote_name, url, mirror_refmap: mirror_refmap)
        end
      end
    end

    describe '#remove_remote' do
      it 'removes the remote via Gitaly' do
        expect_any_instance_of(Gitlab::GitalyClient::RemoteService)
          .to receive(:remove_remote).with(remote_name)

        repository.remove_remote(remote_name)
      end

      context 'with Gitaly disabled', :skip_gitaly_mock do
        it 'removes the remote via Rugged' do
          expect_any_instance_of(Rugged::RemoteCollection).to receive(:delete)
            .with(remote_name)

          repository.remove_remote(remote_name)
        end
      end
    end
  end

2111 2112 2113 2114 2115 2116 2117
  describe '#gitlab_projects' do
    subject { repository.gitlab_projects }

    it { expect(subject.shard_path).to eq(storage_path) }
    it { expect(subject.repository_relative_path).to eq(repository.relative_path) }
  end

2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
  describe '#bundle_to_disk' do
    shared_examples 'bundling to disk' do
      let(:save_path) { File.join(Dir.tmpdir, "repo-#{SecureRandom.hex}.bundle") }

      after do
        FileUtils.rm_rf(save_path)
      end

      it 'saves a bundle to disk' do
        repository.bundle_to_disk(save_path)

        success = system(
          *%W(#{Gitlab.config.git.bin_path} -C #{repository.path} bundle verify #{save_path}),
          [:out, :err] => '/dev/null'
        )
        expect(success).to be true
      end
    end

    context 'when Gitaly bundle_to_disk feature is enabled' do
      it_behaves_like 'bundling to disk'
    end

    context 'when Gitaly bundle_to_disk feature is disabled', :disable_gitaly do
      it_behaves_like 'bundling to disk'
    end
  end

2146 2147 2148 2149 2150 2151
  describe '#create_from_bundle' do
    shared_examples 'creating repo from bundle' do
      let(:bundle_path) { File.join(Dir.tmpdir, "repo-#{SecureRandom.hex}.bundle") }
      let(:project) { create(:project) }
      let(:imported_repo) { project.repository.raw }

2152 2153 2154 2155 2156 2157 2158
      before do
        expect(repository.bundle_to_disk(bundle_path)).to be true
      end

      after do
        FileUtils.rm_rf(bundle_path)
      end
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186

      it 'creates a repo from a bundle file' do
        expect(imported_repo).not_to exist

        result = imported_repo.create_from_bundle(bundle_path)

        expect(result).to be true
        expect(imported_repo).to exist
        expect { imported_repo.fsck }.not_to raise_exception
      end

      it 'creates a symlink to the global hooks dir' do
        imported_repo.create_from_bundle(bundle_path)
        hooks_path = File.join(imported_repo.path, 'hooks')

        expect(File.readlink(hooks_path)).to eq(Gitlab.config.gitlab_shell.hooks_path)
      end
    end

    context 'when Gitaly create_repo_from_bundle feature is enabled' do
      it_behaves_like 'creating repo from bundle'
    end

    context 'when Gitaly create_repo_from_bundle feature is disabled', :disable_gitaly do
      it_behaves_like 'creating repo from bundle'
    end
  end

2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
  describe '#checksum' do
    shared_examples 'calculating checksum' do
      it 'calculates the checksum for non-empty repo' do
        expect(repository.checksum).to eq '54f21be4c32c02f6788d72207fa03ad3bce725e4'
      end

      it 'returns 0000000000000000000000000000000000000000 for an empty repo' do
        FileUtils.rm_rf(File.join(storage_path, 'empty-repo.git'))

        system(git_env, *%W(#{Gitlab.config.git.bin_path} init --bare empty-repo.git),
               chdir: storage_path,
               out:   '/dev/null',
               err:   '/dev/null')

        empty_repo = described_class.new('default', 'empty-repo.git', '')

        expect(empty_repo.checksum).to eq '0000000000000000000000000000000000000000'
      end

      it 'raises a no repository exception when there is no repo' do
        broken_repo = described_class.new('default', 'a/path.git', '')

        expect { broken_repo.checksum }.to raise_error(Gitlab::Git::Repository::NoRepository)
      end
    end

    context 'when calculate_checksum Gitaly feature is enabled' do
      it_behaves_like 'calculating checksum'
    end

    context 'when calculate_checksum Gitaly feature is disabled', :disable_gitaly do
      it_behaves_like 'calculating checksum'

      describe 'when storage is broken', :broken_storage  do
        it 'raises a storage exception when storage is not available' do
          broken_repo = described_class.new('broken', 'a/path.git', '')

          expect { broken_repo.rugged }.to raise_error(Gitlab::Git::Storage::Inaccessible)
        end
      end

      it "raises a Gitlab::Git::Repository::Failure error if the `popen` call to git returns a non-zero exit code" do
        allow(repository).to receive(:popen).and_return(['output', nil])

        expect { repository.checksum }.to raise_error Gitlab::Git::Repository::ChecksumError
      end
    end
  end

2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
  context 'gitlab_projects commands' do
    let(:gitlab_projects) { repository.gitlab_projects }
    let(:timeout) { Gitlab.config.gitlab_shell.git_timeout }

    describe '#push_remote_branches' do
      subject do
        repository.push_remote_branches('downstream-remote', ['master'])
      end

      it 'executes the command' do
        expect(gitlab_projects).to receive(:push_branches)
          .with('downstream-remote', timeout, true, ['master'])
          .and_return(true)

        is_expected.to be_truthy
      end

      it 'raises an error if the command fails' do
        allow(gitlab_projects).to receive(:output) { 'error' }
        expect(gitlab_projects).to receive(:push_branches)
          .with('downstream-remote', timeout, true, ['master'])
          .and_return(false)

        expect { subject }.to raise_error(Gitlab::Git::CommandError, 'error')
      end
    end
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308

    describe '#delete_remote_branches' do
      subject do
        repository.delete_remote_branches('downstream-remote', ['master'])
      end

      it 'executes the command' do
        expect(gitlab_projects).to receive(:delete_remote_branches)
          .with('downstream-remote', ['master'])
          .and_return(true)

        is_expected.to be_truthy
      end

      it 'raises an error if the command fails' do
        allow(gitlab_projects).to receive(:output) { 'error' }
        expect(gitlab_projects).to receive(:delete_remote_branches)
          .with('downstream-remote', ['master'])
          .and_return(false)

        expect { subject }.to raise_error(Gitlab::Git::CommandError, 'error')
      end
    end

    describe '#delete_remote_branches' do
      subject do
        repository.delete_remote_branches('downstream-remote', ['master'])
      end

      it 'executes the command' do
        expect(gitlab_projects).to receive(:delete_remote_branches)
          .with('downstream-remote', ['master'])
          .and_return(true)

        is_expected.to be_truthy
      end

      it 'raises an error if the command fails' do
        allow(gitlab_projects).to receive(:output) { 'error' }
        expect(gitlab_projects).to receive(:delete_remote_branches)
          .with('downstream-remote', ['master'])
          .and_return(false)

        expect { subject }.to raise_error(Gitlab::Git::CommandError, 'error')
      end
    end

2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
    describe '#clean_stale_repository_files' do
      let(:worktree_path) { File.join(repository.path, 'worktrees', 'delete-me') }

      it 'cleans up the files' do
        repository.with_worktree(worktree_path, 'master', env: ENV) do
          FileUtils.touch(worktree_path, mtime: Time.now - 8.hours)
          # git rev-list --all will fail in git 2.16 if HEAD is pointing to a non-existent object,
          # but the HEAD must be 40 characters long or git will ignore it.
          File.write(File.join(worktree_path, 'HEAD'), Gitlab::Git::BLANK_SHA)

          # git 2.16 fails with "fatal: bad object HEAD"
          expect { repository.rev_list(including: :all) }.to raise_error(Gitlab::Git::Repository::GitError)

          repository.clean_stale_repository_files

          expect { repository.rev_list(including: :all) }.not_to raise_error
          expect(File.exist?(worktree_path)).to be_falsey
        end
      end

      it 'increments a counter upon an error' do
        expect(repository.gitaly_repository_client).to receive(:cleanup).and_raise(Gitlab::Git::CommandError)

        counter = double(:counter)

        expect(counter).to receive(:increment)
        expect(Gitlab::Metrics).to receive(:counter).with(:failed_repository_cleanup_total,
                                                          'Number of failed repository cleanup events').and_return(counter)

        repository.clean_stale_repository_files
      end
    end

2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
    describe '#delete_remote_branches' do
      subject do
        repository.delete_remote_branches('downstream-remote', ['master'])
      end

      it 'executes the command' do
        expect(gitlab_projects).to receive(:delete_remote_branches)
          .with('downstream-remote', ['master'])
          .and_return(true)

        is_expected.to be_truthy
      end

      it 'raises an error if the command fails' do
        allow(gitlab_projects).to receive(:output) { 'error' }
        expect(gitlab_projects).to receive(:delete_remote_branches)
          .with('downstream-remote', ['master'])
          .and_return(false)

        expect { subject }.to raise_error(Gitlab::Git::CommandError, 'error')
      end
    end
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382

    describe '#squash' do
      let(:squash_id) { '1' }
      let(:branch_name) { 'fix' }
      let(:start_sha) { '4b4918a572fa86f9771e5ba40fbd48e1eb03e2c6' }
      let(:end_sha) { '12d65c8dd2b2676fa3ac47d955accc085a37a9c1' }

      subject do
        opts = {
          branch: branch_name,
          start_sha: start_sha,
          end_sha: end_sha,
          author: user,
          message: 'Squash commit message'
        }

        repository.squash(user, squash_id, opts)
      end

2383
      context 'sparse checkout', :skip_gitaly_mock do
2384 2385
        let(:expected_files) { %w(files files/js files/js/application.js) }

2386
        it 'checks out only the files in the diff' do
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
          allow(repository).to receive(:with_worktree).and_wrap_original do |m, *args|
            m.call(*args) do
              worktree_path = args[0]
              files_pattern = File.join(worktree_path, '**', '*')
              expected = expected_files.map do |path|
                File.expand_path(path, worktree_path)
              end

              expect(Dir[files_pattern]).to eq(expected)
            end
          end

          subject
        end
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425

        context 'when the diff contains a rename' do
          let(:repo) { Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '').rugged }
          let(:end_sha) { new_commit_move_file(repo).oid }

          after do
            # Erase our commits so other tests get the original repo
            repo = Gitlab::Git::Repository.new('default', TEST_REPO_PATH, '').rugged
            repo.references.update('refs/heads/master', SeedRepo::LastCommit::ID)
          end

          it 'does not include the renamed file in the sparse checkout' do
            allow(repository).to receive(:with_worktree).and_wrap_original do |m, *args|
              m.call(*args) do
                worktree_path = args[0]
                files_pattern = File.join(worktree_path, '**', '*')

                expect(Dir[files_pattern]).not_to include('CHANGELOG')
                expect(Dir[files_pattern]).not_to include('encoding/CHANGELOG')
              end
            end

            subject
          end
        end
2426
      end
2427 2428 2429 2430 2431 2432 2433 2434

      context 'with an ASCII-8BIT diff', :skip_gitaly_mock do
        let(:diff) { "diff --git a/README.md b/README.md\nindex faaf198..43c5edf 100644\n--- a/README.md\n+++ b/README.md\n@@ -1,4 +1,4 @@\n-testme\n+✓ testme\n ======\n \n Sample repo for testing gitlab features\n" }

        it 'applies a ASCII-8BIT diff' do
          allow(repository).to receive(:run_git!).and_call_original
          allow(repository).to receive(:run_git!).with(%W(diff --binary #{start_sha}...#{end_sha})).and_return(diff.force_encoding('ASCII-8BIT'))

2435
          expect(subject).to match(/\h{40}/)
2436 2437
        end
      end
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451

      context 'with trailing whitespace in an invalid patch', :skip_gitaly_mock do
        let(:diff) { "diff --git a/README.md b/README.md\nindex faaf198..43c5edf 100644\n--- a/README.md\n+++ b/README.md\n@@ -1,4 +1,4 @@\n-testme\n+   \n ======   \n \n Sample repo for testing gitlab features\n" }

        it 'does not include whitespace warnings in the error' do
          allow(repository).to receive(:run_git!).and_call_original
          allow(repository).to receive(:run_git!).with(%W(diff --binary #{start_sha}...#{end_sha})).and_return(diff.force_encoding('ASCII-8BIT'))

          expect { subject }.to raise_error do |error|
            expect(error).to be_a(described_class::GitError)
            expect(error.message).not_to include('trailing whitespace')
          end
        end
      end
2452
    end
2453 2454
  end

2455 2456 2457
  def create_remote_branch(repository, remote_name, branch_name, source_branch_name)
    source_branch = repository.branches.find { |branch| branch.name == source_branch_name }
    rugged = repository.rugged
Robert Speicher's avatar
Robert Speicher committed
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
    rugged.references.create("refs/remotes/#{remote_name}/#{branch_name}", source_branch.dereferenced_target.sha)
  end

  # Build the options hash that's passed to Rugged::Commit#create
  def commit_options(repo, index, message)
    options = {}
    options[:tree] = index.write_tree(repo)
    options[:author] = {
      email: "test@example.com",
      name: "Test Author",
      time: Time.gm(2014, "mar", 3, 20, 15, 1)
    }
    options[:committer] = {
      email: "test@example.com",
      name: "Test Author",
      time: Time.gm(2014, "mar", 3, 20, 15, 1)
    }
    options[:message] ||= message
    options[:parents] = repo.empty? ? [] : [repo.head.target].compact
    options[:update_ref] = "HEAD"

    options
  end

  # Writes a new commit to the repo and returns a Rugged::Commit.  Replaces the
  # contents of CHANGELOG with a single new line of text.
  def new_commit_edit_old_file(repo)
    oid = repo.write("I replaced the changelog with this text", :blob)
    index = repo.index
    index.read_tree(repo.head.target.tree)
    index.add(path: "CHANGELOG", oid: oid, mode: 0100644)

    options = commit_options(
      repo,
      index,
      "Edit CHANGELOG in its original location"
    )

    sha = Rugged::Commit.create(repo, options)
    repo.lookup(sha)
  end

  # Writes a new commit to the repo and returns a Rugged::Commit.  Replaces the
  # contents of encoding/CHANGELOG with new text.
  def new_commit_edit_new_file(repo)
    oid = repo.write("I'm a new changelog with different text", :blob)
    index = repo.index
    index.read_tree(repo.head.target.tree)
    index.add(path: "encoding/CHANGELOG", oid: oid, mode: 0100644)

    options = commit_options(repo, index, "Edit encoding/CHANGELOG")

    sha = Rugged::Commit.create(repo, options)
    repo.lookup(sha)
  end

  # Writes a new commit to the repo and returns a Rugged::Commit.  Moves the
  # CHANGELOG file to the encoding/ directory.
  def new_commit_move_file(repo)
    blob_oid = repo.head.target.tree.detect { |i| i[:name] == "CHANGELOG" }[:oid]
    file_content = repo.lookup(blob_oid).content
    oid = repo.write(file_content, :blob)
    index = repo.index
    index.read_tree(repo.head.target.tree)
    index.add(path: "encoding/CHANGELOG", oid: oid, mode: 0100644)
    index.remove("CHANGELOG")

    options = commit_options(repo, index, "Move CHANGELOG to encoding/")

    sha = Rugged::Commit.create(repo, options)
    repo.lookup(sha)
  end
2530 2531 2532 2533 2534 2535

  def refs(dir)
    IO.popen(%W[git -C #{dir} for-each-ref], &:read).split("\n").map do |line|
      line.split("\t").last
    end
  end
Robert Speicher's avatar
Robert Speicher committed
2536
end