hook_env.rb 1.5 KB
Newer Older
1 2
# Gitaly note: JV: no RPC's here.

3 4 5
module Gitlab
  module Git
    # Ephemeral (per request) storage for environment variables that some Git
6
    # commands need during internal API calls made from Git push hooks.
7 8 9 10 11 12
    #
    # For example, in pre-receive hooks, new objects are put in a temporary
    # $GIT_OBJECT_DIRECTORY. Without it set, the new objects cannot be retrieved
    # (this would break push rules for instance).
    #
    # This class is thread-safe via RequestStore.
13
    class HookEnv
14 15 16
      WHITELISTED_VARIABLES = %w[
        GIT_OBJECT_DIRECTORY_RELATIVE
        GIT_ALTERNATE_OBJECT_DIRECTORIES_RELATIVE
17 18
      ].freeze

19
      def self.set(gl_repository, env)
20 21
        return unless RequestStore.active?

22 23 24 25
        raise "missing gl_repository" if gl_repository.blank?

        RequestStore.store[:gitlab_git_env] ||= {}
        RequestStore.store[:gitlab_git_env][gl_repository] = whitelist_git_env(env)
26 27
      end

28
      def self.all(gl_repository)
29 30
        return {} unless RequestStore.active?

31 32
        h = RequestStore.fetch(:gitlab_git_env) { {} }
        h.fetch(gl_repository, {})
33 34
      end

35
      def self.to_env_hash(gl_repository)
36 37
        env = {}

38
        all(gl_repository).compact.each do |key, value|
39 40 41 42 43 44 45
          value = value.join(File::PATH_SEPARATOR) if value.is_a?(Array)
          env[key.to_s] = value
        end

        env
      end

46
      def self.whitelist_git_env(env)
47
        env.select { |key, _| WHITELISTED_VARIABLES.include?(key.to_s) }.with_indifferent_access
48 49 50 51
      end
    end
  end
end