<commit_before>require "gemstash"
require "dalli"
require "fileutils"
require "sequel"
require "uri"

module Gemstash
  # Storage for application-wide variables and configuration.
  class Env
    # The Gemstash::Env must be set before being retreived via
    # Gemstash::Env.current. This error is thrown when that is not honored.
    class EnvNotSetError < StandardError
    end

    # Little module to provide easy access to the current Gemstash::Env.
    module Helper
    private

      def gemstash_env
        Gemstash::Env.current
      end
    end

    # Rack middleware to set the Gemstash::Env for the app.
    class RackMiddleware
      def initialize(app, gemstash_env)
        @app = app
        @gemstash_env = gemstash_env
      end

      def call(env)
        env["gemstash.env"] = @gemstash_env
        @app.call(env)
      end
    end

    def initialize(config = nil, cache: nil, db: nil)
      @config = config
      @cache = cache
      @db = db
    end

    def self.available?
      !Thread.current[:gemstash_env].nil?
    end

    def self.current
      raise EnvNotSetError unless Thread.current[:gemstash_env]
      Thread.current[:gemstash_env]
    end

    def self.current=(value)
      Thread.current[:gemstash_env] = value
    end

    def self.daemonized?
      if @daemonized.nil?
        raise "Daemonized hasn't been set yet!"
      else
        @daemonized
      end
    end

    def self.daemonized=(value)
      value = false if value.nil?
      @daemonized = value
    end

    def config
      @config ||= Gemstash::Configuration.new
    end

    def config=(value)
      reset
      @config = value
    end

    def reset
      @config = nil
      @cache = nil
      @cache_client = nil
      @db = nil
    end

    def base_path
      dir = config[:base_path]

      if config.default?(:base_path)
        FileUtils.mkpath(dir) unless Dir.exist?(dir)
      else
        raise "Base path '#{dir}' is not writable" unless File.writable?(dir)
      end

      dir
    end

    def base_file(path)
      File.join(base_path, path)
    end

    def rackup
      File.expand_path("../config.ru", __FILE__)
    end

    def db
      @db ||= begin
        case config[:db_adapter]
        when "sqlite3"
          db_path = base_file("gemstash.db")

          if RUBY_PLATFORM == "java"
            db = Sequel.connect("jdbc:sqlite:#{db_path}")
          else
            db = Sequel.connect("sqlite://#{URI.escape(db_path)}")
          end
        when "postgres"
          db = Sequel.connect(config[:db_url])
        else
          raise "Unsupported DB adapter: '#{config[:db_adapter]}'"
        end

        Gemstash::Env.migrate(db)
        db
      end
    end

    def self.migrate(db)
      Sequel.extension :migration
      migrations_dir = File.expand_path("../migrations", __FILE__)
      Sequel::Migrator.run(db, migrations_dir, :use_transactions => true)
    end

    def cache
      @cache ||= Gemstash::Cache.new(cache_client)
    end

    def cache_client
      @cache_client ||= begin<commit_msg>Use 1 connection when using SQLite (fixes #42)<commit_after>require "gemstash"
require "dalli"
require "fileutils"
require "sequel"
require "uri"

module Gemstash
  # Storage for application-wide variables and configuration.
  class Env
    # The Gemstash::Env must be set before being retreived via
    # Gemstash::Env.current. This error is thrown when that is not honored.
    class EnvNotSetError < StandardError
    end

    # Little module to provide easy access to the current Gemstash::Env.
    module Helper
    private

      def gemstash_env
        Gemstash::Env.current
      end
    end

    # Rack middleware to set the Gemstash::Env for the app.
    class RackMiddleware
      def initialize(app, gemstash_env)
        @app = app
        @gemstash_env = gemstash_env
      end

      def call(env)
        env["gemstash.env"] = @gemstash_env
        @app.call(env)
      end
    end

    def initialize(config = nil, cache: nil, db: nil)
      @config = config
      @cache = cache
      @db = db
    end

    def self.available?
      !Thread.current[:gemstash_env].nil?
    end

    def self.current
      raise EnvNotSetError unless Thread.current[:gemstash_env]
      Thread.current[:gemstash_env]
    end

    def self.current=(value)
      Thread.current[:gemstash_env] = value
    end

    def self.daemonized?
      if @daemonized.nil?
        raise "Daemonized hasn't been set yet!"
      else
        @daemonized
      end
    end

    def self.daemonized=(value)
      value = false if value.nil?
      @daemonized = value
    end

    def config
      @config ||= Gemstash::Configuration.new
    end

    def config=(value)
      reset
      @config = value
    end

    def reset
      @config = nil
      @cache = nil
      @cache_client = nil
      @db = nil
    end

    def base_path
      dir = config[:base_path]

      if config.default?(:base_path)
        FileUtils.mkpath(dir) unless Dir.exist?(dir)
      else
        raise "Base path '#{dir}' is not writable" unless File.writable?(dir)
      end

      dir
    end

    def base_file(path)
      File.join(base_path, path)
    end

    def rackup
      File.expand_path("../config.ru", __FILE__)
    end

    def db
      @db ||= begin
        case config[:db_adapter]
        when "sqlite3"
          db_path = base_file("gemstash.db")

          if RUBY_PLATFORM == "java"
            db = Sequel.connect("jdbc:sqlite:#{db_path}", max_connections: 1)
          else
            db = Sequel.connect("sqlite://#{URI.escape(db_path)}", max_connections: 1)
          end
        when "postgres"
          db = Sequel.connect(config[:db_url])
        else
          raise "Unsupported DB adapter: '#{config[:db_adapter]}'"
        end

        Gemstash::Env.migrate(db)
        db
      end
    end

    def self.migrate(db)
      Sequel.extension :migration
      migrations_dir = File.expand_path("../migrations", __FILE__)
      Sequel::Migrator.run(db, migrations_dir, :use_transactions => true)
    end

    def cache
      @cache ||= Gemstash::Cache.new(cache_client)
    end

    def cache_client
      @cache_client ||= begin
{'fraction_non_alphanumeric': 0.09415005671690163, 'fraction_numerical': 0.0011343380327337547, 'mean_word_length': 2.1489795918367345, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3666697', 'n_tokens_mistral': 1979, 'n_tokens_neox': 1942, 'n_words': 510}