new_file_action.rb 2.3 KB
Newer Older
1 2
require_relative 'file_action'

3 4
module Gitlab
  module Satellite
5
    class NewFileAction < FileAction
R
Riyad Preukschas 已提交
6 7 8
      # Updates the files content and creates a new commit for it
      #
      # Returns false if the ref has been updated while editing the file
K
Kevin Lyda 已提交
9
      # Returns false if committing the change fails
D
Dmitriy Zaporozhets 已提交
10
      # Returns false if pushing from the satellite to bare repo failed or was rejected
R
Riyad Preukschas 已提交
11
      # Returns true otherwise
V
Valery Sizov 已提交
12
      def commit!(content, commit_message, encoding, new_branch = nil)
13 14 15
        in_locked_and_timed_satellite do |repo|
          prepare_satellite!(repo)

D
Dmitriy Zaporozhets 已提交
16
          # create target branch in satellite at the corresponding commit from bare repo
17
          current_ref =
D
Dmitriy Zaporozhets 已提交
18
            if @project.empty_repo?
19 20
              # skip this step if we want to add first file to empty repo
              Satellite::PARKING_BRANCH
D
Dmitriy Zaporozhets 已提交
21
            else
22
              repo.git.checkout({ raise: true, timeout: true, b: true }, ref, "origin/#{ref}")
D
Dmitriy Zaporozhets 已提交
23
              ref
24
            end
25

26
          file_path_in_satellite = File.join(repo.working_dir, file_path)
27
          dir_name_in_satellite = File.dirname(file_path_in_satellite)
28 29

          # Prevent relative links
30 31
          unless safe_path?(file_path_in_satellite)
            Gitlab::GitLogger.error("FileAction: Relative path not allowed")
32 33 34
            return false
          end

35 36 37 38
          # Create dir if not exists
          FileUtils.mkdir_p(dir_name_in_satellite)

          # Write file
39
          write_file(file_path_in_satellite, content, encoding)
40

41 42 43
          # add new file
          repo.add(file_path_in_satellite)

44 45 46 47
          # commit the changes
          # will raise CommandFailed when commit fails
          repo.git.commit(raise: true, timeout: true, a: true, m: commit_message)

V
Valery Sizov 已提交
48 49 50 51 52 53
          target_branch = if new_branch.present? && !@project.empty_repo?
                            "#{ref}:#{new_branch}"
                          else
                            "#{current_ref}:#{ref}"
                          end

D
Dmitriy Zaporozhets 已提交
54
          # push commit back to bare repo
55
          # will raise CommandFailed when push fails
V
Valery Sizov 已提交
56
          repo.git.push({ raise: true, timeout: true }, :origin, target_branch)
57 58 59 60 61 62 63 64 65 66 67

          # everything worked
          true
        end
      rescue Grit::Git::CommandFailed => ex
        Gitlab::GitLogger.error(ex.message)
        false
      end
    end
  end
end