repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/validates_uniqueness_of_string.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/validates_uniqueness_of_string.rb
class CreateValidatesUniquenessOf < ActiveRecord::Migration def self.up create_table "validates_uniqueness_of", :force => true do |t| t.column :cs_string, :string t.column :ci_string, :string t.column :content, :text end end def self.down drop_table "validates_uniqueness_of" end end class ValidatesUniquenessOfString < ActiveRecord::Base self.set_table_name "validates_uniqueness_of" validates_uniqueness_of :cs_string, :case_sensitive => true validates_uniqueness_of :ci_string, :case_sensitive => false end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/pg.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/pg.rb
# Stub library for postgresql -- allows Rails to load # postgresql_adapter without error Other than postgres-pr, there's no # other way to use PostgreSQL on JRuby anyway, right? If you've # installed ar-jdbc you probably want to use that to connect to pg.
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter.rb
if defined?(JRUBY_VERSION) begin tried_gem ||= false require 'active_record/version' rescue LoadError raise if tried_gem require 'rubygems' gem 'activerecord' tried_gem = true retry end if ActiveRecord::VERSION::MAJOR < 2 if defined?(RAILS_CONNECTION_ADAPTERS) RAILS_CONNECTION_ADAPTERS << %q(jdbc) else RAILS_CONNECTION_ADAPTERS = %w(jdbc) end if ActiveRecord::VERSION::MAJOR == 1 && ActiveRecord::VERSION::MINOR == 14 require 'active_record/connection_adapters/jdbc_adapter' end else require 'active_record' require 'active_record/connection_adapters/jdbc_adapter' end else warn "ActiveRecord-JDBC is for use with JRuby only" end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/activerecord-jdbc-adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/activerecord-jdbc-adapter.rb
require 'jdbc_adapter' begin require 'jdbc_adapter/railtie' rescue LoadError # Assume we don't have railties in this version of AR end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_db2.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_db2.rb
module JdbcSpec module DB2 def self.adapter_matcher(name, config) if name =~ /db2/i return config[:url] =~ /^jdbc:derby:net:/ ? ::JdbcSpec::Derby : self end false end def self.adapter_selector [/db2/i, lambda {|cfg,adapt| if cfg[:url] =~ /^jdbc:derby:net:/ adapt.extend(::JdbcSpec::Derby) else adapt.extend(::JdbcSpec::DB2) end }] end def self.extended(obj) # Ignore these 4 system tables ActiveRecord::SchemaDumper.ignore_tables |= %w{hmon_atm_info hmon_collection policy stmg_dbsize_info} end module Column def type_cast(value) return nil if value.nil? || value =~ /^\s*null\s*$/i case type when :string then value when :integer then defined?(value.to_i) ? value.to_i : (value ? 1 : 0) when :primary_key then defined?(value.to_i) ? value.to_i : (value ? 1 : 0) when :float then value.to_f when :datetime then cast_to_date_or_time(value) when :timestamp then cast_to_time(value) when :time then cast_to_time(value) else value end end def cast_to_date_or_time(value) return value if value.is_a? Date return nil if value.blank? guess_date_or_time((value.is_a? Time) ? value : cast_to_time(value)) end def cast_to_time(value) return value if value.is_a? Time time_array = ParseDate.parsedate value time_array[0] ||= 2000; time_array[1] ||= 1; time_array[2] ||= 1; Time.send(ActiveRecord::Base.default_timezone, *time_array) rescue nil end def guess_date_or_time(value) (value.hour == 0 and value.min == 0 and value.sec == 0) ? Date.new(value.year, value.month, value.day) : value end end def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) id = super unless id table_name = sql.split(/\s/)[2] result = select(ActiveRecord::Base.send(:sanitize_sql, %[select IDENTITY_VAL_LOCAL() as last_insert_id from #{table_name}], nil)) id = result.last['last_insert_id'] end id end def modify_types(tp) tp[:primary_key] = 'int not null generated by default as identity (start with 1) primary key' tp[:string][:limit] = 255 tp[:integer][:limit] = nil tp[:boolean][:limit] = nil tp end def adapter_name 'DB2' end def add_limit_offset!(sql, options) if limit = options[:limit] offset = options[:offset] || 0 sql.gsub!(/SELECT/i, 'SELECT B.* FROM (SELECT A.*, row_number() over () AS internal$rownum FROM (SELECT') sql << ") A ) B WHERE B.internal$rownum > #{offset} AND B.internal$rownum <= #{limit + offset}" end end def pk_and_sequence_for(table) # In JDBC/DB2 side, only upcase names of table and column are handled. keys = super(table.upcase) if keys[0] # In ActiveRecord side, only downcase names of table and column are handled. keys[0] = keys[0].downcase end keys end def quote_column_name(column_name) column_name end def quote(value, column = nil) # :nodoc: if column && column.type == :primary_key return value.to_s end if column && (column.type == :decimal || column.type == :integer) && value return value.to_s end case value when String if column && column.type == :binary "BLOB('#{quote_string(value)}')" else "'#{quote_string(value)}'" end else super end end def quote_string(string) string.gsub(/'/, "''") # ' (for ruby-mode) end def quoted_true '1' end def quoted_false '0' end def recreate_database(name) do_not_drop = ["stmg_dbsize_info","hmon_atm_info","hmon_collection","policy"] tables.each do |table| unless do_not_drop.include?(table) drop_table(table) end end end def remove_index(table_name, options = { }) execute "DROP INDEX #{quote_column_name(index_name(table_name, options))}" end # This method makes tests pass without understanding why. # Don't use this in production. def columns(table_name, name = nil) super.select do |col| # strip out "magic" columns from DB2 (?) !/rolename|roleid|create_time|auditpolicyname|auditpolicyid|remarks/.match(col.name) end end def add_quotes(name) return name unless name %Q{"#{name}"} end def strip_quotes(str) return str unless str return str unless /^(["']).*\1$/ =~ str str[1..-2] end def expand_double_quotes(name) return name unless name && name['"'] name.gsub(/"/,'""') end def structure_dump #:nodoc: definition="" rs = @connection.connection.meta_data.getTables(nil,nil,nil,["TABLE"].to_java(:string)) while rs.next tname = rs.getString(3) definition << "CREATE TABLE #{tname} (\n" rs2 = @connection.connection.meta_data.getColumns(nil,nil,tname,nil) first_col = true while rs2.next col_name = add_quotes(rs2.getString(4)); default = "" d1 = rs2.getString(13) default = d1 ? " DEFAULT #{d1}" : "" type = rs2.getString(6) col_size = rs2.getString(7) nulling = (rs2.getString(18) == 'NO' ? " NOT NULL" : "") create_col_string = add_quotes(expand_double_quotes(strip_quotes(col_name))) + " " + type + "" + nulling + default if !first_col create_col_string = ",\n #{create_col_string}" else create_col_string = " #{create_col_string}" end definition << create_col_string first_col = false end definition << ");\n\n" end definition end def dump_schema_information begin if (current_schema = ActiveRecord::Migrator.current_version) > 0 #TODO: Find a way to get the DB2 instace name to properly form the statement return "INSERT INTO DB2INST2.SCHEMA_INFO (version) VALUES (#{current_schema})" end rescue ActiveRecord::StatementInvalid # No Schema Info end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/rake_tasks.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/rake_tasks.rb
if defined?(Rake.application) && Rake.application && ENV["SKIP_AR_JDBC_RAKE_REDEFINES"].nil? jdbc_rakefile = File.dirname(__FILE__) + "/jdbc.rake" if Rake.application.lookup("db:create") # rails tasks already defined; load the override tasks now load jdbc_rakefile else # rails tasks not loaded yet; load as an import Rake.application.add_import(jdbc_rakefile) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/version.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/version.rb
module JdbcAdapter module Version VERSION = "0.9.7" end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_postgre.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_postgre.rb
module ::JdbcSpec # Don't need to load native postgres adapter $LOADED_FEATURES << "active_record/connection_adapters/postgresql_adapter.rb" module ActiveRecordExtensions add_method_to_remove_from_ar_base(:postgresql_connection) def postgresql_connection(config) require File.dirname(__FILE__) + "/../active_record/connection_adapters/postgresql_adapter" config[:host] ||= "localhost" config[:port] ||= 5432 config[:url] ||= "jdbc:postgresql://#{config[:host]}:#{config[:port]}/#{config[:database]}" config[:url] << config[:pg_params] if config[:pg_params] config[:driver] ||= "org.postgresql.Driver" conn = jdbc_connection(config) conn.execute("SET SEARCH_PATH TO #{config[:schema_search_path]}") if config[:schema_search_path] conn end end module PostgreSQL def self.extended(mod) mod.class.class_eval do alias_chained_method :insert, :query_dirty, :insert end end def self.adapter_matcher(name, *) name =~ /postgre/i ? self : false end def self.column_selector [/postgre/i, lambda {|cfg,col| col.extend(::JdbcSpec::PostgreSQL::Column)}] end def self.jdbc_connection_class ::ActiveRecord::ConnectionAdapters::PostgresJdbcConnection end module Column def type_cast(value) case type when :boolean then cast_to_boolean(value) else super end end def simplified_type(field_type) return :integer if field_type =~ /^serial/i return :string if field_type =~ /\[\]$/i || field_type =~ /^interval/i return :string if field_type =~ /^(?:point|lseg|box|"?path"?|polygon|circle)/i return :datetime if field_type =~ /^timestamp/i return :float if field_type =~ /^real|^money/i return :binary if field_type =~ /^bytea/i return :boolean if field_type =~ /^bool/i super end def cast_to_boolean(value) return nil if value.nil? if value == true || value == false value else %w(true t 1).include?(value.to_s.downcase) end end # Post process default value from JDBC into a Rails-friendly format (columns{-internal}) def default_value(value) # Boolean types return "t" if value =~ /true/i return "f" if value =~ /false/i # Char/String/Bytea type values return $1 if value =~ /^'(.*)'::(bpchar|text|character varying|bytea)$/ # Numeric values return value if value =~ /^-?[0-9]+(\.[0-9]*)?/ # Fixed dates / timestamp return $1 if value =~ /^'(.+)'::(date|timestamp)/ # Anything else is blank, some user type, or some function # and we can't know the value of that, so return nil. return nil end end def modify_types(tp) tp[:primary_key] = "serial primary key" tp[:string][:limit] = 255 tp[:integer][:limit] = nil tp[:boolean][:limit] = nil tp end def adapter_name #:nodoc: 'PostgreSQL' end def postgresql_version @postgresql_version ||= begin value = select_value('SELECT version()') if value =~ /PostgreSQL (\d+)\.(\d+)\.(\d+)/ ($1.to_i * 10000) + ($2.to_i * 100) + $3.to_i else 0 end end end # Does PostgreSQL support migrations? def supports_migrations? true end # Does PostgreSQL support standard conforming strings? def supports_standard_conforming_strings? # Temporarily set the client message level above error to prevent unintentional # error messages in the logs when working on a PostgreSQL database server that # does not support standard conforming strings. client_min_messages_old = client_min_messages self.client_min_messages = 'panic' # postgres-pr does not raise an exception when client_min_messages is set higher # than error and "SHOW standard_conforming_strings" fails, but returns an empty # PGresult instead. has_support = select('SHOW standard_conforming_strings').to_a[0][0] rescue false self.client_min_messages = client_min_messages_old has_support end def supports_insert_with_returning? postgresql_version >= 80200 end def supports_ddl_transactions? true end def supports_savepoints? true end def create_savepoint execute("SAVEPOINT #{current_savepoint_name}") end def rollback_to_savepoint execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}") end def release_savepoint execute("RELEASE SAVEPOINT #{current_savepoint_name}") end # Returns the configured supported identifier length supported by PostgreSQL, # or report the default of 63 on PostgreSQL 7.x. def table_alias_length @table_alias_length ||= (postgresql_version >= 80000 ? select('SHOW max_identifier_length').to_a[0][0].to_i : 63) end def default_sequence_name(table_name, pk = nil) default_pk, default_seq = pk_and_sequence_for(table_name) default_seq || "#{table_name}_#{pk || default_pk || 'id'}_seq" end # Resets sequence to the max value of the table's pk if present. def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc: unless pk and sequence default_pk, default_sequence = pk_and_sequence_for(table) pk ||= default_pk sequence ||= default_sequence end if pk if sequence quoted_sequence = quote_column_name(sequence) select_value <<-end_sql, 'Reset sequence' SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false) end_sql else @logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger end end end def quote_regclass(table_name) table_name.to_s.split('.').map do |part| part =~ /".*"/i ? part : quote_table_name(part) end.join('.') end # Find a table's primary key and sequence. def pk_and_sequence_for(table) #:nodoc: # First try looking for a sequence with a dependency on the # given table's primary key. result = select(<<-end_sql, 'PK and serial sequence')[0] SELECT attr.attname, seq.relname FROM pg_class seq, pg_attribute attr, pg_depend dep, pg_namespace name, pg_constraint cons WHERE seq.oid = dep.objid AND seq.relkind = 'S' AND attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid AND attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1] AND cons.contype = 'p' AND dep.refobjid = '#{table}'::regclass end_sql if result.nil? or result.empty? # If that fails, try parsing the primary key's default value. # Support the 7.x and 8.0 nextval('foo'::text) as well as # the 8.1+ nextval('foo'::regclass). result = select(<<-end_sql, 'PK and custom sequence')[0] SELECT attr.attname, CASE WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN substr(split_part(def.adsrc, '''', 2), strpos(split_part(def.adsrc, '''', 2), '.')+1) ELSE split_part(def.adsrc, '''', 2) END as relname FROM pg_class t JOIN pg_attribute attr ON (t.oid = attrelid) JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum) JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1]) WHERE t.oid = '#{table}'::regclass AND cons.contype = 'p' AND def.adsrc ~* 'nextval' end_sql end [result["attname"], result["relname"]] rescue nil end def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) # Extract the table from the insert sql. Yuck. table = sql.split(" ", 4)[2].gsub('"', '') # Try an insert with 'returning id' if available (PG >= 8.2) if supports_insert_with_returning? && id_value.nil? pk, sequence_name = *pk_and_sequence_for(table) unless pk if pk id_value = select_value("#{sql} RETURNING #{quote_column_name(pk)}") clear_query_cache #FIXME: Why now? return id_value end end # Otherwise, plain insert execute(sql, name) # Don't need to look up id_value if we already have it. # (and can't in case of non-sequence PK) unless id_value # If neither pk nor sequence name is given, look them up. unless pk || sequence_name pk, sequence_name = *pk_and_sequence_for(table) end # If a pk is given, fallback to default sequence name. # Don't fetch last insert id for a table without a pk. if pk && sequence_name ||= default_sequence_name(table, pk) id_value = last_insert_id(table, sequence_name) end end id_value end def columns(table_name, name=nil) schema_name = @config[:schema_search_path] if table_name =~ /\./ parts = table_name.split(/\./) table_name = parts.pop schema_name = parts.join(".") end @connection.columns_internal(table_name, name, schema_name) end # From postgresql_adapter.rb def indexes(table_name, name = nil) result = select_rows(<<-SQL, name) SELECT i.relname, d.indisunique, a.attname FROM pg_class t, pg_class i, pg_index d, pg_attribute a WHERE i.relkind = 'i' AND d.indexrelid = i.oid AND d.indisprimary = 'f' AND t.oid = d.indrelid AND t.relname = '#{table_name}' AND a.attrelid = t.oid AND ( d.indkey[0]=a.attnum OR d.indkey[1]=a.attnum OR d.indkey[2]=a.attnum OR d.indkey[3]=a.attnum OR d.indkey[4]=a.attnum OR d.indkey[5]=a.attnum OR d.indkey[6]=a.attnum OR d.indkey[7]=a.attnum OR d.indkey[8]=a.attnum OR d.indkey[9]=a.attnum ) ORDER BY i.relname SQL current_index = nil indexes = [] result.each do |row| if current_index != row[0] indexes << ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, row[0], row[1] == "t", []) current_index = row[0] end indexes.last.columns << row[2] end indexes end def last_insert_id(table, sequence_name) Integer(select_value("SELECT currval('#{sequence_name}')")) end def recreate_database(name) drop_database(name) create_database(name) end def create_database(name, options = {}) execute "CREATE DATABASE \"#{name}\" ENCODING='#{options[:encoding] || 'utf8'}'" end def drop_database(name) execute "DROP DATABASE \"#{name}\"" end def create_schema(schema_name, pg_username) execute("CREATE SCHEMA \"#{schema_name}\" AUTHORIZATION \"#{pg_username}\"") end def drop_schema(schema_name) execute("DROP SCHEMA \"#{schema_name}\"") end def all_schemas select('select nspname from pg_namespace').map {|r| r["nspname"] } end def primary_key(table) pk_and_sequence = pk_and_sequence_for(table) pk_and_sequence && pk_and_sequence.first end def structure_dump database = @config[:database] if database.nil? if @config[:url] =~ /\/([^\/]*)$/ database = $1 else raise "Could not figure out what database this url is for #{@config["url"]}" end end ENV['PGHOST'] = @config[:host] if @config[:host] ENV['PGPORT'] = @config[:port].to_s if @config[:port] ENV['PGPASSWORD'] = @config[:password].to_s if @config[:password] search_path = @config[:schema_search_path] search_path = "--schema=#{search_path}" if search_path @connection.connection.close begin definition = `pg_dump -i -U "#{@config[:username]}" -s -x -O #{search_path} #{database}` raise "Error dumping database" if $?.exitstatus == 1 # need to patch away any references to SQL_ASCII as it breaks the JDBC driver definition.gsub(/SQL_ASCII/, 'UNICODE') ensure reconnect! end end def _execute(sql, name = nil) case sql.strip when /\A\(?\s*(select|show)/i then @connection.execute_query(sql) else @connection.execute_update(sql) end end # SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause. # # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and # requires that the ORDER BY include the distinct column. # # distinct("posts.id", "posts.created_at desc") def distinct(columns, order_by) return "DISTINCT #{columns}" if order_by.blank? # construct a clean list of column names from the ORDER BY clause, removing # any asc/desc modifiers order_columns = order_by.split(',').collect { |s| s.split.first } order_columns.delete_if(&:blank?) order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" } # return a DISTINCT ON() clause that's distinct on the columns we want but includes # all the required columns for the ORDER BY to work properly sql = "DISTINCT ON (#{columns}) #{columns}, " sql << order_columns * ', ' end # ORDER BY clause for the passed order option. # # PostgreSQL does not allow arbitrary ordering when using DISTINCT ON, so we work around this # by wrapping the sql as a sub-select and ordering in that query. def add_order_by_for_association_limiting!(sql, options) return sql if options[:order].blank? order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?) order.map! { |s| 'DESC' if s =~ /\bdesc$/i } order = order.zip((0...order.size).to_a).map { |s,i| "id_list.alias_#{i} #{s}" }.join(', ') sql.replace "SELECT * FROM (#{sql}) AS id_list ORDER BY #{order}" end def quote(value, column = nil) return value.quoted_id if value.respond_to?(:quoted_id) if value.kind_of?(String) && column && column.type == :binary "'#{escape_bytea(value)}'" elsif column && column.type == :primary_key return value.to_s else super end end def escape_bytea(s) if s result = '' s.each_byte { |c| result << sprintf('\\\\%03o', c) } result end end def quote_column_name(name) %("#{name}") end def quoted_date(value) #:nodoc: if value.acts_like?(:time) && value.respond_to?(:usec) "#{super}.#{sprintf("%06d", value.usec)}" else super end end def disable_referential_integrity(&block) #:nodoc: execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";")) yield ensure execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";")) end def rename_table(name, new_name) execute "ALTER TABLE #{name} RENAME TO #{new_name}" end def add_column(table_name, column_name, type, options = {}) execute("ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}") change_column_default(table_name, column_name, options[:default]) unless options[:default].nil? if options[:null] == false execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)} = '#{options[:default]}'") if options[:default] execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} SET NOT NULL") end end def change_column(table_name, column_name, type, options = {}) #:nodoc: begin execute "ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit])}" rescue ActiveRecord::StatementInvalid # This is PG7, so we use a more arcane way of doing it. begin_db_transaction add_column(table_name, "#{column_name}_ar_tmp", type, options) execute "UPDATE #{table_name} SET #{column_name}_ar_tmp = CAST(#{column_name} AS #{type_to_sql(type, options[:limit])})" remove_column(table_name, column_name) rename_column(table_name, "#{column_name}_ar_tmp", column_name) commit_db_transaction end change_column_default(table_name, column_name, options[:default]) unless options[:default].nil? end def change_column_default(table_name, column_name, default) #:nodoc: execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT '#{default}'" end def change_column_null(table_name, column_name, null, default = nil) unless null || default.nil? execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL") end def rename_column(table_name, column_name, new_column_name) #:nodoc: execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}" end def remove_index(table_name, options) #:nodoc: execute "DROP INDEX #{index_name(table_name, options)}" end def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc: return super unless type.to_s == 'integer' if limit.nil? || limit == 4 'integer' elsif limit < 4 'smallint' else 'bigint' end end def tables @connection.tables(database_name, nil, nil, ["TABLE"]) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_informix.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_informix.rb
module ::ActiveRecord class Base after_save :write_lobs private def write_lobs if connection.is_a?(JdbcSpec::Informix) self.class.columns.each do |c| if [:text, :binary].include? c.type value = self[c.name] value = value.to_yaml if unserializable_attribute?(c.name, c) unless value.nil? || (value == '') connection.write_large_object(c.type == :binary, c.name, self.class.table_name, self.class.primary_key, quote_value(id), value) end end end end end end end module ::JdbcSpec module ActiveRecordExtensions def informix_connection(config) config[:port] ||= 9088 config[:url] ||= "jdbc:informix-sqli://#{config[:host]}:#{config[:port]}/#{config[:database]}:INFORMIXSERVER=#{config[:servername]}" config[:driver] = 'com.informix.jdbc.IfxDriver' jdbc_connection(config) end end module Informix def self.extended(base) @@db_major_version = base.select_one("SELECT dbinfo('version', 'major') version FROM systables WHERE tabid = 1")['version'].to_i end def self.adapter_matcher(name, *) name =~ /informix/i ? self : false end def self.column_selector [ /informix/i, lambda { |cfg, column| column.extend(::JdbcSpec::Informix::Column) } ] end module Column private # TODO: Test all Informix column types. def simplified_type(field_type) if field_type =~ /serial/i :primary_key else super end end end def modify_types(tp) tp[:primary_key] = "SERIAL PRIMARY KEY" tp[:string] = { :name => "VARCHAR", :limit => 255 } tp[:integer] = { :name => "INTEGER" } tp[:float] = { :name => "FLOAT" } tp[:decimal] = { :name => "DECIMAL" } tp[:datetime] = { :name => "DATETIME YEAR TO FRACTION(5)" } tp[:timestamp] = { :name => "DATETIME YEAR TO FRACTION(5)" } tp[:time] = { :name => "DATETIME HOUR TO FRACTION(5)" } tp[:date] = { :name => "DATE" } tp[:binary] = { :name => "BYTE" } tp[:boolean] = { :name => "BOOLEAN" } tp end def prefetch_primary_key?(table_name = nil) true end def supports_migrations? true end def default_sequence_name(table, column) "#{table}_seq" end def add_limit_offset!(sql, options) if options[:limit] limit = "FIRST #{options[:limit]}" # SKIP available only in IDS >= 10 offset = (@@db_major_version >= 10 && options[:offset]? "SKIP #{options[:offset]}" : "") sql.sub!(/^select /i, "SELECT #{offset} #{limit} ") end sql end def next_sequence_value(sequence_name) select_one("SELECT #{sequence_name}.nextval id FROM systables WHERE tabid=1")['id'] end # TODO: Add some smart quoting for newlines in string and text fields. def quote_string(string) string.gsub(/\'/, "''") end def quote(value, column = nil) if column && [:binary, :text].include?(column.type) # LOBs are updated separately by an after_save trigger. "NULL" elsif column && column.type == :date "'#{value.mon}/#{value.day}/#{value.year}'" else super end end def create_table(name, options = {}) super(name, options) execute("CREATE SEQUENCE #{name}_seq") end def rename_table(name, new_name) execute("RENAME TABLE #{name} TO #{new_name}") execute("RENAME SEQUENCE #{name}_seq TO #{new_name}_seq") end def drop_table(name) super(name) execute("DROP SEQUENCE #{name}_seq") end def remove_index(table_name, options = {}) @connection.execute_update("DROP INDEX #{index_name(table_name, options)}") end private def select(sql, name = nil) # Informix does not like "= NULL", "!= NULL", or "<> NULL". execute(sql.gsub(/(!=|<>)\s*null/i, "IS NOT NULL").gsub(/=\s*null/i, "IS NULL"), name) end end # module Informix end # module ::JdbcSpec
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_sqlite3.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_sqlite3.rb
module ::JdbcSpec # Don't need to load native postgres adapter $LOADED_FEATURES << "active_record/connection_adapters/sqlite3_adapter.rb" module ActiveRecordExtensions add_method_to_remove_from_ar_base(:sqlite3_connection) def sqlite3_connection(config) require File.dirname(__FILE__) + "/../active_record/connection_adapters/sqlite3_adapter" parse_sqlite3_config!(config) config[:url] ||= "jdbc:sqlite:#{config[:database]}" config[:driver] ||= "org.sqlite.JDBC" jdbc_connection(config) end def parse_sqlite3_config!(config) config[:database] ||= config[:dbfile] # Allow database path relative to RAILS_ROOT, but only if # the database path is not the special path that tells # Sqlite to build a database only in memory. rails_root_defined = defined?(Rails.root) || Object.const_defined?(:RAILS_ROOT) if rails_root_defined && ':memory:' != config[:database] rails_root = defined?(Rails.root) ? Rails.root : RAILS_ROOT config[:database] = File.expand_path(config[:database], rails_root) end end end module SQLite3 def self.extended(base) base.class.class_eval do alias_chained_method :insert, :query_dirty, :insert end end def self.adapter_matcher(name, *) name =~ /sqlite/i ? self : false end def self.column_selector [/sqlite/i, lambda {|cfg,col| col.extend(::JdbcSpec::SQLite3::Column)}] end def self.jdbc_connection_class ::ActiveRecord::ConnectionAdapters::Sqlite3JdbcConnection end module Column def init_column(name, default, *args) @default = '' if default =~ /NULL/ end def type_cast(value) return nil if value.nil? case type when :string then value when :integer then JdbcSpec::SQLite3::Column.cast_to_integer(value) when :primary_key then defined?(value.to_i) ? value.to_i : (value ? 1 : 0) when :float then value.to_f when :datetime then JdbcSpec::SQLite3::Column.cast_to_date_or_time(value) when :date then JdbcSpec::SQLite3::Column.cast_to_date_or_time(value) when :time then JdbcSpec::SQLite3::Column.cast_to_time(value) when :decimal then self.class.value_to_decimal(value) when :boolean then self.class.value_to_boolean(value) else value end end def type_cast_code(var_name) case type when :integer then "JdbcSpec::SQLite3::Column.cast_to_integer(#{var_name})" when :datetime then "JdbcSpec::SQLite3::Column.cast_to_date_or_time(#{var_name})" when :date then "JdbcSpec::SQLite3::Column.cast_to_date_or_time(#{var_name})" when :time then "JdbcSpec::SQLite3::Column.cast_to_time(#{var_name})" else super end end private def simplified_type(field_type) case field_type when /boolean/i then :boolean when /text/i then :text when /varchar/i then :string when /int/i then :integer when /float/i then :float when /real/i then @scale == 0 ? :integer : :decimal when /datetime/i then :datetime when /date/i then :date when /time/i then :time when /blob/i then :binary end end def extract_precision(sql_type) case sql_type when /^(real)\((\d+)(,\d+)?\)/i then $2.to_i else super end end def extract_scale(sql_type) case sql_type when /^(real)\((\d+)\)/i then 0 when /^(real)\((\d+)(,(\d+))\)/i then $4.to_i else super end end # Post process default value from JDBC into a Rails-friendly format (columns{-internal}) def default_value(value) # jdbc returns column default strings with actual single quotes around the value. return $1 if value =~ /^'(.*)'$/ value end def self.cast_to_integer(value) return nil if value =~ /NULL/ or value.to_s.empty? or value.nil? return (value.to_i) ? value.to_i : (value ? 1 : 0) end def self.cast_to_date_or_time(value) return value if value.is_a? Date return nil if value.blank? guess_date_or_time((value.is_a? Time) ? value : cast_to_time(value)) end def self.cast_to_time(value) return value if value.is_a? Time time_array = ParseDate.parsedate value time_array[0] ||= 2000; time_array[1] ||= 1; time_array[2] ||= 1; Time.send(ActiveRecord::Base.default_timezone, *time_array) rescue nil end def self.guess_date_or_time(value) (value.hour == 0 and value.min == 0 and value.sec == 0) ? Date.new(value.year, value.month, value.day) : value end end def adapter_name #:nodoc: 'SQLite' end def supports_count_distinct? #:nodoc: sqlite_version >= '3.2.6' end def supports_autoincrement? #:nodoc: sqlite_version >= '3.1.0' end def sqlite_version @sqlite_version ||= select_value('select sqlite_version(*)') end def modify_types(tp) tp[:primary_key] = "INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" tp[:string] = { :name => "VARCHAR", :limit => 255 } tp[:float] = { :name => "REAL" } tp[:decimal] = { :name => "REAL" } tp[:datetime] = { :name => "DATETIME" } tp[:timestamp] = { :name => "DATETIME" } tp[:time] = { :name => "TIME" } tp[:date] = { :name => "DATE" } tp[:boolean] = { :name => "BOOLEAN" } tp end def quote(value, column = nil) # :nodoc: return value.quoted_id if value.respond_to?(:quoted_id) case value when String if column && column.type == :binary "'#{quote_string(column.class.string_to_binary(value))}'" elsif column && [:integer, :float].include?(column.type) (column.type == :integer ? value.to_i : value.to_f).to_s elsif column && column.respond_to?(:primary) && column.primary && column.klass != String value.to_i.to_s else "'#{quote_string(value)}'" end else super end end def quote_column_name(name) #:nodoc: name = name.to_s # Did not find reference on values needing quoting, but these # happen in AR unit tests if name == "references" || name =~ /-/ %Q("#{name}") else name end end def quote_string(str) str.gsub(/'/, "''") end def quoted_true %Q{'t'} end def quoted_false %Q{'f'} end def add_column(table_name, column_name, type, options = {}) if option_not_null = options[:null] == false option_not_null = options.delete(:null) end add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" add_column_options!(add_column_sql, options) execute(add_column_sql) if option_not_null alter_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} NOT NULL" end end def remove_column(table_name, *column_names) #:nodoc: column_names.flatten.each do |column_name| alter_table(table_name) do |definition| definition.columns.delete(definition[column_name]) end end end alias :remove_columns :remove_column def change_column(table_name, column_name, type, options = {}) #:nodoc: alter_table(table_name) do |definition| include_default = options_include_default?(options) definition[column_name].instance_eval do self.type = type self.limit = options[:limit] if options.include?(:limit) self.default = options[:default] if include_default self.null = options[:null] if options.include?(:null) end end end def change_column_default(table_name, column_name, default) #:nodoc: alter_table(table_name) do |definition| definition[column_name].default = default end end def rename_column(table_name, column_name, new_column_name) #:nodoc: unless columns(table_name).detect{|c| c.name == column_name.to_s } raise ActiveRecord::ActiveRecordError, "Missing column #{table_name}.#{column_name}" end alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s}) end def rename_table(name, new_name) execute "ALTER TABLE #{name} RENAME TO #{new_name}" end def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc: log(sql,name) do @connection.execute_update(sql) end table = sql.split(" ", 4)[2] id_value || last_insert_id(table, nil) end def last_insert_id(table, sequence_name) Integer(select_value("SELECT SEQ FROM SQLITE_SEQUENCE WHERE NAME = '#{table}'")) end def add_limit_offset!(sql, options) #:nodoc: if options[:limit] sql << " LIMIT #{options[:limit]}" sql << " OFFSET #{options[:offset]}" if options[:offset] end end def tables(name = nil) #:nodoc: sql = <<-SQL SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence' SQL select_rows(sql, name).map do |row| row[0] end end def remove_index(table_name, options = {}) execute "DROP INDEX #{quote_column_name(index_name(table_name, options))}" end def indexes(table_name, name = nil) result = select_rows("SELECT name, sql FROM sqlite_master WHERE tbl_name = '#{table_name}' AND type = 'index'", name) result.collect do |row| name = row[0] index_sql = row[1] unique = (index_sql =~ /unique/i) cols = index_sql.match(/\((.*)\)/)[1].gsub(/,/,' ').split ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, name, unique, cols) end end def primary_key(table_name) #:nodoc: column = table_structure(table_name).find {|field| field['pk'].to_i == 1} column ? column['name'] : nil end def recreate_database(name) tables.each{ |table| drop_table(table) } end def _execute(sql, name = nil) if ActiveRecord::ConnectionAdapters::JdbcConnection::select?(sql) @connection.execute_query(sql) else affected_rows = @connection.execute_update(sql) ActiveRecord::ConnectionAdapters::JdbcConnection::insert?(sql) ? last_insert_id(sql.split(" ", 4)[2], nil) : affected_rows end end def select(sql, name=nil) execute(sql, name).map do |row| record = {} row.each_key do |key| if key.is_a?(String) record[key.sub(/^"?\w+"?\./, '')] = row[key] end end record end end def table_structure(table_name) structure = @connection.execute_query("PRAGMA table_info(#{quote_table_name(table_name)})") raise ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'" if structure.empty? structure end def columns(table_name, name = nil) #:nodoc: table_structure(table_name).map do |field| ::ActiveRecord::ConnectionAdapters::JdbcColumn.new(@config, field['name'], field['dflt_value'], field['type'], field['notnull'] == 0) end end # SELECT ... FOR UPDATE is redundant since the table is locked. def add_lock!(sql, options) #:nodoc: sql end protected include JdbcSpec::MissingFunctionalityHelper end end module ActiveRecord module ConnectionAdapters class JdbcColumn < Column def self.string_to_binary(value) value.gsub(/\0|%/n) do |b| case b when "\0" then "%00" when "\%" then "%25" end end end def self.binary_to_string(value) value.gsub(/%00|%25/n) do |b| case b when "%00" then "\0" when "%25" then "%" end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_sybase.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_sybase.rb
module JdbcSpec module Sybase def self.adapter_matcher(name, *) name =~ /sybase|tds/i ? self : false end def add_limit_offset!(sql, options) # :nodoc: @limit = options[:limit] @offset = options[:offset] if use_temp_table? # Use temp table to hack offset with Sybase sql.sub!(/ FROM /i, ' INTO #artemp FROM ') elsif zero_limit? # "SET ROWCOUNT 0" turns off limits, so we havesy # to use a cheap trick. if sql =~ /WHERE/i sql.sub!(/WHERE/i, 'WHERE 1 = 2 AND ') elsif sql =~ /ORDER\s+BY/i sql.sub!(/ORDER\s+BY/i, 'WHERE 1 = 2 ORDER BY') else sql << 'WHERE 1 = 2' end end end # If limit is not set at all, we can ignore offset; # if limit *is* set but offset is zero, use normal select # with simple SET ROWCOUNT. Thus, only use the temp table # if limit is set and offset > 0. def use_temp_table? !@limit.nil? && !@offset.nil? && @offset > 0 end def zero_limit? !@limit.nil? && @limit == 0 end def modify_types(tp) #:nodoc: tp[:primary_key] = "NUMERIC(22,0) IDENTITY PRIMARY KEY" tp[:integer][:limit] = nil tp[:boolean] = {:name => "bit"} tp[:binary] = {:name => "image"} tp end def remove_index(table_name, options = {}) execute "DROP INDEX #{table_name}.#{index_name(table_name, options)}" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_mimer.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_mimer.rb
module JdbcSpec module Mimer def self.extended(mod) ActiveRecord::Base.extend JdbcSpec::QuotedPrimaryKeyExtension end def self.adapter_matcher(name, *) name =~ /mimer/i ? self : false end def modify_types(tp) tp[:primary_key] = "INTEGER NOT NULL PRIMARY KEY" tp[:boolean][:limit] = nil tp[:string][:limit] = 255 tp[:binary] = {:name => "BINARY VARYING", :limit => 4096} tp[:text] = {:name => "VARCHAR", :limit => 4096} tp[:datetime] = { :name => "TIMESTAMP" } tp[:timestamp] = { :name => "TIMESTAMP" } tp[:time] = { :name => "TIMESTAMP" } tp[:date] = { :name => "TIMESTAMP" } tp end def default_sequence_name(table, column) #:nodoc: "#{table}_seq" end def create_table(name, options = {}) #:nodoc: super(name, options) execute "CREATE SEQUENCE #{name}_seq" unless options[:id] == false end def drop_table(name, options = {}) #:nodoc: super(name) rescue nil execute "DROP SEQUENCE #{name}_seq" rescue nil end def change_column(table_name, column_name, type, options = {}) #:nodoc: execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} #{type_to_sql(type, options[:limit])}" end def change_column_default(table_name, column_name, default) #:nodoc: execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} SET DEFAULT #{quote(default)}" end def remove_index(table_name, options = {}) #:nodoc: execute "DROP INDEX #{index_name(table_name, options)}" end def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc: if pk.nil? # Who called us? What does the sql look like? No idea! execute sql, name elsif id_value # Pre-assigned id log(sql, name) { @connection.execute_insert sql,pk } else # Assume the sql contains a bind-variable for the id id_value = select_one("SELECT NEXT_VALUE OF #{sequence_name} AS val FROM MIMER.ONEROW")['val'] log(sql, name) { execute_prepared_insert(sql,id_value) } end id_value end def execute_prepared_insert(sql, id) @stmts ||= {} @stmts[sql] ||= @connection.ps(sql) stmt = @stmts[sql] stmt.setLong(1,id) stmt.executeUpdate id end def quote(value, column = nil) #:nodoc: return value.quoted_id if value.respond_to?(:quoted_id) if String === value && column && column.type == :binary return "X'#{quote_string(value.unpack("C*").collect {|v| v.to_s(16)}.join)}'" end case value when String %Q{'#{quote_string(value)}'} when NilClass 'NULL' when TrueClass '1' when FalseClass '0' when Numeric value.to_s when Date, Time %Q{TIMESTAMP '#{value.strftime("%Y-%m-%d %H:%M:%S")}'} else %Q{'#{quote_string(value.to_yaml)}'} end end def quoted_true '1' end def quoted_false '0' end def add_limit_offset!(sql, options) # :nodoc: @limit = options[:limit] @offset = options[:offset] end def select_all(sql, name = nil) @offset ||= 0 if !@limit || @limit == -1 range = @offset..-1 else range = @offset...(@offset+@limit) end select(sql, name)[range] ensure @limit = @offset = nil end def select_one(sql, name = nil) @offset ||= 0 select(sql, name)[@offset] ensure @limit = @offset = nil end def _execute(sql, name = nil) if sql =~ /^select/i @offset ||= 0 if !@limit || @limit == -1 range = @offset..-1 else range = @offset...(@offset+@limit) end @connection.execute_query(sql)[range] else @connection.execute_update(sql) end ensure @limit = @offset = nil end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/railtie.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/railtie.rb
require 'rails/railtie' module ::JdbcSpec class Railtie < ::Rails::Railtie rake_tasks do load File.expand_path('../rake_tasks.rb', __FILE__) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_oracle.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_oracle.rb
module ::JdbcSpec module ActiveRecordExtensions def oracle_connection(config) config[:port] ||= 1521 config[:url] ||= "jdbc:oracle:thin:@#{config[:host]}:#{config[:port]}:#{config[:database]}" config[:driver] ||= "oracle.jdbc.driver.OracleDriver" jdbc_connection(config) end end module Oracle def self.extended(mod) unless @lob_callback_added ActiveRecord::Base.class_eval do def after_save_with_oracle_lob self.class.columns.select { |c| c.sql_type =~ /LOB\(|LOB$/i }.each do |c| value = self[c.name] value = value.to_yaml if unserializable_attribute?(c.name, c) next if value.nil? || (value == '') connection.write_large_object(c.type == :binary, c.name, self.class.table_name, self.class.primary_key, quote_value(id), value) end end end ActiveRecord::Base.after_save :after_save_with_oracle_lob @lob_callback_added = true end ActiveRecord::Base.extend JdbcSpec::QuotedPrimaryKeyExtension mod.class.class_eval do alias_chained_method :insert, :query_dirty, :insert alias_chained_method :columns, :query_cache, :columns end end def self.adapter_matcher(name, *) name =~ /oracle/i ? self : false end def self.column_selector [/oracle/i, lambda {|cfg,col| col.extend(::JdbcSpec::Oracle::Column)}] end module Column def primary=(val) super if val && @sql_type =~ /^NUMBER$/i @type = :integer end end def type_cast(value) return nil if value.nil? case type when :datetime then JdbcSpec::Oracle::Column.string_to_time(value, self.class) else super end end def type_cast_code(var_name) case type when :datetime then "JdbcSpec::Oracle::Column.string_to_time(#{var_name}, self.class)" else super end end def self.string_to_time(string, klass) time = klass.string_to_time(string) guess_date_or_time(time) end def self.guess_date_or_time(value) (value && value.hour == 0 && value.min == 0 && value.sec == 0) ? Date.new(value.year, value.month, value.day) : value end private def simplified_type(field_type) case field_type when /^number\(1\)$/i then :boolean when /char/i then :string when /float|double/i then :float when /int/i then :integer when /num|dec|real/i then extract_scale(field_type) == 0 ? :integer : :decimal when /date|time/i then :datetime when /clob/i then :text when /blob/i then :binary end end # Post process default value from JDBC into a Rails-friendly format (columns{-internal}) def default_value(value) return nil unless value # Not sure why we need this for Oracle? value = value.strip return nil if value == "null" # sysdate default should be treated like a null value return nil if value.downcase == "sysdate" # jdbc returns column default strings with actual single quotes around the value. return $1 if value =~ /^'(.*)'$/ value end end def adapter_name 'Oracle' end def table_alias_length 30 end def default_sequence_name(table, column = nil) #:nodoc: "#{table}_seq" end def create_table(name, options = {}) #:nodoc: super(name, options) seq_name = options[:sequence_name] || "#{name}_seq" start_value = options[:sequence_start_value] || 10000 raise ActiveRecord::StatementInvalid.new("name #{seq_name} too long") if seq_name.length > table_alias_length execute "CREATE SEQUENCE #{seq_name} START WITH #{start_value}" unless options[:id] == false end def rename_table(name, new_name) #:nodoc: execute "RENAME #{name} TO #{new_name}" execute "RENAME #{name}_seq TO #{new_name}_seq" rescue nil end def drop_table(name, options = {}) #:nodoc: super(name) seq_name = options[:sequence_name] || "#{name}_seq" execute "DROP SEQUENCE #{seq_name}" rescue nil end def recreate_database(name) tables.each{ |table| drop_table(table) } end def drop_database(name) recreate_database(name) end def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc: if (id_value && !id_value.respond_to?(:to_sql)) || pk.nil? # Pre-assigned id or table without a primary key # Presence of #to_sql means an Arel literal bind variable # that should use #execute_id_insert below execute sql, name else # Assume the sql contains a bind-variable for the id # Extract the table from the insert sql. Yuck. table = sql.split(" ", 4)[2].gsub('"', '') sequence_name ||= default_sequence_name(table) id_value = select_one("select #{sequence_name}.nextval id from dual")['id'].to_i log(sql, name) do @connection.execute_id_insert(sql,id_value) end end id_value end def indexes(table, name = nil) @connection.indexes(table, name, @connection.connection.meta_data.user_name) end def _execute(sql, name = nil) case sql.strip when /\A\(?\s*(select|show)/i then @connection.execute_query(sql) else @connection.execute_update(sql) end end def modify_types(tp) tp[:primary_key] = "NUMBER(38) NOT NULL PRIMARY KEY" tp[:integer] = { :name => "NUMBER", :limit => 38 } tp[:datetime] = { :name => "DATE" } tp[:timestamp] = { :name => "DATE" } tp[:time] = { :name => "DATE" } tp[:date] = { :name => "DATE" } tp end def add_limit_offset!(sql, options) #:nodoc: offset = options[:offset] || 0 if limit = options[:limit] sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_ where rownum <= #{offset+limit}) where raw_rnum_ > #{offset}" elsif offset > 0 sql.replace "select * from (select raw_sql_.*, rownum raw_rnum_ from (#{sql}) raw_sql_) where raw_rnum_ > #{offset}" end end def current_database #:nodoc: select_one("select sys_context('userenv','db_name') db from dual")["db"] end def remove_index(table_name, options = {}) #:nodoc: execute "DROP INDEX #{index_name(table_name, options)}" end def change_column_default(table_name, column_name, default) #:nodoc: execute "ALTER TABLE #{table_name} MODIFY #{column_name} DEFAULT #{quote(default)}" end def add_column_options!(sql, options) #:nodoc: # handle case of defaults for CLOB columns, which would otherwise get "quoted" incorrectly if options_include_default?(options) && (column = options[:column]) && column.type == :text sql << " DEFAULT #{quote(options.delete(:default))}" end super end def change_column(table_name, column_name, type, options = {}) #:nodoc: change_column_sql = "ALTER TABLE #{table_name} MODIFY #{column_name} #{type_to_sql(type, options[:limit])}" add_column_options!(change_column_sql, options) execute(change_column_sql) end def rename_column(table_name, column_name, new_column_name) #:nodoc: execute "ALTER TABLE #{table_name} RENAME COLUMN #{column_name} to #{new_column_name}" end def remove_column(table_name, column_name) #:nodoc: execute "ALTER TABLE #{table_name} DROP COLUMN #{column_name}" end def structure_dump #:nodoc: s = select_all("select sequence_name from user_sequences").inject("") do |structure, seq| structure << "create sequence #{seq.to_a.first.last};\n\n" end select_all("select table_name from user_tables").inject(s) do |structure, table| ddl = "create table #{table.to_a.first.last} (\n " cols = select_all(%Q{ select column_name, data_type, data_length, data_precision, data_scale, data_default, nullable from user_tab_columns where table_name = '#{table.to_a.first.last}' order by column_id }).map do |row| row = row.inject({}) do |h,args| h[args[0].downcase] = args[1] h end col = "#{row['column_name'].downcase} #{row['data_type'].downcase}" if row['data_type'] =='NUMBER' and !row['data_precision'].nil? col << "(#{row['data_precision'].to_i}" col << ",#{row['data_scale'].to_i}" if !row['data_scale'].nil? col << ')' elsif row['data_type'].include?('CHAR') col << "(#{row['data_length'].to_i})" end col << " default #{row['data_default']}" if !row['data_default'].nil? col << ' not null' if row['nullable'] == 'N' col end ddl << cols.join(",\n ") ddl << ");\n\n" structure << ddl end end def structure_drop #:nodoc: s = select_all("select sequence_name from user_sequences").inject("") do |drop, seq| drop << "drop sequence #{seq.to_a.first.last};\n\n" end select_all("select table_name from user_tables").inject(s) do |drop, table| drop << "drop table #{table.to_a.first.last} cascade constraints;\n\n" end end # SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause. # # Oracle requires the ORDER BY columns to be in the SELECT list for DISTINCT # queries. However, with those columns included in the SELECT DISTINCT list, you # won't actually get a distinct list of the column you want (presuming the column # has duplicates with multiple values for the ordered-by columns. So we use the # FIRST_VALUE function to get a single (first) value for each column, effectively # making every row the same. # # distinct("posts.id", "posts.created_at desc") def distinct(columns, order_by) return "DISTINCT #{columns}" if order_by.blank? # construct a valid DISTINCT clause, ie. one that includes the ORDER BY columns, using # FIRST_VALUE such that the inclusion of these columns doesn't invalidate the DISTINCT order_columns = order_by.split(',').map { |s| s.strip }.reject(&:blank?) order_columns = order_columns.zip((0...order_columns.size).to_a).map do |c, i| "FIRST_VALUE(#{c.split.first}) OVER (PARTITION BY #{columns} ORDER BY #{c}) AS alias_#{i}__" end sql = "DISTINCT #{columns}, " sql << order_columns * ", " end # ORDER BY clause for the passed order option. # # Uses column aliases as defined by #distinct. def add_order_by_for_association_limiting!(sql, options) return sql if options[:order].blank? order = options[:order].split(',').collect { |s| s.strip }.reject(&:blank?) order.map! {|s| $1 if s =~ / (.*)/} order = order.zip((0...order.size).to_a).map { |s,i| "alias_#{i}__ #{s}" }.join(', ') sql << "ORDER BY #{order}" end def tables @connection.tables(nil, oracle_schema) end def columns(table_name, name=nil) @connection.columns_internal(table_name, name, oracle_schema) end # QUOTING ================================================== # # see: abstract/quoting.rb # See ACTIVERECORD_JDBC-33 for details -- better to not quote # table names, esp. if they have schemas. def quote_table_name(name) #:nodoc: name.to_s end # Camelcase column names need to be quoted. # Nonquoted identifiers can contain only alphanumeric characters from your # database character set and the underscore (_), dollar sign ($), and pound sign (#). # Database links can also contain periods (.) and "at" signs (@). # Oracle strongly discourages you from using $ and # in nonquoted identifiers. # Source: http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements008.htm def quote_column_name(name) #:nodoc: name.to_s =~ /^[a-z0-9_$#]+$/ ? name.to_s : "\"#{name}\"" end def quote_string(string) #:nodoc: string.gsub(/'/, "''") end def quote(value, column = nil) #:nodoc: if column && [:text, :binary].include?(column.type) if /(.*?)\([0-9]+\)/ =~ column.sql_type %Q{empty_#{ $1.downcase }()} else %Q{empty_#{ column.sql_type.downcase rescue 'blob' }()} end else if column.respond_to?(:primary) && column.primary && column.klass != String return value.to_i.to_s end quoted = super if value.acts_like?(:date) || value.acts_like?(:time) quoted = "#{quoted_date(value)}" end quoted end end def quoted_date(value) %Q{TIMESTAMP'#{super}'} end def quoted_true #:nodoc: '1' end def quoted_false #:nodoc: '0' end private # In Oracle, schemas are created under your username: # http://www.oracle.com/technology/obe/2day_dba/schema/schema.htm def oracle_schema @config[:username].to_s if @config[:username] end def select(sql, name=nil) records = execute(sql,name) records.each do |col| col.delete('raw_rnum_') end records end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_mssql.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_mssql.rb
require 'jdbc_adapter/tsql_helper' module ::JdbcSpec module ActiveRecordExtensions def mssql_connection(config) require "active_record/connection_adapters/mssql_adapter" config[:host] ||= "localhost" config[:port] ||= 1433 config[:url] ||= "jdbc:jtds:sqlserver://#{config[:host]}:#{config[:port]}/#{config[:database]}" config[:driver] ||= "net.sourceforge.jtds.jdbc.Driver" embedded_driver(config) end end module MsSQL include TSqlMethods def self.extended(mod) unless @lob_callback_added ActiveRecord::Base.class_eval do def after_save_with_mssql_lob self.class.columns.select { |c| c.sql_type =~ /image/i }.each do |c| value = self[c.name] value = value.to_yaml if unserializable_attribute?(c.name, c) next if value.nil? || (value == '') connection.write_large_object(c.type == :binary, c.name, self.class.table_name, self.class.primary_key, quote_value(id), value) end end end ActiveRecord::Base.after_save :after_save_with_mssql_lob @lob_callback_added = true end mod.add_version_specific_add_limit_offset end def self.adapter_matcher(name, *) name =~ /sqlserver|tds/i ? self : false end def self.column_selector [/sqlserver|tds/i, lambda {|cfg,col| col.extend(::JdbcSpec::MsSQL::Column)}] end def self.jdbc_connection_class ::ActiveRecord::ConnectionAdapters::MssqlJdbcConnection end def sqlserver_version @sqlserver_version ||= select_value("select @@version")[/Microsoft SQL Server\s+(\d{4})/, 1] end def add_version_specific_add_limit_offset if sqlserver_version == "2000" extend SqlServer2000LimitOffset else extend SqlServerLimitOffset end end def modify_types(tp) #:nodoc: super(tp) tp[:string] = {:name => "NVARCHAR", :limit => 255} if sqlserver_version == "2000" tp[:text] = {:name => "NTEXT"} else tp[:text] = {:name => "NVARCHAR(MAX)"} end tp end module Column attr_accessor :identity, :is_special def simplified_type(field_type) case field_type when /int|bigint|smallint|tinyint/i then :integer when /numeric/i then (@scale.nil? || @scale == 0) ? :integer : :decimal when /float|double|decimal|money|real|smallmoney/i then :decimal when /datetime|smalldatetime/i then :datetime when /timestamp/i then :timestamp when /time/i then :time when /date/i then :date when /text|ntext/i then :text when /binary|image|varbinary/i then :binary when /char|nchar|nvarchar|string|varchar/i then :string when /bit/i then :boolean when /uniqueidentifier/i then :string end end def default_value(value) return $1 if value =~ /^\(N?'(.*)'\)$/ value end def type_cast(value) return nil if value.nil? || value == "(null)" || value == "(NULL)" case type when :integer then unquote(value).to_i rescue value ? 1 : 0 when :primary_key then value == true || value == false ? value == true ? 1 : 0 : value.to_i when :decimal then self.class.value_to_decimal(unquote(value)) when :datetime then cast_to_datetime(value) when :timestamp then cast_to_time(value) when :time then cast_to_time(value) when :date then cast_to_date(value) when :boolean then value == true or (value =~ /^t(rue)?$/i) == 0 or unquote(value)=="1" when :binary then unquote value else value end end def is_utf8? sql_type =~ /nvarchar|ntext|nchar/i end def unquote(value) value.to_s.sub(/\A\([\(\']?/, "").sub(/[\'\)]?\)\Z/, "") end def cast_to_time(value) return value if value.is_a?(Time) time_array = ParseDate.parsedate(value) time_array[0] ||= 2000 time_array[1] ||= 1 time_array[2] ||= 1 Time.send(ActiveRecord::Base.default_timezone, *time_array) rescue nil end def cast_to_date(value) return value if value.is_a?(Date) return Date.parse(value) rescue nil end def cast_to_datetime(value) if value.is_a?(Time) if value.year != 0 and value.month != 0 and value.day != 0 return value else return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil end end return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil value end # These methods will only allow the adapter to insert binary data with a length of 7K or less # because of a SQL Server statement length policy. def self.string_to_binary(value) '' end end def quote(value, column = nil) return value.quoted_id if value.respond_to?(:quoted_id) case value when String, ActiveSupport::Multibyte::Chars value = value.to_s if column && column.type == :binary "'#{quote_string(JdbcSpec::MsSQL::Column.string_to_binary(value))}'" # ' (for ruby-mode) elsif column && [:integer, :float].include?(column.type) value = column.type == :integer ? value.to_i : value.to_f value.to_s elsif !column.respond_to?(:is_utf8?) || column.is_utf8? "N'#{quote_string(value)}'" # ' (for ruby-mode) else super end when TrueClass then '1' when FalseClass then '0' else super end end def quote_string(string) string.gsub(/\'/, "''") end def quote_table_name(name) name end def quote_column_name(name) "[#{name}]" end def quoted_true quote true end def quoted_false quote false end module SqlServer2000LimitOffset def add_limit_offset!(sql, options) limit = options[:limit] if limit offset = (options[:offset] || 0).to_i start_row = offset + 1 end_row = offset + limit.to_i order = (options[:order] || determine_order_clause(sql)) sql.sub!(/ ORDER BY.*$/i, '') find_select = /\b(SELECT(?:\s+DISTINCT)?)\b(.*)/i whole, select, rest_of_query = find_select.match(sql).to_a if (start_row == 1) && (end_row ==1) new_sql = "#{select} TOP 1 #{rest_of_query}" sql.replace(new_sql) else #UGLY #KLUDGY? #removing out stuff before the FROM... rest = rest_of_query[/FROM/i=~ rest_of_query.. -1] #need the table name for avoiding amiguity table_name = get_table_name(sql) #I am not sure this will cover all bases. but all the tests pass new_order = "#{order}, #{table_name}.id" if order.index("#{table_name}.id").nil? new_order ||= order new_sql = "#{select} TOP #{limit} #{rest_of_query} WHERE #{table_name}.id NOT IN (#{select} TOP #{offset} #{table_name}.id #{rest} ORDER BY #{new_order}) ORDER BY #{order} " sql.replace(new_sql) end end end end module SqlServerLimitOffset def add_limit_offset!(sql, options) limit = options[:limit] if limit offset = (options[:offset] || 0).to_i start_row = offset + 1 end_row = offset + limit.to_i order = (options[:order] || determine_order_clause(sql)) sql.sub!(/ ORDER BY.*$/i, '') find_select = /\b(SELECT(?:\s+DISTINCT)?)\b(.*)/i whole, select, rest_of_query = find_select.match(sql).to_a new_sql = "#{select} t.* FROM (SELECT ROW_NUMBER() OVER(ORDER BY #{order}) AS row_num, #{rest_of_query}" new_sql << ") AS t WHERE t.row_num BETWEEN #{start_row.to_s} AND #{end_row.to_s}" sql.replace(new_sql) end end end def change_order_direction(order) order.split(",").collect do |fragment| case fragment when /\bDESC\b/i then fragment.gsub(/\bDESC\b/i, "ASC") when /\bASC\b/i then fragment.gsub(/\bASC\b/i, "DESC") else String.new(fragment).split(',').join(' DESC,') + ' DESC' end end.join(",") end def supports_ddl_transactions? true end def recreate_database(name) drop_database(name) create_database(name) end def drop_database(name) execute "USE master" execute "DROP DATABASE #{name}" end def create_database(name) execute "CREATE DATABASE #{name}" execute "USE #{name}" end def rename_table(name, new_name) execute "EXEC sp_rename '#{name}', '#{new_name}'" end # Adds a new column to the named table. # See TableDefinition#column for details of the options you can use. def add_column(table_name, column_name, type, options = {}) add_column_sql = "ALTER TABLE #{table_name} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" add_column_options!(add_column_sql, options) # TODO: Add support to mimic date columns, using constraints to mark them as such in the database # add_column_sql << " CONSTRAINT ck__#{table_name}__#{column_name}__date_only CHECK ( CONVERT(CHAR(12), #{quote_column_name(column_name)}, 14)='00:00:00:000' )" if type == :date execute(add_column_sql) end def rename_column(table, column, new_column_name) execute "EXEC sp_rename '#{table}.#{column}', '#{new_column_name}'" end def change_column(table_name, column_name, type, options = {}) #:nodoc: change_column_type(table_name, column_name, type, options) change_column_default(table_name, column_name, options[:default]) if options_include_default?(options) end def change_column_type(table_name, column_name, type, options = {}) #:nodoc: sql = "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" if options.has_key?(:null) sql += (options[:null] ? " NULL" : " NOT NULL") end execute(sql) end def change_column_default(table_name, column_name, default) #:nodoc: remove_default_constraint(table_name, column_name) unless default.nil? execute "ALTER TABLE #{table_name} ADD CONSTRAINT DF_#{table_name}_#{column_name} DEFAULT #{quote(default)} FOR #{quote_column_name(column_name)}" end end def remove_column(table_name, column_name) remove_check_constraints(table_name, column_name) remove_default_constraint(table_name, column_name) execute "ALTER TABLE #{table_name} DROP COLUMN [#{column_name}]" end def remove_default_constraint(table_name, column_name) defaults = select "select def.name from sysobjects def, syscolumns col, sysobjects tab where col.cdefault = def.id and col.name = '#{column_name}' and tab.name = '#{table_name}' and col.id = tab.id" defaults.each {|constraint| execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint["name"]}" } end def remove_check_constraints(table_name, column_name) # TODO remove all constraints in single method constraints = select "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '#{table_name}' and COLUMN_NAME = '#{column_name}'" constraints.each do |constraint| execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint["CONSTRAINT_NAME"]}" end end def remove_index(table_name, options = {}) execute "DROP INDEX #{table_name}.#{index_name(table_name, options)}" end def columns(table_name, name = nil) return [] if table_name =~ /^information_schema\./i cc = super cc.each do |col| col.identity = true if col.sql_type =~ /identity/i col.is_special = true if col.sql_type =~ /text|ntext|image/i end cc end def _execute(sql, name = nil) if sql.lstrip =~ /^insert/i if query_requires_identity_insert?(sql) table_name = get_table_name(sql) with_identity_insert_enabled(table_name) do id = @connection.execute_insert(sql) end else @connection.execute_insert(sql) end elsif sql.lstrip =~ /^(create|exec)/i @connection.execute_update(sql) elsif sql.lstrip =~ /^\(?\s*(select|show)/i repair_special_columns(sql) @connection.execute_query(sql) else @connection.execute_update(sql) end end #SELECT .. FOR UPDATE is not supported on Microsoft SQL Server def add_lock!(sql, options) sql end private # Turns IDENTITY_INSERT ON for table during execution of the block # N.B. This sets the state of IDENTITY_INSERT to OFF after the # block has been executed without regard to its previous state def with_identity_insert_enabled(table_name, &block) set_identity_insert(table_name, true) yield ensure set_identity_insert(table_name, false) end def set_identity_insert(table_name, enable = true) execute "SET IDENTITY_INSERT #{table_name} #{enable ? 'ON' : 'OFF'}" rescue Exception => e raise ActiveRecord::ActiveRecordError, "IDENTITY_INSERT could not be turned #{enable ? 'ON' : 'OFF'} for table #{table_name}" end def get_table_name(sql) if sql =~ /^\s*insert\s+into\s+([^\(\s,]+)\s*|^\s*update\s+([^\(\s,]+)\s*/i $1 elsif sql =~ /from\s+([^\(\s,]+)\s*/i $1 else nil end end def identity_column(table_name) @table_columns = {} unless @table_columns @table_columns[table_name] = columns(table_name) if @table_columns[table_name] == nil @table_columns[table_name].each do |col| return col.name if col.identity end return nil end def query_requires_identity_insert?(sql) table_name = get_table_name(sql) id_column = identity_column(table_name) if sql.strip =~ /insert into [^ ]+ ?\((.+?)\)/i insert_columns = $1.split(/, */).map(&method(:unquote_column_name)) return table_name if insert_columns.include?(id_column) end end def unquote_column_name(name) if name =~ /^\[.*\]$/ name[1..-2] else name end end def get_special_columns(table_name) special = [] @table_columns ||= {} @table_columns[table_name] ||= columns(table_name) @table_columns[table_name].each do |col| special << col.name if col.is_special end special end def repair_special_columns(sql) special_cols = get_special_columns(get_table_name(sql)) for col in special_cols.to_a sql.gsub!(Regexp.new(" #{col.to_s} = "), " #{col.to_s} LIKE ") sql.gsub!(/ORDER BY #{col.to_s}/i, '') end sql end def determine_order_clause(sql) return $1 if sql =~ /ORDER BY (.*)$/ sql =~ /FROM +(\w+?)\b/ || raise("can't determine table name") table_name = $1 "#{table_name}.#{determine_primary_key(table_name)}" end def determine_primary_key(table_name) primary_key = columns(table_name).detect { |column| column.primary || column.identity } primary_key ? primary_key.name : "id" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_firebird.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_firebird.rb
module ::JdbcSpec module FireBird def self.adapter_matcher(name, *) name =~ /firebird/i ? self : false end def modify_types(tp) tp[:primary_key] = 'INTEGER NOT NULL PRIMARY KEY' tp[:string][:limit] = 252 tp[:integer][:limit] = nil tp end def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) # :nodoc: execute(sql, name) id_value end def add_limit_offset!(sql, options) # :nodoc: if options[:limit] limit_string = "FIRST #{options[:limit]}" limit_string << " SKIP #{options[:offset]}" if options[:offset] sql.sub!(/\A(\s*SELECT\s)/i, '\&' + limit_string + ' ') end end def prefetch_primary_key?(table_name = nil) true end def default_sequence_name(table_name, primary_key) # :nodoc: "#{table_name}_seq" end def next_sequence_value(sequence_name) select_one("SELECT GEN_ID(#{sequence_name}, 1 ) FROM RDB$DATABASE;")["gen_id"] end def create_table(name, options = {}) #:nodoc: super(name, options) execute "CREATE GENERATOR #{name}_seq" end def rename_table(name, new_name) #:nodoc: execute "RENAME #{name} TO #{new_name}" execute "UPDATE RDB$GENERATORS SET RDB$GENERATOR_NAME='#{new_name}_seq' WHERE RDB$GENERATOR_NAME='#{name}_seq'" rescue nil end def drop_table(name, options = {}) #:nodoc: super(name) execute "DROP GENERATOR #{name}_seq" rescue nil end def change_column(table_name, column_name, type, options = {}) #:nodoc: execute "ALTER TABLE #{table_name} ALTER #{column_name} TYPE #{type_to_sql(type, options[:limit])}" end def rename_column(table_name, column_name, new_column_name) execute "ALTER TABLE #{table_name} ALTER #{column_name} TO #{new_column_name}" end def remove_index(table_name, options) #:nodoc: execute "DROP INDEX #{index_name(table_name, options)}" end def quote(value, column = nil) # :nodoc: return value.quoted_id if value.respond_to?(:quoted_id) if [Time, DateTime].include?(value.class) "CAST('#{value.strftime("%Y-%m-%d %H:%M:%S")}' AS TIMESTAMP)" else if column && column.type == :primary_key return value.to_s end super end end def quote_string(string) # :nodoc: string.gsub(/'/, "''") end def quote_column_name(column_name) # :nodoc: %Q("#{ar_to_fb_case(column_name)}") end def quoted_true # :nodoc: quote(1) end def quoted_false # :nodoc: quote(0) end private # Maps uppercase Firebird column names to lowercase for ActiveRecord; # mixed-case columns retain their original case. def fb_to_ar_case(column_name) column_name =~ /[[:lower:]]/ ? column_name : column_name.to_s.downcase end # Maps lowercase ActiveRecord column names to uppercase for Fierbird; # mixed-case columns retain their original case. def ar_to_fb_case(column_name) column_name =~ /[[:upper:]]/ ? column_name : column_name.to_s.upcase end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_hsqldb.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_hsqldb.rb
module ::JdbcSpec module ActiveRecordExtensions def hsqldb_connection(config) require File.dirname(__FILE__) + "/../active_record/connection_adapters/hsqldb_adapter" config[:url] ||= "jdbc:hsqldb:#{config[:database]}" config[:driver] ||= "org.hsqldb.jdbcDriver" embedded_driver(config) end def h2_connection(config) require File.dirname(__FILE__) + "/../active_record/connection_adapters/h2_adapter" config[:url] ||= "jdbc:h2:#{config[:database]}" config[:driver] ||= "org.h2.Driver" embedded_driver(config) end end module HSQLDB def self.extended(mod) mod.class.class_eval do alias_chained_method :insert, :query_dirty, :insert end end def self.adapter_matcher(name, *) name =~ /hsqldb/i ? self : false end def self.column_selector [/hsqldb|\.h2\./i, lambda {|cfg,col| col.extend(::JdbcSpec::HSQLDB::Column)}] end module Column private def simplified_type(field_type) case field_type when /longvarchar/i :text when /tinyint/i :boolean when /real/i :float else super(field_type) end end # Override of ActiveRecord::ConnectionAdapters::Column def extract_limit(sql_type) # HSQLDB appears to return "LONGVARCHAR(0)" for :text columns, which # for AR purposes should be interpreted as "no limit" return nil if sql_type =~ /\(0\)/ super end # Post process default value from JDBC into a Rails-friendly format (columns{-internal}) def default_value(value) # jdbc returns column default strings with actual single quotes around the value. return $1 if value =~ /^'(.*)'$/ value end end def adapter_name #:nodoc: defined?(::Jdbc::H2) ? 'H2' : 'Hsqldb' end def modify_types(tp) tp[:primary_key] = "INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY" tp[:integer][:limit] = nil tp[:boolean][:limit] = nil # set text and float limits so we don't see odd scales tacked on # in migrations tp[:boolean] = { :name => "tinyint" } tp[:text][:limit] = nil tp[:float][:limit] = 17 if defined?(::Jdbc::H2) tp[:string][:limit] = 255 tp[:datetime] = { :name => "DATETIME" } tp[:timestamp] = { :name => "DATETIME" } tp[:time] = { :name => "TIME" } tp[:date] = { :name => "DATE" } tp end def quote(value, column = nil) # :nodoc: return value.quoted_id if value.respond_to?(:quoted_id) case value when String if respond_to?(:h2_adapter) && value.empty? "''" elsif column && column.type == :binary "'#{value.unpack("H*")}'" elsif column && (column.type == :integer || column.respond_to?(:primary) && column.primary && column.klass != String) value.to_i.to_s else "'#{quote_string(value)}'" end else super end end def quote_column_name(name) #:nodoc: name = name.to_s if name =~ /[-]/ %Q{"#{name.upcase}"} else name end end def quote_string(str) str.gsub(/'/, "''") end def quoted_true '1' end def quoted_false '0' end def add_column(table_name, column_name, type, options = {}) if option_not_null = options[:null] == false option_not_null = options.delete(:null) end add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" add_column_options!(add_column_sql, options) execute(add_column_sql) if option_not_null alter_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} NOT NULL" end end def change_column(table_name, column_name, type, options = {}) #:nodoc: execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} #{type_to_sql(type, options[:limit])}" end def change_column_default(table_name, column_name, default) #:nodoc: execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} SET DEFAULT #{quote(default)}" end def rename_column(table_name, column_name, new_column_name) #:nodoc: execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} RENAME TO #{new_column_name}" end # Maps logical Rails types to MySQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil) return super if defined?(::Jdbc::H2) || type.to_s != 'integer' || limit == nil type end def rename_table(name, new_name) execute "ALTER TABLE #{name} RENAME TO #{new_name}" end def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc: log(sql,name) do @connection.execute_update(sql) end table = sql.split(" ", 4)[2] id_value || last_insert_id(table, nil) end def last_insert_id(table, sequence_name) Integer(select_value("CALL IDENTITY()")) end # Override normal #_execute: See Rubyforge #11567 def _execute(sql, name = nil) if ::ActiveRecord::ConnectionAdapters::JdbcConnection::select?(sql) @connection.execute_query(sql) elsif ::ActiveRecord::ConnectionAdapters::JdbcConnection::insert?(sql) insert(sql, name) else @connection.execute_update(sql) end end def add_limit_offset!(sql, options) #:nodoc: offset = options[:offset] || 0 bef = sql[7..-1] if limit = options[:limit] sql.replace "select limit #{offset} #{limit} #{bef}" elsif offset > 0 sql.replace "select limit #{offset} 0 #{bef}" end end # override to filter out system tables that otherwise end # up in db/schema.rb during migrations. JdbcConnection#tables # now takes an optional block filter so we can screen out # rows corresponding to system tables. HSQLDB names its # system tables SYSTEM.*, but H2 seems to name them without # any kind of convention def tables @connection.tables.select {|row| row.to_s !~ /^system_/i } end def remove_index(table_name, options = {}) execute "DROP INDEX #{quote_column_name(index_name(table_name, options))}" end end module H2 include HSQLDB def self.adapter_matcher(name, *) name =~ /\.h2\./i ? self : false end def h2_adapter true end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/tsql_helper.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/tsql_helper.rb
# Common methods for handling TSQL databases. module TSqlMethods def modify_types(tp) #:nodoc: tp[:primary_key] = "int NOT NULL IDENTITY(1, 1) PRIMARY KEY" tp[:integer][:limit] = nil tp[:boolean] = {:name => "bit"} tp[:binary] = { :name => "image"} tp end def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc: return 'uniqueidentifier' if (type.to_s == 'uniqueidentifier') return super unless type.to_s == 'integer' if limit.nil? || limit == 4 'int' elsif limit == 2 'smallint' elsif limit == 1 'tinyint' else 'bigint' end end def add_limit_offset!(sql, options) if options[:limit] and options[:offset] total_rows = select_all("SELECT count(*) as TotalRows from (#{sql.gsub(/\bSELECT(\s+DISTINCT)?\b/i, "SELECT\\1 TOP 1000000000")}) tally")[0]["TotalRows"].to_i if (options[:limit] + options[:offset]) >= total_rows options[:limit] = (total_rows - options[:offset] >= 0) ? (total_rows - options[:offset]) : 0 end sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i, "SELECT * FROM (SELECT TOP #{options[:limit]} * FROM (SELECT\\1 TOP #{options[:limit] + options[:offset]} ") sql << ") AS tmp1" if options[:order] options[:order] = options[:order].split(',').map do |field| parts = field.split(" ") tc = parts[0] if sql =~ /\.\[/ and tc =~ /\./ # if column quoting used in query tc.gsub!(/\./, '\\.\\[') tc << '\\]' end if sql =~ /#{tc} AS (t\d_r\d\d?)/ parts[0] = $1 elsif parts[0] =~ /\w+\.(\w+)/ parts[0] = $1 end parts.join(' ') end.join(', ') sql << " ORDER BY #{change_order_direction(options[:order])}) AS tmp2 ORDER BY #{options[:order]}" else sql << " ) AS tmp2" end elsif sql !~ /^\s*SELECT (@@|COUNT\()/i sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i) do "SELECT#{$1} TOP #{options[:limit]}" end unless options[:limit].nil? end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_cachedb.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_cachedb.rb
require 'jdbc_adapter/tsql_helper' module ::JdbcSpec module ActiveRecordExtensions def cachedb_connection( config ) config[:port] ||= 1972 config[:url] ||= "jdbc:Cache://#{config[:host]}:#{config[:port]}/#{ config[:database]}" config[:driver] ||= "com.intersys.jdbc.CacheDriver" jdbc_connection( config ) end end module CacheDB include TSqlMethods def self.adapter_matcher(name, *) name =~ /cache/i ? self : false end def self.column_selector [ /cache/i, lambda { | cfg, col | col.extend( ::JdbcSpec::CacheDB::Column ) } ] end module Column end def create_table(name, options = { }) super(name, options) primary_key = options[:primary_key] || "id" execute "ALTER TABLE #{name} ADD CONSTRAINT #{name}_PK PRIMARY KEY(#{primary_key})" unless options[:id] == false end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_mysql.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_mysql.rb
require 'active_record/connection_adapters/abstract/schema_definitions' module ::JdbcSpec # Don't need to load native mysql adapter $LOADED_FEATURES << "active_record/connection_adapters/mysql_adapter.rb" module ActiveRecordExtensions add_method_to_remove_from_ar_base(:mysql_connection) def mysql_connection(config) require File.dirname(__FILE__) + "/../active_record/connection_adapters/mysql_adapter" config[:port] ||= 3306 url_options = "zeroDateTimeBehavior=convertToNull&jdbcCompliantTruncation=false&useUnicode=true&characterEncoding=" url_options << (config[:encoding] || 'utf8') if config[:url] config[:url] = config[:url]['?'] ? "#{config[:url]}&#{url_options}" : "#{config[:url]}?#{url_options}" else config[:url] = "jdbc:mysql://#{config[:host]}:#{config[:port]}/#{config[:database]}?#{url_options}" end config[:driver] = "com.mysql.jdbc.Driver" connection = jdbc_connection(config) ::JdbcSpec::MySQL.kill_cancel_timer(connection.raw_connection) connection end end module MySQL def self.adapter_matcher(name, *) name =~ /mysql/i ? self : false end def self.column_selector [/mysql/i, lambda {|cfg,col| col.extend(::JdbcSpec::MySQL::Column)}] end def self.extended(adapter) adapter.execute("SET SQL_AUTO_IS_NULL=0") end module Column TYPES_ALLOWING_EMPTY_STRING_DEFAULT = Set.new([:binary, :string, :text]) def simplified_type(field_type) return :boolean if field_type =~ /tinyint\(1\)|bit/i return :string if field_type =~ /enum/i super end def init_column(name, default, *args) @original_default = default @default = nil if missing_default_forged_as_empty_string? end # MySQL misreports NOT NULL column default when none is given. # We can't detect this for columns which may have a legitimate '' # default (string, text, binary) but we can for others (integer, # datetime, boolean, and the rest). # # Test whether the column has default '', is not null, and is not # a type allowing default ''. def missing_default_forged_as_empty_string? !null && @original_default == '' && !TYPES_ALLOWING_EMPTY_STRING_DEFAULT.include?(type) end end def modify_types(tp) tp[:primary_key] = "int(11) DEFAULT NULL auto_increment PRIMARY KEY" tp[:decimal] = { :name => "decimal" } tp[:timestamp] = { :name => "datetime" } tp[:datetime][:limit] = nil tp end def adapter_name #:nodoc: 'mysql' end # QUOTING ================================================== def quote(value, column = nil) return value.quoted_id if value.respond_to?(:quoted_id) if column && column.type == :primary_key value.to_s elsif column && String === value && column.type == :binary && column.class.respond_to?(:string_to_binary) s = column.class.string_to_binary(value).unpack("H*")[0] "x'#{s}'" elsif BigDecimal === value "'#{value.to_s("F")}'" else super end end def quoted_true "1" end def quoted_false "0" end def begin_db_transaction #:nodoc: @connection.begin rescue Exception # Transactions aren't supported end def commit_db_transaction #:nodoc: @connection.commit rescue Exception # Transactions aren't supported end def rollback_db_transaction #:nodoc: @connection.rollback rescue Exception # Transactions aren't supported end def supports_savepoints? #:nodoc: true end def create_savepoint execute("SAVEPOINT #{current_savepoint_name}") end def rollback_to_savepoint execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}") end def release_savepoint execute("RELEASE SAVEPOINT #{current_savepoint_name}") end def disable_referential_integrity(&block) #:nodoc: old = select_value("SELECT @@FOREIGN_KEY_CHECKS") begin update("SET FOREIGN_KEY_CHECKS = 0") yield ensure update("SET FOREIGN_KEY_CHECKS = #{old}") end end # SCHEMA STATEMENTS ======================================== def structure_dump #:nodoc: if supports_views? sql = "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'" else sql = "SHOW TABLES" end select_all(sql).inject("") do |structure, table| table.delete('Table_type') hash = show_create_table(table.to_a.first.last) if(table = hash["Create Table"]) structure += table + ";\n\n" elsif(view = hash["Create View"]) structure += view + ";\n\n" end end end def recreate_database(name, options = {}) #:nodoc: drop_database(name) create_database(name, options) end def character_set(options) #:nodoc: str = "CHARACTER SET `#{options[:charset] || 'utf8'}`" str += " COLLATE `#{options[:collation]}`" if options[:collation] str end private :character_set def create_database(name, options = {}) #:nodoc: execute "CREATE DATABASE `#{name}` DEFAULT #{character_set(options)}" end def drop_database(name) #:nodoc: execute "DROP DATABASE IF EXISTS `#{name}`" end def current_database select_one("SELECT DATABASE() as db")["db"] end def create_table(name, options = {}) #:nodoc: super(name, {:options => "ENGINE=InnoDB #{character_set(options)}"}.merge(options)) end def rename_table(name, new_name) execute "RENAME TABLE #{quote_table_name(name)} TO #{quote_table_name(new_name)}" end def change_column_default(table_name, column_name, default) #:nodoc: current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"] execute("ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{current_type} DEFAULT #{quote(default)}") end def change_column(table_name, column_name, type, options = {}) #:nodoc: unless options_include_default?(options) if column = columns(table_name).find { |c| c.name == column_name.to_s } options[:default] = column.default else raise "No such column: #{table_name}.#{column_name}" end end change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" add_column_options!(change_column_sql, options) execute(change_column_sql) end def rename_column(table_name, column_name, new_column_name) #:nodoc: cols = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'") current_type = cols["Type"] || cols["COLUMN_TYPE"] execute "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_table_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}" end def add_limit_offset!(sql, options) #:nodoc: if limit = options[:limit] unless offset = options[:offset] sql << " LIMIT #{limit}" else sql << " LIMIT #{offset}, #{limit}" end end end def show_variable(var) res = execute("show variables like '#{var}'") row = res.detect {|row| row["Variable_name"] == var } row && row["Value"] end def charset show_variable("character_set_database") end def collation show_variable("collation_database") end private def show_create_table(table) select_one("SHOW CREATE TABLE #{quote_table_name(table)}") end def supports_views? false end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/missing_functionality_helper.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/missing_functionality_helper.rb
module JdbcSpec module MissingFunctionalityHelper #Taken from SQLite adapter def alter_table(table_name, options = {}) #:nodoc: table_name = table_name.to_s.downcase altered_table_name = "altered_#{table_name}" caller = lambda {|definition| yield definition if block_given?} transaction do # A temporary table might improve performance here, but # it doesn't seem to maintain indices across the whole move. move_table(table_name, altered_table_name, options) move_table(altered_table_name, table_name, &caller) end end def move_table(from, to, options = {}, &block) #:nodoc: copy_table(from, to, options, &block) drop_table(from) end def copy_table(from, to, options = {}) #:nodoc: options = options.merge(:id => (!columns(from).detect{|c| c.name == 'id'}.nil? && 'id' == primary_key(from).to_s)) create_table(to, options) do |definition| @definition = definition columns(from).each do |column| column_name = options[:rename] ? (options[:rename][column.name] || options[:rename][column.name.to_sym] || column.name) : column.name @definition.column(column_name, column.type, :limit => column.limit, :default => column.default, :null => column.null) end @definition.primary_key(primary_key(from)) if primary_key(from) yield @definition if block_given? end copy_table_indexes(from, to, options[:rename] || {}) copy_table_contents(from, to, @definition.columns.map {|column| column.name}, options[:rename] || {}) end def copy_table_indexes(from, to, rename = {}) #:nodoc: indexes(from).each do |index| name = index.name.downcase if to == "altered_#{from}" name = "temp_#{name}" elsif from == "altered_#{to}" name = name[5..-1] end to_column_names = columns(to).map(&:name) columns = index.columns.map {|c| rename[c] || c }.select do |column| to_column_names.include?(column) end unless columns.empty? # index name can't be the same opts = { :name => name.gsub(/(_?)(#{from})_/, "\\1#{to}_") } opts[:unique] = true if index.unique add_index(to, columns, opts) end end end def copy_table_contents(from, to, columns, rename = {}) #:nodoc: column_mappings = Hash[*columns.map {|name| [name, name]}.flatten] rename.inject(column_mappings) {|map, a| map[a.last] = a.first; map} from_columns = columns(from).collect {|col| col.name} columns = columns.find_all{|col| from_columns.include?(column_mappings[col])} quoted_columns = columns.map { |col| quote_column_name(col) } * ',' quoted_to = quote_table_name(to) execute("SELECT * FROM #{quote_table_name(from)}").each do |row| sql = "INSERT INTO #{quoted_to} (#{quoted_columns}) VALUES (" sql << columns.map {|col| quote row[column_mappings[col]]} * ', ' sql << ')' execute sql end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_derby.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/jdbc_adapter/jdbc_derby.rb
require 'jdbc_adapter/missing_functionality_helper' module ::JdbcSpec module ActiveRecordExtensions def derby_connection(config) require File.dirname(__FILE__) + "/../active_record/connection_adapters/derby_adapter" config[:url] ||= "jdbc:derby:#{config[:database]};create=true" config[:driver] ||= "org.apache.derby.jdbc.EmbeddedDriver" check_version(embedded_driver(config)) end def check_version(conn) md = conn.raw_connection.connection.meta_data if md.database_major_version < 10 || md.database_minor_version < 5 raise ::ActiveRecord::ConnectionFailed, "Derby adapter requires Derby 10.5 or later" end conn end end module Derby def self.adapter_matcher(name, *) name =~ /derby/i ? self : false end def self.column_selector [/derby/i, lambda {|cfg,col| col.extend(::JdbcSpec::Derby::Column)}] end def self.monkey_rails unless @already_monkeyd # Needed because Rails is broken wrt to quoting of # some values. Most databases are nice about it, # but not Derby. The real issue is that you can't # compare a CHAR value to a NUMBER column. ::ActiveRecord::Associations::ClassMethods.module_eval do private def select_limited_ids_list(options, join_dependency) connection.select_all( construct_finder_sql_for_association_limiting(options, join_dependency), "#{name} Load IDs For Limited Eager Loading" ).collect { |row| connection.quote(row[primary_key], columns_hash[primary_key]) }.join(", ") end end @already_monkeyd = true end end def self.extended(*args) monkey_rails end def self.included(*args) monkey_rails end module Column def simplified_type(field_type) return :boolean if field_type =~ /smallint/i return :float if field_type =~ /real/i super end # Post process default value from JDBC into a Rails-friendly format (columns{-internal}) def default_value(value) # jdbc returns column default strings with actual single quotes around the value. return $1 if value =~ /^'(.*)'$/ value end end def adapter_name #:nodoc: 'Derby' end include JdbcSpec::MissingFunctionalityHelper # Convert the speficied column type to a SQL string. In Derby, :integers cannot specify # a limit. def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc: return super unless type == :integer native = native_database_types[type.to_s.downcase.to_sym] native.is_a?(Hash) ? native[:name] : native end def modify_types(tp) tp[:primary_key] = "int generated by default as identity NOT NULL PRIMARY KEY" tp[:integer][:limit] = nil tp[:string][:limit] = 256 tp[:boolean] = {:name => "smallint"} tp end # Override default -- fix case where ActiveRecord passes :default => nil, :null => true def add_column_options!(sql, options) options.delete(:default) if options.has_key?(:default) && options[:default].nil? options.delete(:null) if options.has_key?(:null) && (options[:null].nil? || options[:null] == true) super end def classes_for_table_name(table) ActiveRecord::Base.send(:subclasses).select {|klass| klass.table_name == table} end # Set the sequence to the max value of the table's column. def reset_sequence!(table, column, sequence = nil) mpk = select_value("SELECT MAX(#{quote_column_name(column)}) FROM #{quote_table_name(table)}") execute("ALTER TABLE #{quote_table_name(table)} ALTER COLUMN #{quote_column_name(column)} RESTART WITH #{mpk.to_i + 1}") end def reset_pk_sequence!(table, pk = nil, sequence = nil) klasses = classes_for_table_name(table) klass = klasses.nil? ? nil : klasses.first pk = klass.primary_key unless klass.nil? if pk && klass.columns_hash[pk].type == :integer reset_sequence!(klass.table_name, pk) end end def remove_index(table_name, options) #:nodoc: execute "DROP INDEX #{index_name(table_name, options)}" end def rename_table(name, new_name) execute "RENAME TABLE #{name} TO #{new_name}" end COLUMN_INFO_STMT = "SELECT C.COLUMNNAME, C.REFERENCEID, C.COLUMNNUMBER FROM SYS.SYSCOLUMNS C, SYS.SYSTABLES T WHERE T.TABLEID = '%s' AND T.TABLEID = C.REFERENCEID ORDER BY C.COLUMNNUMBER" COLUMN_TYPE_STMT = "SELECT COLUMNDATATYPE, COLUMNDEFAULT FROM SYS.SYSCOLUMNS WHERE REFERENCEID = '%s' AND COLUMNNAME = '%s'" AUTO_INC_STMT = "SELECT AUTOINCREMENTSTART, AUTOINCREMENTINC, COLUMNNAME, REFERENCEID, COLUMNDEFAULT FROM SYS.SYSCOLUMNS WHERE REFERENCEID = '%s' AND COLUMNNAME = '%s'" AUTO_INC_STMT2 = "SELECT AUTOINCREMENTSTART, AUTOINCREMENTINC, COLUMNNAME, REFERENCEID, COLUMNDEFAULT FROM SYS.SYSCOLUMNS WHERE REFERENCEID = (SELECT T.TABLEID FROM SYS.SYSTABLES T WHERE T.TABLENAME = '%s') AND COLUMNNAME = '%s'" def add_quotes(name) return name unless name %Q{"#{name}"} end def strip_quotes(str) return str unless str return str unless /^(["']).*\1$/ =~ str str[1..-2] end def expand_double_quotes(name) return name unless name && name['"'] name.gsub(/"/,'""') end def reinstate_auto_increment(name, refid, coldef) stmt = AUTO_INC_STMT % [refid, strip_quotes(name)] data = execute(stmt).first if data start = data['autoincrementstart'] if start coldef << " GENERATED " << (data['columndefault'].nil? ? "ALWAYS" : "BY DEFAULT ") coldef << "AS IDENTITY (START WITH " coldef << start coldef << ", INCREMENT BY " coldef << data['autoincrementinc'] coldef << ")" return true end end false end def reinstate_auto_increment(name, refid, coldef) stmt = AUTO_INC_STMT % [refid, strip_quotes(name)] data = execute(stmt).first if data start = data['autoincrementstart'] if start coldef << " GENERATED " << (data['columndefault'].nil? ? "ALWAYS" : "BY DEFAULT ") coldef << "AS IDENTITY (START WITH " coldef << start coldef << ", INCREMENT BY " coldef << data['autoincrementinc'] coldef << ")" return true end end false end def auto_increment_stmt(tname, cname) stmt = AUTO_INC_STMT2 % [tname, strip_quotes(cname)] data = execute(stmt).first if data start = data['autoincrementstart'] if start coldef = "" coldef << " GENERATED " << (data['columndefault'].nil? ? "ALWAYS" : "BY DEFAULT ") coldef << "AS IDENTITY (START WITH " coldef << start coldef << ", INCREMENT BY " coldef << data['autoincrementinc'] coldef << ")" return coldef end end "" end def add_column(table_name, column_name, type, options = {}) if option_not_null = options[:null] == false option_not_null = options.delete(:null) end add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" add_column_options!(add_column_sql, options) execute(add_column_sql) if option_not_null alter_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} NOT NULL" end end def execute(sql, name = nil) if sql =~ /^\s*(UPDATE|INSERT)/i i = sql =~ /\swhere\s/im if i sql[i..-1] = sql[i..-1].gsub(/!=\s*NULL/, 'IS NOT NULL').gsub(/=\sNULL/i, 'IS NULL') end else sql.gsub!(/= NULL/i, 'IS NULL') end super end # I don't think this method is ever called ??? (stepheneb) def create_column(name, refid, colno) stmt = COLUMN_TYPE_STMT % [refid, strip_quotes(name)] coldef = "" data = execute(stmt).first if data coldef << add_quotes(expand_double_quotes(strip_quotes(name))) coldef << " " coldef << data['columndatatype'] if !reinstate_auto_increment(name, refid, coldef) && data['columndefault'] coldef << " DEFAULT " << data['columndefault'] end end coldef end SIZEABLE = %w(VARCHAR CLOB BLOB) def structure_dump #:nodoc: definition="" rs = @connection.connection.meta_data.getTables(nil,nil,nil,["TABLE"].to_java(:string)) while rs.next tname = rs.getString(3) definition << "CREATE TABLE #{tname} (\n" rs2 = @connection.connection.meta_data.getColumns(nil,nil,tname,nil) first_col = true while rs2.next col_name = add_quotes(rs2.getString(4)); default = "" d1 = rs2.getString(13) if d1 =~ /^GENERATED_/ default = auto_increment_stmt(tname, col_name) elsif d1 default = " DEFAULT #{d1}" end type = rs2.getString(6) col_size = rs2.getString(7) nulling = (rs2.getString(18) == 'NO' ? " NOT NULL" : "") create_col_string = add_quotes(expand_double_quotes(strip_quotes(col_name))) + " " + type + (SIZEABLE.include?(type) ? "(#{col_size})" : "") + nulling + default if !first_col create_col_string = ",\n #{create_col_string}" else create_col_string = " #{create_col_string}" end definition << create_col_string first_col = false end definition << ");\n\n" end definition end # Support for removing columns added via derby bug issue: # https://issues.apache.org/jira/browse/DERBY-1489 # # This feature has not made it into a formal release and is not in Java 6. # If the normal strategy fails we fall back on a strategy by creating a new # table without the new column and there after moving the data to the new # def remove_column(table_name, column_name) begin execute "ALTER TABLE #{table_name} DROP COLUMN #{column_name} RESTRICT" rescue alter_table(table_name) do |definition| definition.columns.delete(definition[column_name]) end end end # Notes about changing in Derby: # http://db.apache.org/derby/docs/10.2/ref/rrefsqlj81859.html#rrefsqlj81859__rrefsqlj37860) # # We support changing columns using the strategy outlined in: # https://issues.apache.org/jira/browse/DERBY-1515 # # This feature has not made it into a formal release and is not in Java 6. We will # need to conditionally support this somehow (supposed to arrive for 10.3.0.0) def change_column(table_name, column_name, type, options = {}) # null/not nulling is easy, handle that separately if options.include?(:null) # This seems to only work with 10.2 of Derby if options.delete(:null) == false execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} NOT NULL" else execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} NULL" end end # anything left to do? unless options.empty? begin execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} SET DATA TYPE #{type_to_sql(type, options[:limit])}" rescue transaction do temp_new_column_name = "#{column_name}_newtype" # 1) ALTER TABLE t ADD COLUMN c1_newtype NEWTYPE; add_column table_name, temp_new_column_name, type, options # 2) UPDATE t SET c1_newtype = c1; execute "UPDATE #{table_name} SET #{temp_new_column_name} = CAST(#{column_name} AS #{type_to_sql(type, options[:limit])})" # 3) ALTER TABLE t DROP COLUMN c1; remove_column table_name, column_name # 4) ALTER TABLE t RENAME COLUMN c1_newtype to c1; rename_column table_name, temp_new_column_name, column_name end end end end # Support for renaming columns: # https://issues.apache.org/jira/browse/DERBY-1490 # # This feature is expect to arrive in version 10.3.0.0: # http://wiki.apache.org/db-derby/DerbyTenThreeRelease) # def rename_column(table_name, column_name, new_column_name) #:nodoc: begin execute "ALTER TABLE #{table_name} ALTER RENAME COLUMN #{column_name} TO #{new_column_name}" rescue alter_table(table_name, :rename => {column_name => new_column_name}) end end def primary_keys(table_name) @connection.primary_keys table_name.to_s.upcase end def columns(table_name, name=nil) @connection.columns_internal(table_name.to_s, name, derby_schema) end def tables @connection.tables(nil, derby_schema) end def recreate_database(db_name) tables.each do |t| drop_table t end end # For DDL it appears you can quote "" column names, but in queries (like insert it errors out?) def quote_column_name(name) #:nodoc: name = name.to_s if /^(references|integer|key|group|year)$/i =~ name %Q{"#{name.upcase}"} elsif /[A-Z]/ =~ name && /[a-z]/ =~ name %Q{"#{name}"} elsif name =~ /[\s-]/ %Q{"#{name.upcase}"} elsif name =~ /^[_\d]/ %Q{"#{name.upcase}"} else name end end def quoted_true '1' end def quoted_false '0' end def add_limit_offset!(sql, options) #:nodoc: if options[:offset] sql << " OFFSET #{options[:offset]} ROWS" end if options[:limit] #ROWS/ROW and FIRST/NEXT mean the same sql << " FETCH FIRST #{options[:limit]} ROWS ONLY" end end private # Derby appears to define schemas using the username def derby_schema @config[:username].to_s end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/h2_compiler.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/h2_compiler.rb
module Arel module SqlCompiler class H2Compiler < GenericCompiler end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/hsqldb_compiler.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/hsqldb_compiler.rb
module Arel module SqlCompiler class HsqldbCompiler < GenericCompiler end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/derby_compiler.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/derby_compiler.rb
module Arel module SqlCompiler class DerbyCompiler < GenericCompiler end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/jdbc_compiler.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/jdbc_compiler.rb
module Arel module SqlCompiler class JDBCCompiler < GenericCompiler end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/db2_compiler.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/arel/engines/sql/compilers/db2_compiler.rb
require 'arel/engines/sql/compilers/ibm_db_compiler' module Arel module SqlCompiler class DB2Compiler < IBM_DBCompiler end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/generators/jdbc/jdbc_generator.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/generators/jdbc/jdbc_generator.rb
class JdbcGenerator < Rails::Generators::Base def self.source_root @source_root ||= File.expand_path('../../../../rails_generators/templates', __FILE__) end def create_jdbc_files directory '.', '.' end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/sqlite3_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/sqlite3_adapter.rb
tried_gem = false begin require "jdbc/sqlite3" rescue LoadError unless tried_gem require 'rubygems' gem "jdbc-sqlite3" tried_gem = true retry end # trust that the sqlite jar is already present end require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/jndi_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/jndi_adapter.rb
require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/h2_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/h2_adapter.rb
tried_gem = false begin require "jdbc/h2" rescue LoadError unless tried_gem require 'rubygems' gem "jdbc-h2" tried_gem = true retry end # trust that the hsqldb jar is already present end require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/hsqldb_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/hsqldb_adapter.rb
tried_gem = false begin require "jdbc/hsqldb" rescue LoadError unless tried_gem require 'rubygems' gem "jdbc-hsqldb" tried_gem = true retry end # trust that the hsqldb jar is already present end require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/oracle_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/oracle_adapter.rb
require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/derby_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/derby_adapter.rb
tried_gem = false begin require "jdbc/derby" rescue LoadError unless tried_gem require 'rubygems' gem "jdbc-derby" tried_gem = true retry end # trust that the derby jar is already present end require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/mysql_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/mysql_adapter.rb
tried_gem = false begin require "jdbc/mysql" rescue LoadError unless tried_gem require 'rubygems' gem "jdbc-mysql" tried_gem = true retry end # trust that the mysql jar is already present end require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/postgresql_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/postgresql_adapter.rb
tried_gem = false begin require "jdbc/postgres" rescue LoadError unless tried_gem require 'rubygems' gem "jdbc-postgres" tried_gem = true retry end # trust that the postgres jar is already present end require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/jdbc_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/jdbc_adapter.rb
require 'active_record/version' require 'active_record/connection_adapters/abstract_adapter' require 'java' require 'active_record/connection_adapters/jdbc_adapter_spec' require 'jdbc_adapter/jdbc_adapter_internal' require 'bigdecimal' # AR's 2.2 version of this method is sufficient, but we need it for # older versions if ActiveRecord::VERSION::MAJOR <= 2 && ActiveRecord::VERSION::MINOR < 2 module ActiveRecord module ConnectionAdapters # :nodoc: module SchemaStatements # Convert the speficied column type to a SQL string. def type_to_sql(type, limit = nil, precision = nil, scale = nil) if native = native_database_types[type] column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup if type == :decimal # ignore limit, use precision and scale scale ||= native[:scale] if precision ||= native[:precision] if scale column_type_sql << "(#{precision},#{scale})" else column_type_sql << "(#{precision})" end elsif scale raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale if specified" end elsif limit ||= native.is_a?(Hash) && native[:limit] column_type_sql << "(#{limit})" end column_type_sql else type end end end end end end module JdbcSpec module ActiveRecordExtensions def jdbc_connection(config) ::ActiveRecord::ConnectionAdapters::JdbcAdapter.new(nil, logger, config) end alias jndi_connection jdbc_connection def embedded_driver(config) config[:username] ||= "sa" config[:password] ||= "" jdbc_connection(config) end end module QuotedPrimaryKeyExtension def self.extended(base) # Rails 3 method Rails 2 method meth = [:arel_attributes_values, :attributes_with_quotes].detect do |m| base.private_instance_methods.include?(m.to_s) end pk_hash_key = "self.class.primary_key" pk_hash_value = '"?"' if meth == :arel_attributes_values pk_hash_key = "self.class.arel_table[#{pk_hash_key}]" pk_hash_value = "Arel::SqlLiteral.new(#{pk_hash_value})" end if meth base.module_eval %{ alias :#{meth}_pre_pk :#{meth} def #{meth}(include_primary_key = true, *args) #:nodoc: aq = #{meth}_pre_pk(include_primary_key, *args) if connection.is_a?(JdbcSpec::Oracle) || connection.is_a?(JdbcSpec::Mimer) aq[#{pk_hash_key}] = #{pk_hash_value} if include_primary_key && aq[#{pk_hash_key}].nil? end aq end } end end end end module ActiveRecord class Base extend JdbcSpec::ActiveRecordExtensions end module ConnectionAdapters module Java Class = java.lang.Class URL = java.net.URL URLClassLoader = java.net.URLClassLoader end module Jdbc Mutex = java.lang.Object.new DriverManager = java.sql.DriverManager Statement = java.sql.Statement Types = java.sql.Types # some symbolic constants for the benefit of the JDBC-based # JdbcConnection#indexes method module IndexMetaData INDEX_NAME = 6 NON_UNIQUE = 4 TABLE_NAME = 3 COLUMN_NAME = 9 end module TableMetaData TABLE_CAT = 1 TABLE_SCHEM = 2 TABLE_NAME = 3 TABLE_TYPE = 4 end module PrimaryKeyMetaData COLUMN_NAME = 4 end end # I want to use JDBC's DatabaseMetaData#getTypeInfo to choose the best native types to # use for ActiveRecord's Adapter#native_database_types in a database-independent way, # but apparently a database driver can return multiple types for a given # java.sql.Types constant. So this type converter uses some heuristics to try to pick # the best (most common) type to use. It's not great, it would be better to just # delegate to each database's existin AR adapter's native_database_types method, but I # wanted to try to do this in a way that didn't pull in all the other adapters as # dependencies. Suggestions appreciated. class JdbcTypeConverter # The basic ActiveRecord types, mapped to an array of procs that are used to #select # the best type. The procs are used as selectors in order until there is only one # type left. If all the selectors are applied and there is still more than one # type, an exception will be raised. AR_TO_JDBC_TYPES = { :string => [ lambda {|r| Jdbc::Types::VARCHAR == r['data_type'].to_i}, lambda {|r| r['type_name'] =~ /^varchar/i}, lambda {|r| r['type_name'] =~ /^varchar$/i}, lambda {|r| r['type_name'] =~ /varying/i}], :text => [ lambda {|r| [Jdbc::Types::LONGVARCHAR, Jdbc::Types::CLOB].include?(r['data_type'].to_i)}, lambda {|r| r['type_name'] =~ /^text$/i}, # For Informix lambda {|r| r['type_name'] =~ /^(text|clob)$/i}, lambda {|r| r['type_name'] =~ /^character large object$/i}, lambda {|r| r['sql_data_type'] == 2005}], :integer => [ lambda {|r| Jdbc::Types::INTEGER == r['data_type'].to_i}, lambda {|r| r['type_name'] =~ /^integer$/i}, lambda {|r| r['type_name'] =~ /^int4$/i}, lambda {|r| r['type_name'] =~ /^int$/i}], :decimal => [ lambda {|r| Jdbc::Types::DECIMAL == r['data_type'].to_i}, lambda {|r| r['type_name'] =~ /^decimal$/i}, lambda {|r| r['type_name'] =~ /^numeric$/i}, lambda {|r| r['type_name'] =~ /^number$/i}, lambda {|r| r['type_name'] =~ /^real$/i}, lambda {|r| r['precision'] == '38'}, lambda {|r| r['data_type'] == '2'}], :float => [ lambda {|r| [Jdbc::Types::FLOAT,Jdbc::Types::DOUBLE, Jdbc::Types::REAL].include?(r['data_type'].to_i)}, lambda {|r| r['data_type'].to_i == Jdbc::Types::REAL}, #Prefer REAL to DOUBLE for Postgresql lambda {|r| r['type_name'] =~ /^float/i}, lambda {|r| r['type_name'] =~ /^double$/i}, lambda {|r| r['type_name'] =~ /^real$/i}, lambda {|r| r['precision'] == '15'}], :datetime => [ lambda {|r| Jdbc::Types::TIMESTAMP == r['data_type'].to_i}, lambda {|r| r['type_name'] =~ /^datetime$/i}, lambda {|r| r['type_name'] =~ /^timestamp$/i}, lambda {|r| r['type_name'] =~ /^date/i}, lambda {|r| r['type_name'] =~ /^integer/i}], #Num of milliseconds for SQLite3 JDBC Driver :timestamp => [ lambda {|r| Jdbc::Types::TIMESTAMP == r['data_type'].to_i}, lambda {|r| r['type_name'] =~ /^timestamp$/i}, lambda {|r| r['type_name'] =~ /^datetime/i}, lambda {|r| r['type_name'] =~ /^date/i}, lambda {|r| r['type_name'] =~ /^integer/i}], #Num of milliseconds for SQLite3 JDBC Driver :time => [ lambda {|r| Jdbc::Types::TIME == r['data_type'].to_i}, lambda {|r| r['type_name'] =~ /^time$/i}, lambda {|r| r['type_name'] =~ /^datetime/i}, # For Informix lambda {|r| r['type_name'] =~ /^date/i}, lambda {|r| r['type_name'] =~ /^integer/i}], #Num of milliseconds for SQLite3 JDBC Driver :date => [ lambda {|r| Jdbc::Types::DATE == r['data_type'].to_i}, lambda {|r| r['type_name'] =~ /^date$/i}, lambda {|r| r['type_name'] =~ /^date/i}, lambda {|r| r['type_name'] =~ /^integer/i}], #Num of milliseconds for SQLite3 JDBC Driver3 :binary => [ lambda {|r| [Jdbc::Types::LONGVARBINARY,Jdbc::Types::BINARY,Jdbc::Types::BLOB].include?(r['data_type'].to_i)}, lambda {|r| r['type_name'] =~ /^blob/i}, lambda {|r| r['type_name'] =~ /sub_type 0$/i}, # For FireBird lambda {|r| r['type_name'] =~ /^varbinary$/i}, # We want this sucker for Mimer lambda {|r| r['type_name'] =~ /^binary$/i}, ], :boolean => [ lambda {|r| [Jdbc::Types::TINYINT].include?(r['data_type'].to_i)}, lambda {|r| r['type_name'] =~ /^bool/i}, lambda {|r| r['data_type'] == '-7'}, lambda {|r| r['type_name'] =~ /^tinyint$/i}, lambda {|r| r['type_name'] =~ /^decimal$/i}, lambda {|r| r['type_name'] =~ /^integer$/i}] } def initialize(types) @types = types @types.each {|t| t['type_name'] ||= t['local_type_name']} # Sybase driver seems to want 'local_type_name' end def choose_best_types type_map = {} @types.each do |row| name = row['type_name'].downcase k = name.to_sym type_map[k] = { :name => name } type_map[k][:limit] = row['precision'].to_i if row['precision'] end AR_TO_JDBC_TYPES.keys.each do |k| typerow = choose_type(k) type_map[k] = { :name => typerow['type_name'].downcase } case k when :integer, :string, :decimal type_map[k][:limit] = typerow['precision'] && typerow['precision'].to_i when :boolean type_map[k][:limit] = 1 end end type_map end def choose_type(ar_type) procs = AR_TO_JDBC_TYPES[ar_type] types = @types procs.each do |p| new_types = types.reject {|r| r["data_type"].to_i == Jdbc::Types::OTHER} new_types = new_types.select(&p) new_types = new_types.inject([]) do |typs,t| typs << t unless typs.detect {|el| el['type_name'] == t['type_name']} typs end return new_types.first if new_types.length == 1 types = new_types if new_types.length > 0 end raise "unable to choose type for #{ar_type} from:\n#{types.collect{|t| t['type_name']}.inspect}" end end class JdbcDriver def initialize(name) @name = name end def driver_class @driver_class ||= begin driver_class_const = (@name[0...1].capitalize + @name[1..@name.length]).gsub(/\./, '_') Jdbc::Mutex.synchronized do unless Jdbc.const_defined?(driver_class_const) driver_class_name = @name Jdbc.module_eval do include_class(driver_class_name) { driver_class_const } end end end driver_class = Jdbc.const_get(driver_class_const) raise "You specify a driver for your JDBC connection" unless driver_class driver_class end end def load Jdbc::DriverManager.registerDriver(create) end def connection(url, user, pass) Jdbc::DriverManager.getConnection(url, user, pass) rescue # bypass DriverManager to get around problem with dynamically loaded jdbc drivers props = java.util.Properties.new props.setProperty("user", user) props.setProperty("password", pass) create.connect(url, props) end def create driver_class.new end end class JdbcColumn < Column attr_writer :limit, :precision COLUMN_TYPES = ::JdbcSpec.constants.map{|c| ::JdbcSpec.const_get c }.select{ |c| c.respond_to? :column_selector }.map{|c| c.column_selector }.inject({}) { |h,val| h[val[0]] = val[1]; h } def initialize(config, name, default, *args) dialect = config[:dialect] || config[:driver] for reg, func in COLUMN_TYPES if reg === dialect.to_s func.call(config,self) end end super(name,default_value(default),*args) init_column(name, default, *args) end def init_column(*args) end def default_value(val) val end end include_class "jdbc_adapter.JdbcConnectionFactory" class JdbcConnection attr_reader :adapter, :connection_factory # @native_database_types - setup properly by adapter= versus set_native_database_types. # This contains type information for the adapter. Individual adapters can make tweaks # by defined modify_types # # @native_types - This is the default type settings sans any modifications by the # individual adapter. My guess is that if we loaded two adapters of different types # then this is used as a base to be tweaked by each adapter to create @native_database_types def initialize(config) @config = config.symbolize_keys! @config[:retry_count] ||= 5 @config[:connection_alive_sql] ||= "select 1" if @config[:jndi] begin configure_jndi rescue => e warn "JNDI data source unavailable: #{e.message}; trying straight JDBC" configure_jdbc end else configure_jdbc end connection # force the connection to load set_native_database_types @stmts = {} rescue Exception => e raise "The driver encountered an error: #{e}" end def adapter=(adapter) @adapter = adapter @native_database_types = dup_native_types @adapter.modify_types(@native_database_types) end # Duplicate all native types into new hash structure so it can be modified # without destroying original structure. def dup_native_types types = {} @native_types.each_pair do |k, v| types[k] = v.inject({}) do |memo, kv| memo[kv.first] = begin kv.last.dup rescue kv.last end memo end end types end private :dup_native_types def jndi_connection? @jndi_connection end private def configure_jndi jndi = @config[:jndi].to_s ctx = javax.naming.InitialContext.new ds = ctx.lookup(jndi) @connection_factory = JdbcConnectionFactory.impl do ds.connection end unless @config[:driver] @config[:driver] = connection.meta_data.connection.java_class.name end @jndi_connection = true end def configure_jdbc driver = @config[:driver].to_s user = @config[:username].to_s pass = @config[:password].to_s url = @config[:url].to_s unless driver && url raise ::ActiveRecord::ConnectionFailed, "jdbc adapter requires driver class and url" end jdbc_driver = JdbcDriver.new(driver) jdbc_driver.load @connection_factory = JdbcConnectionFactory.impl do jdbc_driver.connection(url, user, pass) end end end class JdbcAdapter < AbstractAdapter module ShadowCoreMethods def alias_chained_method(meth, feature, target) if instance_methods.include?("#{meth}_without_#{feature}") alias_method "#{meth}_without_#{feature}".to_sym, target else alias_method meth, target if meth != target end end end module CompatibilityMethods def self.needed?(base) !base.instance_methods.include?("quote_table_name") end def quote_table_name(name) quote_column_name(name) end end module ConnectionPoolCallbacks def self.included(base) if base.respond_to?(:set_callback) # Rails 3 callbacks base.set_callback :checkin, :after, :on_checkin base.set_callback :checkout, :before, :on_checkout else base.checkin :on_checkin base.checkout :on_checkout end end def self.needed? ActiveRecord::Base.respond_to?(:connection_pool) end def on_checkin # default implementation does nothing end def on_checkout # default implementation does nothing end end module JndiConnectionPoolCallbacks def self.prepare(adapter, conn) if ActiveRecord::Base.respond_to?(:connection_pool) && conn.jndi_connection? adapter.extend self conn.disconnect! # disconnect initial connection in JdbcConnection#initialize end end def on_checkin disconnect! end def on_checkout reconnect! end end extend ShadowCoreMethods include CompatibilityMethods if CompatibilityMethods.needed?(self) include ConnectionPoolCallbacks if ConnectionPoolCallbacks.needed? attr_reader :config def initialize(connection, logger, config) @config = config spec = adapter_spec config unless connection connection_class = jdbc_connection_class spec connection = connection_class.new config end super(connection, logger) extend spec if spec connection.adapter = self JndiConnectionPoolCallbacks.prepare(self, connection) end def jdbc_connection_class(spec) connection_class = spec.jdbc_connection_class if spec && spec.respond_to?(:jdbc_connection_class) connection_class = ::ActiveRecord::ConnectionAdapters::JdbcConnection unless connection_class connection_class end # Locate specialized adapter specification if one exists based on config data def adapter_spec(config) dialect = (config[:dialect] || config[:driver]).to_s ::JdbcSpec.constants.map { |name| ::JdbcSpec.const_get name }.each do |constant| if constant.respond_to? :adapter_matcher spec = constant.adapter_matcher(dialect, config) return spec if spec end end nil end def modify_types(tp) tp end def adapter_name #:nodoc: 'JDBC' end def supports_migrations? true end def native_database_types #:nodoc: @connection.native_database_types end def database_name #:nodoc: @connection.database_name end def native_sql_to_type(tp) if /^(.*?)\(([0-9]+)\)/ =~ tp tname = $1 limit = $2.to_i ntype = native_database_types if ntype[:primary_key] == tp return :primary_key,nil else ntype.each do |name,val| if name == :primary_key next end if val[:name].downcase == tname.downcase && (val[:limit].nil? || val[:limit].to_i == limit) return name,limit end end end elsif /^(.*?)/ =~ tp tname = $1 ntype = native_database_types if ntype[:primary_key] == tp return :primary_key,nil else ntype.each do |name,val| if val[:name].downcase == tname.downcase && val[:limit].nil? return name,nil end end end else return :string,255 end return nil,nil end def reconnect! @connection.reconnect! @connection end def disconnect! @connection.disconnect! end def jdbc_select_all(sql, name = nil) select(sql, name) end alias_chained_method :select_all, :query_cache, :jdbc_select_all def select_rows(sql, name = nil) rows = [] select(sql, name).each {|row| rows << row.values } rows end def select_one(sql, name = nil) select(sql, name).first end def execute(sql, name = nil) log(sql, name) do _execute(sql,name) end end # we need to do it this way, to allow Rails stupid tests to always work # even if we define a new execute method. Instead of mixing in a new # execute, an _execute should be mixed in. def _execute(sql, name = nil) if JdbcConnection::select?(sql) @connection.execute_query(sql) elsif JdbcConnection::insert?(sql) @connection.execute_insert(sql) else @connection.execute_update(sql) end end def jdbc_update(sql, name = nil) #:nodoc: execute(sql, name) end alias_chained_method :update, :query_dirty, :jdbc_update def jdbc_insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) id = execute(sql, name = nil) id_value || id end alias_chained_method :insert, :query_dirty, :jdbc_insert def jdbc_columns(table_name, name = nil) @connection.columns(table_name.to_s) end alias_chained_method :columns, :query_cache, :jdbc_columns def tables @connection.tables end def indexes(table_name, name = nil, schema_name = nil) @connection.indexes(table_name, name, schema_name) end def begin_db_transaction @connection.begin end def commit_db_transaction @connection.commit end def rollback_db_transaction @connection.rollback end def write_large_object(*args) @connection.write_large_object(*args) end def pk_and_sequence_for(table) key = primary_key(table) [key, nil] if key end def primary_key(table) primary_keys(table).first end def primary_keys(table) @connection.primary_keys(table) end private def select(sql, name=nil) log(sql, name) do @connection.execute_query(sql) end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/mssql_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/mssql_adapter.rb
tried_gem = false begin require "jdbc/jtds" rescue LoadError unless tried_gem require 'rubygems' gem "jdbc-mssql" tried_gem = true retry end # trust that the jtds jar is already present end require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/cachedb_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/cachedb_adapter.rb
require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/informix_adapter.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/informix_adapter.rb
require 'active_record/connection_adapters/jdbc_adapter'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/jdbc_adapter_spec.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/lib/active_record/connection_adapters/jdbc_adapter_spec.rb
module JdbcSpec module ActiveRecordExtensions def self.add_method_to_remove_from_ar_base(meth) @methods ||= [] @methods << meth end def self.extended(klass) (@methods || []).each {|m| (class << klass; self; end).instance_eval { remove_method(m) rescue nil } } end end end require 'jdbc_adapter/jdbc_mimer' require 'jdbc_adapter/jdbc_hsqldb' require 'jdbc_adapter/jdbc_oracle' require 'jdbc_adapter/jdbc_postgre' require 'jdbc_adapter/jdbc_mysql' require 'jdbc_adapter/jdbc_derby' require 'jdbc_adapter/jdbc_firebird' require 'jdbc_adapter/jdbc_db2' require 'jdbc_adapter/jdbc_mssql' require 'jdbc_adapter/jdbc_cachedb' require 'jdbc_adapter/jdbc_sqlite3' require 'jdbc_adapter/jdbc_sybase' require 'jdbc_adapter/jdbc_informix'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/rails_generators/jdbc_generator.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/rails_generators/jdbc_generator.rb
class JdbcGenerator < Rails::Generator::Base def manifest record do |m| m.directory 'config/initializers' m.template 'config/initializers/jdbc.rb', File.join('config', 'initializers', 'jdbc.rb') m.directory 'lib/tasks' m.template 'lib/tasks/jdbc.rake', File.join('lib', 'tasks', 'jdbc.rake') end end protected def banner "Usage: #{$0} jdbc\nGenerate JDBC bootstrapping files for your Rails application." end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/rails_generators/templates/config/initializers/jdbc.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/rails_generators/templates/config/initializers/jdbc.rb
# This file was generated by the "jdbc" generator, which is provided # by the activerecord-jdbc-adapter gem. # # This file allows the JDBC drivers to be hooked into ActiveRecord # such that you don't have to change anything else in your Rails # application. require 'jdbc_adapter' if defined?(JRUBY_VERSION)
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/install.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/install.rb
require 'rbconfig' require 'find' require 'ftools' include Config $ruby = CONFIG['ruby_install_name'] ## # Install a binary file. We patch in on the way through to # insert a #! line. If this is a Unix install, we name # the command (for example) 'rake' and let the shebang line # handle running it. Under windows, we add a '.rb' extension # and let file associations to their stuff # def installBIN(from, opfile) tmp_dir = nil for t in [".", "/tmp", "c:/temp", $bindir] stat = File.stat(t) rescue next if stat.directory? and stat.writable? tmp_dir = t break end end fail "Cannot find a temporary directory" unless tmp_dir tmp_file = File.join(tmp_dir, "_tmp") File.open(from) do |ip| File.open(tmp_file, "w") do |op| ruby = File.join($realbindir, $ruby) op.puts "#!#{ruby} -w" op.write ip.read end end opfile += ".rb" if CONFIG["target_os"] =~ /mswin/i File::install(tmp_file, File.join($bindir, opfile), 0755, true) File::unlink(tmp_file) end $sitedir = CONFIG["sitelibdir"] unless $sitedir version = CONFIG["MAJOR"]+"."+CONFIG["MINOR"] $libdir = File.join(CONFIG["libdir"], "ruby", version) $sitedir = $:.find {|x| x =~ /site_ruby/} if !$sitedir $sitedir = File.join($libdir, "site_ruby") elsif $sitedir !~ Regexp.quote(version) $sitedir = File.join($sitedir, version) end end $bindir = CONFIG["bindir"] $realbindir = $bindir bindir = CONFIG["bindir"] if (destdir = ENV['DESTDIR']) $bindir = destdir + $bindir $sitedir = destdir + $sitedir File::makedirs($bindir) File::makedirs($sitedir) end rake_dest = File.join($sitedir, "rake") File::makedirs(rake_dest, true) File::chmod(0755, rake_dest) # The library files files = Dir.chdir('lib') { Dir['**/*.rb'] } for fn in files fn_dir = File.dirname(fn) target_dir = File.join($sitedir, fn_dir) if ! File.exist?(target_dir) File.makedirs(target_dir) end File::install(File.join('lib', fn), File.join($sitedir, fn), 0644, true) end # and the executable installBIN("bin/rake", "rake")
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_application.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_application.rb
#!/usr/bin/env ruby begin require 'rubygems' rescue LoadError # got no gems end require 'test/unit' require 'rake' require 'test/rake_test_setup' require 'test/capture_stdout' require 'test/in_environment' TESTING_REQUIRE = [ ] ###################################################################### class TestApplication < Test::Unit::TestCase include CaptureStdout include InEnvironment include TestMethods def setup @app = Rake::Application.new @app.options.rakelib = [] end def test_constant_warning err = capture_stderr do @app.instance_eval { const_warning("Task") } end assert_match(/warning/i, err) assert_match(/deprecated/i, err) assert_match(/Task/i, err) end def test_display_tasks @app.options.show_task_pattern = // @app.last_description = "COMMENT" @app.define_task(Rake::Task, "t") out = capture_stdout do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# COMMENT/, out) end def test_display_tasks_with_long_comments in_environment('RAKE_COLUMNS' => '80') do @app.options.show_task_pattern = // @app.last_description = "1234567890" * 8 @app.define_task(Rake::Task, "t") out = capture_stdout do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# 12345678901234567890123456789012345678901234567890123456789012345\.\.\./, out) end end def test_display_tasks_with_task_name_wider_than_tty_display in_environment('RAKE_COLUMNS' => '80') do @app.options.show_task_pattern = // description = "something short" task_name = "task name" * 80 @app.last_description = "something short" @app.define_task(Rake::Task, task_name ) out = capture_stdout do @app.instance_eval { display_tasks_and_comments } end # Ensure the entire task name is output and we end up showing no description assert_match(/rake #{task_name} # .../, out) end end def test_display_tasks_with_very_long_task_name_to_a_non_tty_shows_name_and_comment @app.options.show_task_pattern = // @app.tty_output = false description = "something short" task_name = "task name" * 80 @app.last_description = "something short" @app.define_task(Rake::Task, task_name ) out = capture_stdout do @app.instance_eval { display_tasks_and_comments } end # Ensure the entire task name is output and we end up showing no description assert_match(/rake #{task_name} # #{description}/, out) end def test_display_tasks_with_long_comments_to_a_non_tty_shows_entire_comment @app.options.show_task_pattern = // @app.tty_output = false @app.last_description = "1234567890" * 8 @app.define_task(Rake::Task, "t") out = capture_stdout do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# #{@app.last_description}/, out) end def test_display_tasks_with_long_comments_to_a_non_tty_with_columns_set_truncates_comments in_environment("RAKE_COLUMNS" => '80') do @app.options.show_task_pattern = // @app.tty_output = false @app.last_description = "1234567890" * 8 @app.define_task(Rake::Task, "t") out = capture_stdout do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t/, out) assert_match(/# 12345678901234567890123456789012345678901234567890123456789012345\.\.\./, out) end end def test_display_tasks_with_full_descriptions @app.options.show_task_pattern = // @app.options.full_description = true @app.last_description = "COMMENT" @app.define_task(Rake::Task, "t") out = capture_stdout do @app.instance_eval { display_tasks_and_comments } end assert_match(/^rake t$/, out) assert_match(/^ {4}COMMENT$/, out) end def test_finding_rakefile assert_match(/Rakefile/i, @app.instance_eval { have_rakefile }) end def test_not_finding_rakefile @app.instance_eval { @rakefiles = ['NEVER_FOUND'] } assert( ! @app.instance_eval do have_rakefile end ) assert_nil @app.rakefile end def test_load_rakefile in_environment("PWD" => "test/data/unittest") do @app.instance_eval do handle_options options.silent = true load_rakefile end assert_equal "rakefile", @app.rakefile.downcase assert_match(%r(unittest$), Dir.pwd) end end def test_load_rakefile_from_subdir in_environment("PWD" => "test/data/unittest/subdir") do @app.instance_eval do handle_options options.silent = true load_rakefile end assert_equal "rakefile", @app.rakefile.downcase assert_match(%r(unittest$), Dir.pwd) end end def test_load_rakefile_not_found in_environment("PWD" => "/", "RAKE_SYSTEM" => 'not_exist') do @app.instance_eval do handle_options options.silent = true end ex = assert_exception(RuntimeError) do @app.instance_eval do raw_load_rakefile end end assert_match(/no rakefile found/i, ex.message) end end def test_load_from_system_rakefile in_environment('RAKE_SYSTEM' => 'test/data/sys') do @app.options.rakelib = [] @app.instance_eval do handle_options options.silent = true options.load_system = true options.rakelib = [] load_rakefile end assert_equal "test/data/sys", @app.system_dir assert_nil @app.rakefile end end def test_windows assert ! (@app.windows? && @app.unix?) end def test_loading_imports mock = flexmock("loader") mock.should_receive(:load).with("x.dummy").once @app.instance_eval do add_loader("dummy", mock) add_import("x.dummy") load_imports end end def test_building_imported_files_on_demand mock = flexmock("loader") mock.should_receive(:load).with("x.dummy").once mock.should_receive(:make_dummy).with_no_args.once @app.instance_eval do intern(Rake::Task, "x.dummy").enhance do mock.make_dummy end add_loader("dummy", mock) add_import("x.dummy") load_imports end end def test_handle_options_should_strip_options_from_ARGV assert !@app.options.trace valid_option = '--trace' ARGV.clear ARGV << valid_option @app.handle_options assert !ARGV.include?(valid_option) assert @app.options.trace end def test_good_run ran = false ARGV.clear ARGV << '--rakelib=""' @app.options.silent = true @app.instance_eval do intern(Rake::Task, "default").enhance { ran = true } end in_environment("PWD" => "test/data/default") do @app.run end assert ran end def test_display_task_run ran = false ARGV.clear ARGV << '-f' << '-s' << '--tasks' << '--rakelib=""' @app.last_description = "COMMENT" @app.define_task(Rake::Task, "default") out = capture_stdout { @app.run } assert @app.options.show_tasks assert ! ran assert_match(/rake default/, out) assert_match(/# COMMENT/, out) end def test_display_prereqs ran = false ARGV.clear ARGV << '-f' << '-s' << '--prereqs' << '--rakelib=""' @app.last_description = "COMMENT" t = @app.define_task(Rake::Task, "default") t.enhance([:a, :b]) @app.define_task(Rake::Task, "a") @app.define_task(Rake::Task, "b") out = capture_stdout { @app.run } assert @app.options.show_prereqs assert ! ran assert_match(/rake a$/, out) assert_match(/rake b$/, out) assert_match(/rake default\n( *(a|b)\n){2}/m, out) end def test_bad_run @app.intern(Rake::Task, "default").enhance { fail } ARGV.clear ARGV << '-f' << '-s' << '--rakelib=""' assert_exception(SystemExit) { err = capture_stderr { @app.run } assert_match(/see full trace/, err) } ensure ARGV.clear end def test_bad_run_with_trace @app.intern(Rake::Task, "default").enhance { fail } ARGV.clear ARGV << '-f' << '-s' << '-t' assert_exception(SystemExit) { err = capture_stderr { capture_stdout { @app.run } } assert_no_match(/see full trace/, err) } ensure ARGV.clear end def test_run_with_bad_options @app.intern(Rake::Task, "default").enhance { fail } ARGV.clear ARGV << '-f' << '-s' << '--xyzzy' assert_exception(SystemExit) { err = capture_stderr { capture_stdout { @app.run } } } ensure ARGV.clear end end ###################################################################### class TestApplicationOptions < Test::Unit::TestCase include CaptureStdout include TestMethods def setup clear_argv RakeFileUtils.verbose_flag = false RakeFileUtils.nowrite_flag = false TESTING_REQUIRE.clear end def teardown clear_argv RakeFileUtils.verbose_flag = false RakeFileUtils.nowrite_flag = false end def clear_argv while ! ARGV.empty? ARGV.pop end end def test_default_options opts = command_line assert_nil opts.classic_namespace assert_nil opts.dryrun assert_nil opts.full_description assert_nil opts.ignore_system assert_nil opts.load_system assert_nil opts.nosearch assert_equal ['rakelib'], opts.rakelib assert_nil opts.show_prereqs assert_nil opts.show_task_pattern assert_nil opts.show_tasks assert_nil opts.silent assert_nil opts.trace assert_equal ['rakelib'], opts.rakelib assert ! RakeFileUtils.verbose_flag assert ! RakeFileUtils.nowrite_flag end def test_dry_run flags('--dry-run', '-n') do |opts| assert opts.dryrun assert opts.trace assert RakeFileUtils.verbose_flag assert RakeFileUtils.nowrite_flag end end def test_describe flags('--describe') do |opts| assert opts.full_description assert opts.show_tasks assert_equal(//.to_s, opts.show_task_pattern.to_s) end end def test_describe_with_pattern flags('--describe=X') do |opts| assert opts.full_description assert opts.show_tasks assert_equal(/X/.to_s, opts.show_task_pattern.to_s) end end def test_execute $xyzzy = 0 flags('--execute=$xyzzy=1', '-e $xyzzy=1') do |opts| assert_equal 1, $xyzzy assert_equal :exit, @exit $xyzzy = 0 end end def test_execute_and_continue $xyzzy = 0 flags('--execute-continue=$xyzzy=1', '-E $xyzzy=1') do |opts| assert_equal 1, $xyzzy assert_not_equal :exit, @exit $xyzzy = 0 end end def test_execute_and_print $xyzzy = 0 flags('--execute-print=$xyzzy="pugh"', '-p $xyzzy="pugh"') do |opts| assert_equal 'pugh', $xyzzy assert_equal :exit, @exit assert_match(/^pugh$/, @out) $xyzzy = 0 end end def test_help flags('--help', '-H', '-h') do |opts| assert_match(/\Arake/, @out) assert_match(/\boptions\b/, @out) assert_match(/\btargets\b/, @out) assert_equal :exit, @exit assert_equal :exit, @exit end end def test_libdir flags(['--libdir', 'xx'], ['-I', 'xx'], ['-Ixx']) do |opts| $:.include?('xx') end ensure $:.delete('xx') end def test_rakefile flags(['--rakefile', 'RF'], ['--rakefile=RF'], ['-f', 'RF'], ['-fRF']) do |opts| assert_equal ['RF'], @app.instance_eval { @rakefiles } end end def test_rakelib flags(['--rakelibdir', 'A:B:C'], ['--rakelibdir=A:B:C'], ['-R', 'A:B:C'], ['-RA:B:C']) do |opts| assert_equal ['A', 'B', 'C'], opts.rakelib end end def test_require flags(['--require', 'test/reqfile'], '-rtest/reqfile2', '-rtest/reqfile3') do |opts| end assert TESTING_REQUIRE.include?(1) assert TESTING_REQUIRE.include?(2) assert TESTING_REQUIRE.include?(3) assert_equal 3, TESTING_REQUIRE.size end def test_missing_require ex = assert_exception(LoadError) do flags(['--require', 'test/missing']) do |opts| end end assert_match(/no such file/, ex.message) assert_match(/test\/missing/, ex.message) end def test_prereqs flags('--prereqs', '-P') do |opts| assert opts.show_prereqs end end def test_quiet flags('--quiet', '-q') do |opts| assert ! RakeFileUtils.verbose_flag assert ! opts.silent end end def test_no_search flags('--nosearch', '--no-search', '-N') do |opts| assert opts.nosearch end end def test_silent flags('--silent', '-s') do |opts| assert ! RakeFileUtils.verbose_flag assert opts.silent end end def test_system flags('--system', '-g') do |opts| assert opts.load_system end end def test_no_system flags('--no-system', '-G') do |opts| assert opts.ignore_system end end def test_trace flags('--trace', '-t') do |opts| assert opts.trace assert RakeFileUtils.verbose_flag assert ! RakeFileUtils.nowrite_flag end end def test_trace_rules flags('--rules') do |opts| assert opts.trace_rules end end def test_tasks flags('--tasks', '-T') do |opts| assert opts.show_tasks assert_equal(//.to_s, opts.show_task_pattern.to_s) end flags(['--tasks', 'xyz'], ['-Txyz']) do |opts| assert opts.show_tasks assert_equal(/xyz/, opts.show_task_pattern) end end def test_verbose flags('--verbose', '-V') do |opts| assert RakeFileUtils.verbose_flag assert ! opts.silent end end def test_version flags('--version', '-V') do |opts| assert_match(/\bversion\b/, @out) assert_match(/\b#{RAKEVERSION}\b/, @out) assert_equal :exit, @exit end end def test_classic_namespace flags(['--classic-namespace'], ['-C', '-T', '-P', '-n', '-s', '-t']) do |opts| assert opts.classic_namespace assert_equal opts.show_tasks, $show_tasks assert_equal opts.show_prereqs, $show_prereqs assert_equal opts.trace, $trace assert_equal opts.dryrun, $dryrun assert_equal opts.silent, $silent end end def test_bad_option capture_stderr do ex = assert_exception(OptionParser::InvalidOption) do flags('--bad-option') end if ex.message =~ /^While/ # Ruby 1.9 error message assert_match(/while parsing/i, ex.message) else # Ruby 1.8 error message assert_match(/(invalid|unrecognized) option/i, ex.message) assert_match(/--bad-option/, ex.message) end end end def test_task_collection command_line("a", "b") assert_equal ["a", "b"], @tasks.sort end def test_default_task_collection command_line() assert_equal ["default"], @tasks end def test_environment_definition ENV.delete('TESTKEY') command_line("a", "TESTKEY=12") assert_equal ["a"], @tasks.sort assert '12', ENV['TESTKEY'] end private def flags(*sets) sets.each do |set| ARGV.clear @out = capture_stdout { @exit = catch(:system_exit) { opts = command_line(*set) } } yield(@app.options) if block_given? end end def command_line(*options) options.each do |opt| ARGV << opt end @app = Rake::Application.new def @app.exit(*args) throw :system_exit, :exit end @app.instance_eval do handle_options collect_tasks end @tasks = @app.top_level_tasks @app.options end end class TestTaskArgumentParsing < Test::Unit::TestCase def setup @app = Rake::Application.new end def test_name_only name, args = @app.parse_task_string("name") assert_equal "name", name assert_equal [], args end def test_empty_args name, args = @app.parse_task_string("name[]") assert_equal "name", name assert_equal [], args end def test_one_argument name, args = @app.parse_task_string("name[one]") assert_equal "name", name assert_equal ["one"], args end def test_two_arguments name, args = @app.parse_task_string("name[one,two]") assert_equal "name", name assert_equal ["one", "two"], args end def test_can_handle_spaces_between_args name, args = @app.parse_task_string("name[one, two,\tthree , \tfour]") assert_equal "name", name assert_equal ["one", "two", "three", "four"], args end def test_keeps_embedded_spaces name, args = @app.parse_task_string("name[a one ana, two]") assert_equal "name", name assert_equal ["a one ana", "two"], args end end class TestTaskArgumentParsing < Test::Unit::TestCase include InEnvironment def test_terminal_width_using_env app = Rake::Application.new in_environment('RAKE_COLUMNS' => '1234') do assert_equal 1234, app.terminal_width end end def test_terminal_width_using_stty app = Rake::Application.new flexmock(app, :unix? => true, :dynamic_width_stty => 1235, :dynamic_width_tput => 0) in_environment('RAKE_COLUMNS' => nil) do assert_equal 1235, app.terminal_width end end def test_terminal_width_using_tput app = Rake::Application.new flexmock(app, :unix? => true, :dynamic_width_stty => 0, :dynamic_width_tput => 1236) in_environment('RAKE_COLUMNS' => nil) do assert_equal 1236, app.terminal_width end end def test_terminal_width_using_hardcoded_80 app = Rake::Application.new flexmock(app, :unix? => false) in_environment('RAKE_COLUMNS' => nil) do assert_equal 80, app.terminal_width end end def test_terminal_width_with_failure app = Rake::Application.new flexmock(app).should_receive(:unix?).and_throw(RuntimeError) in_environment('RAKE_COLUMNS' => nil) do assert_equal 80, app.terminal_width end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_invocation_chain.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_invocation_chain.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' require 'test/rake_test_setup' ###################################################################### class TestAnEmptyInvocationChain < Test::Unit::TestCase include TestMethods def setup @empty = Rake::InvocationChain::EMPTY end def test_should_be_able_to_add_members assert_nothing_raised do @empty.append("A") end end def test_to_s assert_equal "TOP", @empty.to_s end end ###################################################################### class TestAnInvocationChainWithOneMember < Test::Unit::TestCase include TestMethods def setup @empty = Rake::InvocationChain::EMPTY @first_member = "A" @chain = @empty.append(@first_member) end def test_should_report_first_member_as_a_member assert @chain.member?(@first_member) end def test_should_fail_when_adding_original_member ex = assert_exception RuntimeError do @chain.append(@first_member) end assert_match(/circular +dependency/i, ex.message) assert_match(/A.*=>.*A/, ex.message) end def test_to_s assert_equal "TOP => A", @chain.to_s end end ###################################################################### class TestAnInvocationChainWithMultipleMember < Test::Unit::TestCase include TestMethods def setup @first_member = "A" @second_member = "B" ch = Rake::InvocationChain::EMPTY.append(@first_member) @chain = ch.append(@second_member) end def test_should_report_first_member_as_a_member assert @chain.member?(@first_member) end def test_should_report_second_member_as_a_member assert @chain.member?(@second_member) end def test_should_fail_when_adding_original_member ex = assert_exception RuntimeError do @chain.append(@first_member) end assert_match(/A.*=>.*B.*=>.*A/, ex.message) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_win32.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_win32.rb
#!/usr/bin/env ruby require 'test/unit' require 'test/rake_test_setup' require 'test/in_environment' require 'rake' class TestWin32 < Test::Unit::TestCase include InEnvironment include TestMethods Win32 = Rake::Win32 def test_win32_system_dir_uses_home_if_defined in_environment('RAKE_SYSTEM' => nil, 'HOME' => 'C:\\HP') do assert_equal "C:/HP/Rake", Win32.win32_system_dir end end def test_win32_system_dir_uses_homedrive_homepath_when_no_home_defined in_environment( 'RAKE_SYSTEM' => nil, 'HOME' => nil, 'HOMEDRIVE' => "C:", 'HOMEPATH' => "\\HP" ) do assert_equal "C:/HP/Rake", Win32.win32_system_dir end end def test_win32_system_dir_uses_appdata_when_no_home_or_home_combo in_environment( 'RAKE_SYSTEM' => nil, 'HOME' => nil, 'HOMEDRIVE' => nil, 'HOMEPATH' => nil, 'APPDATA' => "C:\\Documents and Settings\\HP\\Application Data" ) do assert_equal "C:/Documents and Settings/HP/Application Data/Rake", Win32.win32_system_dir end end def test_win32_system_dir_fallback_to_userprofile_otherwise in_environment( 'RAKE_SYSTEM' => nil, 'HOME' => nil, 'HOMEDRIVE' => nil, 'HOMEPATH' => nil, 'APPDATA' => nil, 'USERPROFILE' => "C:\\Documents and Settings\\HP" ) do assert_equal "C:/Documents and Settings/HP/Rake", Win32.win32_system_dir end end def test_win32_system_dir_nil_of_no_env_vars in_environment( 'RAKE_SYSTEM' => nil, 'HOME' => nil, 'HOMEDRIVE' => nil, "HOMEPATH" => nil, 'APPDATA' => nil, "USERPROFILE" => nil ) do assert_exception(Rake::Win32::Win32HomeError) do Win32.win32_system_dir end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_task_manager.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_task_manager.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' require 'test/rake_test_setup' class TaskManager include Rake::TaskManager end class TestTaskManager < Test::Unit::TestCase include TestMethods def setup @tm = TaskManager.new end def test_create_task_manager assert_not_nil @tm assert_equal [], @tm.tasks end def test_define_task t = @tm.define_task(Rake::Task, :t) assert_equal "t", t.name assert_equal @tm, t.application end def test_name_lookup t = @tm.define_task(Rake::Task, :t) assert_equal t, @tm[:t] end def test_namespace_task_create @tm.in_namespace("x") do t = @tm.define_task(Rake::Task, :t) assert_equal "x:t", t.name end assert_equal ["x:t"], @tm.tasks.collect { |t| t.name } end def test_anonymous_namespace anon_ns = @tm.in_namespace(nil) do t = @tm.define_task(Rake::Task, :t) assert_equal "_anon_1:t", t.name end task = anon_ns[:t] assert_equal "_anon_1:t", task.name end def test_create_filetask_in_namespace @tm.in_namespace("x") do t = @tm.define_task(Rake::FileTask, "fn") assert_equal "fn", t.name end assert_equal ["fn"], @tm.tasks.collect { |t| t.name } end def test_namespace_yields_same_namespace_as_returned yielded_namespace = nil returned_namespace = @tm.in_namespace("x") do |ns| yielded_namespace = ns end assert_equal returned_namespace, yielded_namespace end def test_name_lookup_with_implicit_file_tasks t = @tm["README"] assert_equal "README", t.name assert Rake::FileTask === t end def test_name_lookup_with_nonexistent_task assert_exception(RuntimeError) { t = @tm["DOES NOT EXIST"] } end def test_name_lookup_in_multiple_scopes aa = nil bb = nil xx = @tm.define_task(Rake::Task, :xx) top_z = @tm.define_task(Rake::Task, :z) @tm.in_namespace("a") do aa = @tm.define_task(Rake::Task, :aa) mid_z = @tm.define_task(Rake::Task, :z) @tm.in_namespace("b") do bb = @tm.define_task(Rake::Task, :bb) bot_z = @tm.define_task(Rake::Task, :z) assert_equal ["a", "b"], @tm.current_scope assert_equal bb, @tm["a:b:bb"] assert_equal aa, @tm["a:aa"] assert_equal xx, @tm["xx"] assert_equal bot_z, @tm["z"] assert_equal mid_z, @tm["^z"] assert_equal top_z, @tm["^^z"] assert_equal top_z, @tm["rake:z"] end assert_equal ["a"], @tm.current_scope assert_equal bb, @tm["a:b:bb"] assert_equal aa, @tm["a:aa"] assert_equal xx, @tm["xx"] assert_equal bb, @tm["b:bb"] assert_equal aa, @tm["aa"] assert_equal mid_z, @tm["z"] assert_equal top_z, @tm["^z"] assert_equal top_z, @tm["rake:z"] end assert_equal [], @tm.current_scope assert_equal [], xx.scope assert_equal ['a'], aa.scope assert_equal ['a', 'b'], bb.scope end def test_lookup_with_explicit_scopes t1, t2, t3, s = (0...4).collect { nil } t1 = @tm.define_task(Rake::Task, :t) @tm.in_namespace("a") do t2 = @tm.define_task(Rake::Task, :t) s = @tm.define_task(Rake::Task, :s) @tm.in_namespace("b") do t3 = @tm.define_task(Rake::Task, :t) end end assert_equal t1, @tm[:t, []] assert_equal t2, @tm[:t, ["a"]] assert_equal t3, @tm[:t, ["a", "b"]] assert_equal s, @tm[:s, ["a", "b"]] assert_equal s, @tm[:s, ["a"]] end def test_correctly_scoped_prerequisites_are_invoked values = [] @tm = Rake::Application.new @tm.define_task(Rake::Task, :z) do values << "top z" end @tm.in_namespace("a") do @tm.define_task(Rake::Task, :z) do values << "next z" end @tm.define_task(Rake::Task, :x => :z) end @tm["a:x"].invoke assert_equal ["next z"], values end end class TestTaskManagerArgumentResolution < Test::Unit::TestCase def test_good_arg_patterns assert_equal [:t, [], []], task(:t) assert_equal [:t, [], [:x]], task(:t => :x) assert_equal [:t, [], [:x, :y]], task(:t => [:x, :y]) assert_equal [:t, [:a, :b], []], task(:t, :a, :b) assert_equal [:t, [], [:x]], task(:t, :needs => :x) assert_equal [:t, [:a, :b], [:x]], task(:t, :a, :b, :needs => :x) assert_equal [:t, [:a, :b], [:x, :y]], task(:t, :a, :b, :needs => [:x, :y]) assert_equal [:t, [:a, :b], []], task(:t, [:a, :b]) assert_equal [:t, [:a, :b], [:x]], task(:t, [:a, :b] => :x) assert_equal [:t, [:a, :b], [:x, :y]], task(:t, [:a, :b] => [:x, :y]) end def task(*args) tm = TaskManager.new tm.resolve_args(args) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/in_environment.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/in_environment.rb
module InEnvironment private # Create an environment for a test. At the completion of the yielded # block, the environment is restored to its original conditions. def in_environment(settings) original_settings = set_env(settings) yield ensure set_env(original_settings) end # Set the environment according to the settings hash. def set_env(settings) # :nodoc: result = {} settings.each do |k, v| result[k] = ENV[k] if k == 'PWD' result[k] = Dir.pwd Dir.chdir(v) elsif v.nil? ENV.delete(k) else ENV[k] = v end end result end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_namespace.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_namespace.rb
#!/usr/bin/env ruby begin require 'rubygems' rescue LoadError # got no gems end require 'test/unit' require 'flexmock/test_unit' require 'rake' require 'test/rake_test_setup' class TestNameSpace < Test::Unit::TestCase include TestMethods class TM include Rake::TaskManager end def test_namespace_creation mgr = TM.new ns = Rake::NameSpace.new(mgr, []) assert_not_nil ns end def test_namespace_lookup mgr = TM.new ns = mgr.in_namespace("n") do mgr.define_task(Rake::Task, "t") end assert_not_nil ns["t"] assert_equal mgr["n:t"], ns["t"] end def test_namespace_reports_tasks_it_owns mgr = TM.new nns = nil ns = mgr.in_namespace("n") do mgr.define_task(Rake::Task, :x) mgr.define_task(Rake::Task, :y) nns = mgr.in_namespace("nn") do mgr.define_task(Rake::Task, :z) end end mgr.in_namespace("m") do mgr.define_task(Rake::Task, :x) end assert_equal ["n:nn:z", "n:x", "n:y"], ns.tasks.map { |tsk| tsk.name } assert_equal ["n:nn:z"], nns.tasks.map {|t| t.name} end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_tasklib.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_tasklib.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake/tasklib' class TestTaskLib < Test::Unit::TestCase def test_paste tl = Rake::TaskLib.new assert_equal :ab, tl.paste(:a, :b) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/reqfile.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/reqfile.rb
# For --require testing TESTING_REQUIRE << 1
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_require.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_require.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' require 'test/rake_test_setup' # ==================================================================== class TestRequire < Test::Unit::TestCase include TestMethods def test_can_load_rake_library app = Rake::Application.new assert app.instance_eval { rake_require("test2", ['test/data/rakelib'], []) } end def test_wont_reload_rake_library app = Rake::Application.new assert ! app.instance_eval { rake_require("test2", ['test/data/rakelib'], ['test2']) } end def test_throws_error_if_library_not_found app = Rake::Application.new ex = assert_exception(LoadError) { assert app.instance_eval { rake_require("testx", ['test/data/rakelib'], []) } } assert_match(/x/, ex.message) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_earlytime.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_earlytime.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' class TestEarlyTime < Test::Unit::TestCase def test_create early = Rake::EarlyTime.instance time = Time.mktime(1970, 1, 1, 0, 0, 0) assert early <= Time.now assert early < Time.now assert early != Time.now assert Time.now > early assert Time.now >= early assert Time.now != early end def test_equality early = Rake::EarlyTime.instance assert_equal early, early, "two early times should be equal" end def test_original_time_compare_is_not_messed_up t1 = Time.mktime(1970, 1, 1, 0, 0, 0) t2 = Time.now assert t1 < t2 assert t2 > t1 assert t1 == t1 assert t2 == t2 end def test_to_s assert_equal "<EARLY TIME>", Rake::EARLY.to_s end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_filelist.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_filelist.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' require 'test/capture_stdout' require 'test/rake_test_setup' class TestFileList < Test::Unit::TestCase FileList = Rake::FileList include CaptureStdout include TestMethods def setup create_test_data end def teardown # FileList.select_default_ignore_patterns FileUtils.rm_rf("testdata") end def test_delgating_methods_do_not_include_to_a_or_to_ary assert ! FileList::DELEGATING_METHODS.include?("to_a"), "should not include to_a" assert ! FileList::DELEGATING_METHODS.include?(:to_a), "should not include to_a" assert ! FileList::DELEGATING_METHODS.include?("to_ary"), "should not include to_ary" assert ! FileList::DELEGATING_METHODS.include?(:to_ary), "should not include to_ary" end def test_create fl = FileList.new assert_equal 0, fl.size end def test_create_with_args fl = FileList.new("testdata/*.c", "x") assert_equal ["testdata/abc.c", "testdata/x.c", "testdata/xyz.c", "x"].sort, fl.sort end def test_create_with_block fl = FileList.new { |f| f.include("x") } assert_equal ["x"], fl.resolve end def test_create_with_brackets fl = FileList["testdata/*.c", "x"] assert_equal ["testdata/abc.c", "testdata/x.c", "testdata/xyz.c", "x"].sort, fl.sort end def test_create_with_brackets_and_filelist fl = FileList[FileList["testdata/*.c", "x"]] assert_equal ["testdata/abc.c", "testdata/x.c", "testdata/xyz.c", "x"].sort, fl.sort end def test_include_with_another_array fl = FileList.new.include(["x", "y", "z"]) assert_equal ["x", "y", "z"].sort, fl.sort end def test_include_with_another_filelist fl = FileList.new.include(FileList["testdata/*.c", "x"]) assert_equal ["testdata/abc.c", "testdata/x.c", "testdata/xyz.c", "x"].sort, fl.sort end def test_append fl = FileList.new fl << "a.rb" << "b.rb" assert_equal ['a.rb', 'b.rb'], fl end def test_add_many fl = FileList.new fl.include %w(a d c) fl.include('x', 'y') assert_equal ['a', 'd', 'c', 'x', 'y'], fl assert_equal ['a', 'd', 'c', 'x', 'y'], fl.resolve end def test_add_return f = FileList.new g = f << "x" assert_equal f.object_id, g.object_id h = f.include("y") assert_equal f.object_id, h.object_id end def test_match fl = FileList.new fl.include('test/test*.rb') assert fl.include?("test/test_filelist.rb") assert fl.size > 3 fl.each { |fn| assert_match(/\.rb$/, fn) } end def test_add_matching fl = FileList.new fl << "a.java" fl.include("test/*.rb") assert_equal "a.java", fl[0] assert fl.size > 2 assert fl.include?("test/test_filelist.rb") end def test_multiple_patterns create_test_data fl = FileList.new fl.include('*.c', '*xist*') assert_equal [], fl fl.include('testdata/*.c', 'testdata/*xist*') assert_equal [ 'testdata/x.c', 'testdata/xyz.c', 'testdata/abc.c', 'testdata/existing' ].sort, fl.sort end def test_square_bracket_pattern fl = FileList.new fl.include("testdata/abc.[ch]") assert fl.size == 2 assert fl.include?("testdata/abc.c") assert fl.include?("testdata/abc.h") end def test_curly_bracket_pattern fl = FileList.new fl.include("testdata/abc.{c,h}") assert fl.size == 2 assert fl.include?("testdata/abc.c") assert fl.include?("testdata/abc.h") end def test_reject fl = FileList.new fl.include %w(testdata/x.c testdata/abc.c testdata/xyz.c testdata/existing) fl.reject! { |fn| fn =~ %r{/x} } assert_equal [ 'testdata/abc.c', 'testdata/existing' ], fl end def test_exclude fl = FileList['testdata/x.c', 'testdata/abc.c', 'testdata/xyz.c', 'testdata/existing'] fl.each { |fn| touch fn, :verbose => false } x = fl.exclude(%r{/x.+\.}) assert_equal FileList, x.class assert_equal %w(testdata/x.c testdata/abc.c testdata/existing), fl assert_equal fl.object_id, x.object_id fl.exclude('testdata/*.c') assert_equal ['testdata/existing'], fl fl.exclude('testdata/existing') assert_equal [], fl end def test_excluding_via_block fl = FileList['testdata/a.c', 'testdata/b.c', 'testdata/xyz.c'] fl.exclude { |fn| fn.pathmap('%n') == 'xyz' } assert fl.exclude?("xyz.c"), "Should exclude xyz.c" assert_equal ['testdata/a.c', 'testdata/b.c'], fl end def test_exclude_return_on_create fl = FileList['testdata/*'].exclude(/.*\.[hcx]$/) assert_equal ['testdata/existing', 'testdata/cfiles'].sort, fl.sort assert_equal FileList, fl.class end def test_exclude_with_string_return_on_create fl = FileList['testdata/*'].exclude('testdata/abc.c') assert_equal %w(testdata/existing testdata/cfiles testdata/x.c testdata/abc.h testdata/abc.x testdata/xyz.c).sort, fl.sort assert_equal FileList, fl.class end def test_default_exclude fl = FileList.new fl.clear_exclude fl.include("**/*~", "**/*.bak", "**/core") assert fl.member?("testdata/core"), "Should include core" assert fl.member?("testdata/x.bak"), "Should include .bak files" end def test_unique fl = FileList.new fl << "x.c" << "a.c" << "b.rb" << "a.c" assert_equal ['x.c', 'a.c', 'b.rb', 'a.c'], fl fl.uniq! assert_equal ['x.c', 'a.c', 'b.rb'], fl end def test_to_string fl = FileList.new fl << "a.java" << "b.java" assert_equal "a.java b.java", fl.to_s assert_equal "a.java b.java", "#{fl}" end def test_to_array fl = FileList['a.java', 'b.java'] assert_equal ['a.java', 'b.java'], fl.to_a assert_equal Array, fl.to_a.class assert_equal ['a.java', 'b.java'], fl.to_ary assert_equal Array, fl.to_ary.class end def test_to_s_pending fl = FileList['testdata/abc.*'] result = fl.to_s assert_match(%r{testdata/abc\.c}, result) assert_match(%r{testdata/abc\.h}, result) assert_match(%r{testdata/abc\.x}, result) assert_match(%r{(testdata/abc\..\b ?){2}}, result) end def test_inspect_pending fl = FileList['testdata/abc.*'] result = fl.inspect assert_match(%r{"testdata/abc\.c"}, result) assert_match(%r{"testdata/abc\.h"}, result) assert_match(%r{"testdata/abc\.x"}, result) assert_match(%r|^\[("testdata/abc\..", ){2}"testdata/abc\.."\]$|, result) end def test_sub fl = FileList["testdata/*.c"] f2 = fl.sub(/\.c$/, ".o") assert_equal FileList, f2.class assert_equal ["testdata/abc.o", "testdata/x.o", "testdata/xyz.o"].sort, f2.sort f3 = fl.gsub(/\.c$/, ".o") assert_equal FileList, f3.class assert_equal ["testdata/abc.o", "testdata/x.o", "testdata/xyz.o"].sort, f3.sort end def test_claim_to_be_a_kind_of_array fl = FileList['testdata/*.c'] assert fl.is_a?(Array) assert fl.kind_of?(Array) end def test_claim_to_be_a_kind_of_filelist fl = FileList['testdata/*.c'] assert fl.is_a?(FileList) assert fl.kind_of?(FileList) end def test_claim_to_be_a_filelist_instance fl = FileList['testdata/*.c'] assert fl.instance_of?(FileList) end def test_dont_claim_to_be_an_array_instance fl = FileList['testdata/*.c'] assert ! fl.instance_of?(Array) end def test_sub! f = "x/a.c" fl = FileList[f, "x/b.c"] res = fl.sub!(/\.c$/, ".o") assert_equal ["x/a.o", "x/b.o"].sort, fl.sort assert_equal "x/a.c", f assert_equal fl.object_id, res.object_id end def test_sub_with_block fl = FileList["src/org/onestepback/a.java", "src/org/onestepback/b.java"] # The block version doesn't work the way I want it to ... # f2 = fl.sub(%r{^src/(.*)\.java$}) { |x| "classes/" + $1 + ".class" } f2 = fl.sub(%r{^src/(.*)\.java$}, "classes/\\1.class") assert_equal [ "classes/org/onestepback/a.class", "classes/org/onestepback/b.class" ].sort, f2.sort end def test_string_ext assert_equal "one.net", "one.two".ext("net") assert_equal "one.net", "one.two".ext(".net") assert_equal "one.net", "one".ext("net") assert_equal "one.net", "one".ext(".net") assert_equal "one.two.net", "one.two.c".ext(".net") assert_equal "one/two.net", "one/two.c".ext(".net") assert_equal "one.x/two.net", "one.x/two.c".ext(".net") assert_equal "one.x/two.net", "one.x/two".ext(".net") assert_equal ".onerc.net", ".onerc.dot".ext("net") assert_equal ".onerc.net", ".onerc".ext("net") assert_equal ".a/.onerc.net", ".a/.onerc".ext("net") assert_equal "one", "one.two".ext('') assert_equal "one", "one.two".ext assert_equal ".one", ".one.two".ext assert_equal ".one", ".one".ext assert_equal ".", ".".ext("c") assert_equal "..", "..".ext("c") # These only need to work in windows if Rake::Win32.windows? assert_equal "one.x\\two.net", "one.x\\two.c".ext(".net") assert_equal "one.x\\two.net", "one.x\\two".ext(".net") end end def test_filelist_ext assert_equal FileList['one.c', '.one.c'], FileList['one.net', '.one'].ext('c') end def test_gsub create_test_data fl = FileList["testdata/*.c"] f2 = fl.gsub(/a/, "A") assert_equal ["testdAtA/Abc.c", "testdAtA/x.c", "testdAtA/xyz.c"].sort, f2.sort end def test_gsub! create_test_data f = FileList["testdata/*.c"] f.gsub!(/a/, "A") assert_equal ["testdAtA/Abc.c", "testdAtA/x.c", "testdAtA/xyz.c"].sort, f.sort end def test_egrep_with_output files = FileList['test/test*.rb'] the_line_number = __LINE__ + 1 out = capture_stdout do files.egrep(/PUGH/) end assert_match(/:#{the_line_number}:/, out) end def test_egrep_with_block files = FileList['test/test*.rb'] found = false the_line_number = __LINE__ + 1 files.egrep(/XYZZY/) do |fn, ln, line | assert_equal 'test/test_filelist.rb', fn assert_equal the_line_number, ln assert_match(/files\.egrep/, line) found = true end assert found, "should have found a matching line" end def test_existing fl = FileList['testdata/abc.c', 'testdata/notthere.c'] assert_equal ["testdata/abc.c"], fl.existing assert fl.existing.is_a?(FileList) end def test_existing! fl = FileList['testdata/abc.c', 'testdata/notthere.c'] result = fl.existing! assert_equal ["testdata/abc.c"], fl assert_equal fl.object_id, result.object_id end def test_ignore_special f = FileList['testdata/*'] assert ! f.include?("testdata/CVS"), "Should not contain CVS" assert ! f.include?("testdata/.svn"), "Should not contain .svn" assert ! f.include?("testdata/.dummy"), "Should not contain dot files" assert ! f.include?("testdata/x.bak"), "Should not contain .bak files" assert ! f.include?("testdata/x~"), "Should not contain ~ files" assert ! f.include?("testdata/core"), "Should not contain core files" end def test_clear_ignore_patterns f = FileList['testdata/*', 'testdata/.svn'] f.clear_exclude assert f.include?("testdata/abc.c") assert f.include?("testdata/xyz.c") assert f.include?("testdata/CVS") assert f.include?("testdata/.svn") assert f.include?("testdata/x.bak") assert f.include?("testdata/x~") end def test_exclude_with_alternate_file_seps fl = FileList.new assert fl.exclude?("x/CVS/y") assert fl.exclude?("x\\CVS\\y") assert fl.exclude?("x/.svn/y") assert fl.exclude?("x\\.svn\\y") assert fl.exclude?("x/core") assert fl.exclude?("x\\core") end def test_add_default_exclude_list fl = FileList.new fl.exclude(/~\d+$/) assert fl.exclude?("x/CVS/y") assert fl.exclude?("x\\CVS\\y") assert fl.exclude?("x/.svn/y") assert fl.exclude?("x\\.svn\\y") assert fl.exclude?("x/core") assert fl.exclude?("x\\core") assert fl.exclude?("x/abc~1") end def test_basic_array_functions f = FileList['b', 'c', 'a'] assert_equal 'b', f.first assert_equal 'b', f[0] assert_equal 'a', f.last assert_equal 'a', f[2] assert_equal 'a', f[-1] assert_equal ['a', 'b', 'c'], f.sort f.sort! assert_equal ['a', 'b', 'c'], f end def test_flatten assert_equal ['a', 'testdata/x.c', 'testdata/xyz.c', 'testdata/abc.c'].sort, ['a', FileList['testdata/*.c']].flatten.sort end def test_clone_and_dup a = FileList['a', 'b', 'c'] c = a.clone d = a.dup a << 'd' assert_equal ['a', 'b', 'c', 'd'], a assert_equal ['a', 'b', 'c'], c assert_equal ['a', 'b', 'c'], d end def test_dup_and_clone_replicate_taint a = FileList['a', 'b', 'c'] a.taint c = a.clone d = a.dup assert c.tainted?, "Clone should be tainted" assert d.tainted?, "Dup should be tainted" end def test_duped_items_will_thaw a = FileList['a', 'b', 'c'] a.freeze d = a.dup d << 'more' assert_equal ['a', 'b', 'c', 'more'], d end def test_cloned_items_stay_frozen a = FileList['a', 'b', 'c'] a.freeze c = a.clone assert_exception(TypeError, RuntimeError) do c << 'more' end end def test_array_comparisons fl = FileList['b', 'b'] a = ['b', 'a'] b = ['b', 'b'] c = ['b', 'c'] assert_equal( 1, fl <=> a ) assert_equal( 0, fl <=> b ) assert_equal( -1, fl <=> c ) assert_equal( -1, a <=> fl ) assert_equal( 0, b <=> fl ) assert_equal( 1, c <=> fl ) end def test_array_equality a = FileList['a', 'b'] b = ['a', 'b'] assert a == b assert b == a # assert a.eql?(b) # assert b.eql?(a) assert ! a.equal?(b) assert ! b.equal?(a) end def test_enumeration_methods a = FileList['a', 'b'] b = a.collect { |it| it.upcase } assert_equal ['A', 'B'], b assert_equal FileList, b.class b = a.map { |it| it.upcase } assert_equal ['A', 'B'], b assert_equal FileList, b.class b = a.sort assert_equal ['a', 'b'], b assert_equal FileList, b.class b = a.sort_by { |it| it } assert_equal ['a', 'b'], b assert_equal FileList, b.class b = a.find_all { |it| it == 'b'} assert_equal ['b'], b assert_equal FileList, b.class b = a.select { |it| it.size == 1 } assert_equal ['a', 'b'], b assert_equal FileList, b.class b = a.reject { |it| it == 'b' } assert_equal ['a'], b assert_equal FileList, b.class b = a.grep(/./) assert_equal ['a', 'b'], b assert_equal FileList, b.class b = a.partition { |it| it == 'b' } assert_equal [['b'], ['a']], b assert_equal Array, b.class assert_equal FileList, b[0].class assert_equal FileList, b[1].class b = a.zip(['x', 'y']).to_a assert_equal [['a', 'x'], ['b', 'y']], b assert_equal Array, b.class assert_equal Array, b[0].class assert_equal Array, b[1].class end def test_array_operators a = ['a', 'b'] b = ['c', 'd'] f = FileList['x', 'y'] g = FileList['w', 'z'] r = f + g assert_equal ['x', 'y', 'w', 'z'], r assert_equal FileList, r.class r = a + g assert_equal ['a', 'b', 'w', 'z'], r assert_equal Array, r.class r = f + b assert_equal ['x', 'y', 'c', 'd'], r assert_equal FileList, r.class r = FileList['w', 'x', 'y', 'z'] - f assert_equal ['w', 'z'], r assert_equal FileList, r.class r = FileList['w', 'x', 'y', 'z'] & f assert_equal ['x', 'y'], r assert_equal FileList, r.class r = f * 2 assert_equal ['x', 'y', 'x', 'y'], r assert_equal FileList, r.class r = f * ',' assert_equal 'x,y', r assert_equal String, r.class r = f | ['a', 'x'] assert_equal ['a', 'x', 'y'].sort, r.sort assert_equal FileList, r.class end def test_other_array_returning_methods f = FileList['a', nil, 'b'] r = f.compact assert_equal ['a', 'b'], r assert_equal FileList, r.class f = FileList['a', 'b'] r = f.concat(['x', 'y']) assert_equal ['a', 'b', 'x', 'y'], r assert_equal FileList, r.class f = FileList['a', ['b', 'c'], FileList['d', 'e']] r = f.flatten assert_equal ['a', 'b', 'c', 'd', 'e'], r assert_equal FileList, r.class f = FileList['a', 'b', 'a'] r = f.uniq assert_equal ['a', 'b'], r assert_equal FileList, r.class f = FileList['a', 'b', 'c', 'd'] r = f.values_at(1,3) assert_equal ['b', 'd'], r assert_equal FileList, r.class end def test_file_utils_can_use_filelists cfiles = FileList['testdata/*.c'] cp cfiles, @cdir, :verbose => false assert File.exist?(File.join(@cdir, 'abc.c')) assert File.exist?(File.join(@cdir, 'xyz.c')) assert File.exist?(File.join(@cdir, 'x.c')) end def create_test_data verbose(false) do mkdir "testdata" unless File.exist? "testdata" mkdir "testdata/CVS" rescue nil mkdir "testdata/.svn" rescue nil @cdir = "testdata/cfiles" mkdir @cdir rescue nil touch "testdata/.dummy" touch "testdata/x.bak" touch "testdata/x~" touch "testdata/core" touch "testdata/x.c" touch "testdata/xyz.c" touch "testdata/abc.c" touch "testdata/abc.h" touch "testdata/abc.x" touch "testdata/existing" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_file_creation_task.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_file_creation_task.rb
#!/usr/bin/env ruby require 'test/unit' require 'fileutils' require 'rake' require 'test/filecreation' ###################################################################### class TestFileCreationTask < Test::Unit::TestCase include Rake include FileCreation DUMMY_DIR = 'testdata/dummy_dir' def setup Task.clear end def teardown FileUtils.rm_rf DUMMY_DIR end def test_file_needed create_dir DUMMY_DIR fc_task = Task[DUMMY_DIR] assert_equal DUMMY_DIR, fc_task.name FileUtils.rm_rf fc_task.name assert fc_task.needed?, "file should be needed" FileUtils.mkdir fc_task.name assert_equal nil, fc_task.prerequisites.collect{|n| Task[n].timestamp}.max assert ! fc_task.needed?, "file should not be needed" end def test_directory directory DUMMY_DIR fc_task = Task[DUMMY_DIR] assert_equal DUMMY_DIR, fc_task.name assert FileCreationTask === fc_task end def test_no_retriggers_on_filecreate_task create_timed_files(OLDFILE, NEWFILE) t1 = Rake.application.intern(FileCreationTask, OLDFILE).enhance([NEWFILE]) t2 = Rake.application.intern(FileCreationTask, NEWFILE) assert ! t2.needed?, "Should not need to build new file" assert ! t1.needed?, "Should not need to rebuild old file because of new" end def test_no_retriggers_on_file_task create_timed_files(OLDFILE, NEWFILE) t1 = Rake.application.intern(FileCreationTask, OLDFILE).enhance([NEWFILE]) t2 = Rake.application.intern(FileCreationTask, NEWFILE) assert ! t2.needed?, "Should not need to build new file" assert ! t1.needed?, "Should not need to rebuild old file because of new" end def test_very_early_timestamp t1 = Rake.application.intern(FileCreationTask, OLDFILE) assert t1.timestamp < Time.now assert t1.timestamp < Time.now - 1000000 end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_task_arguments.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_task_arguments.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' ###################################################################### class TestTaskArguments < Test::Unit::TestCase def teardown ENV.delete('rev') ENV.delete('VER') end def test_empty_arg_list_is_empty ta = Rake::TaskArguments.new([], []) assert_equal({}, ta.to_hash) end def test_multiple_values_in_args ta = Rake::TaskArguments.new([:a, :b, :c], [:one, :two, :three]) assert_equal({:a => :one, :b => :two, :c => :three}, ta.to_hash) end def test_to_s ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3]) assert_equal ta.to_hash.inspect, ta.to_s assert_equal ta.to_hash.inspect, ta.inspect end def test_enumerable_behavior ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2 ,3]) assert_equal [10, 20, 30], ta.collect { |k,v| v * 10 }.sort end def test_named_args ta = Rake::TaskArguments.new(["aa", "bb"], [1, 2]) assert_equal 1, ta.aa assert_equal 1, ta[:aa] assert_equal 1, ta["aa"] assert_equal 2, ta.bb assert_nil ta.cc end def test_args_knows_its_names ta = Rake::TaskArguments.new(["aa", "bb"], [1, 2]) assert_equal ["aa", "bb"], ta.names end def test_extra_names_are_nil ta = Rake::TaskArguments.new(["aa", "bb", "cc"], [1, 2]) assert_nil ta.cc end def test_args_can_reference_env_values ta = Rake::TaskArguments.new(["aa"], [1]) ENV['rev'] = "1.2" ENV['VER'] = "2.3" assert_equal "1.2", ta.rev assert_equal "2.3", ta.ver end def test_creating_new_argument_scopes parent = Rake::TaskArguments.new(['p'], [1]) child = parent.new_scope(['c', 'p']) assert_equal({:p=>1}, child.to_hash) assert_equal 1, child.p assert_equal 1, child["p"] assert_equal 1, child[:p] assert_nil child.c end def test_child_hides_parent_arg_names parent = Rake::TaskArguments.new(['aa'], [1]) child = Rake::TaskArguments.new(['aa'], [2], parent) assert_equal 2, child.aa end def test_default_arguments_values_can_be_merged ta = Rake::TaskArguments.new(["aa", "bb"], [nil, "original_val"]) ta.with_defaults({ :aa => 'default_val' }) assert_equal 'default_val', ta[:aa] assert_equal 'original_val', ta[:bb] end def test_default_arguements_that_dont_match_names_are_ignored ta = Rake::TaskArguments.new(["aa", "bb"], [nil, "original_val"]) ta.with_defaults({ "cc" => "default_val" }) assert_nil ta[:cc] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_definitions.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_definitions.rb
#!/usr/bin/env ruby require 'test/unit' require 'fileutils' require 'rake' require 'test/filecreation' require 'test/rake_test_setup' ###################################################################### class TestDefinitions < Test::Unit::TestCase include Rake include TestMethods EXISTINGFILE = "testdata/existing" def setup Task.clear end def test_task done = false task :one => [:two] do done = true end task :two task :three => [:one, :two] check_tasks(:one, :two, :three) assert done, "Should be done" end def test_file_task done = false file "testdata/one" => "testdata/two" do done = true end file "testdata/two" file "testdata/three" => ["testdata/one", "testdata/two"] check_tasks("testdata/one", "testdata/two", "testdata/three") assert done, "Should be done" end def check_tasks(n1, n2, n3) t = Task[n1] assert Task === t, "Should be a Task" assert_equal n1.to_s, t.name assert_equal [n2.to_s], t.prerequisites.collect{|n| n.to_s} t.invoke t2 = Task[n2] assert_equal FileList[], t2.prerequisites t3 = Task[n3] assert_equal [n1.to_s, n2.to_s], t3.prerequisites.collect{|n|n.to_s} end def test_incremental_definitions runs = [] task :t1 => [:t2] do runs << "A"; 4321 end task :t1 => [:t3] do runs << "B"; 1234 end task :t1 => [:t3] task :t2 task :t3 Task[:t1].invoke assert_equal ["A", "B"], runs assert_equal ["t2", "t3"], Task[:t1].prerequisites end def test_missing_dependencies task :x => ["testdata/missing"] assert_exception(RuntimeError) { Task[:x].invoke } end def test_implicit_file_dependencies runs = [] create_existing_file task :y => [EXISTINGFILE] do |t| runs << t.name end Task[:y].invoke assert_equal runs, ['y'] end private # ---------------------------------------------------------- def create_existing_file Dir.mkdir File.dirname(EXISTINGFILE) unless File.exist?(File.dirname(EXISTINGFILE)) open(EXISTINGFILE, "w") do |f| f.puts "HI" end unless File.exist?(EXISTINGFILE) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_tasks.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_tasks.rb
#!/usr/bin/env ruby require 'test/unit' require 'fileutils' require 'rake' require 'test/filecreation' require 'test/capture_stdout' require 'test/rake_test_setup' ###################################################################### class TestTask < Test::Unit::TestCase include CaptureStdout include Rake include TestMethods def setup Task.clear end def test_create arg = nil t = task(:name) { |task| arg = task; 1234 } assert_equal "name", t.name assert_equal [], t.prerequisites assert t.needed? t.execute(0) assert_equal t, arg assert_nil t.source assert_equal [], t.sources end def test_inspect t = task(:foo, :needs => [:bar, :baz]) assert_equal "<Rake::Task foo => [bar, baz]>", t.inspect end def test_invoke runlist = [] t1 = task(:t1 => [:t2, :t3]) { |t| runlist << t.name; 3321 } t2 = task(:t2) { |t| runlist << t.name } t3 = task(:t3) { |t| runlist << t.name } assert_equal ["t2", "t3"], t1.prerequisites t1.invoke assert_equal ["t2", "t3", "t1"], runlist end def test_invoke_with_circular_dependencies runlist = [] t1 = task(:t1 => [:t2]) { |t| runlist << t.name; 3321 } t2 = task(:t2 => [:t1]) { |t| runlist << t.name } assert_equal ["t2"], t1.prerequisites assert_equal ["t1"], t2.prerequisites ex = assert_exception RuntimeError do t1.invoke end assert_match(/circular dependency/i, ex.message) assert_match(/t1 => t2 => t1/, ex.message) end def test_dry_run_prevents_actions Rake.application.options.dryrun = true runlist = [] t1 = task(:t1) { |t| runlist << t.name; 3321 } out = capture_stdout { t1.invoke } assert_match(/execute .*t1/i, out) assert_match(/dry run/i, out) assert_no_match(/invoke/i, out) assert_equal [], runlist ensure Rake.application.options.dryrun = false end def test_tasks_can_be_traced Rake.application.options.trace = true t1 = task(:t1) out = capture_stdout { t1.invoke } assert_match(/invoke t1/i, out) assert_match(/execute t1/i, out) ensure Rake.application.options.trace = false end def test_no_double_invoke runlist = [] t1 = task(:t1 => [:t2, :t3]) { |t| runlist << t.name; 3321 } t2 = task(:t2 => [:t3]) { |t| runlist << t.name } t3 = task(:t3) { |t| runlist << t.name } t1.invoke assert_equal ["t3", "t2", "t1"], runlist end def test_can_double_invoke_with_reenable runlist = [] t1 = task(:t1) { |t| runlist << t.name } t1.invoke t1.reenable t1.invoke assert_equal ["t1", "t1"], runlist end def test_clear t = task("t" => "a") { } t.clear assert t.prerequisites.empty?, "prerequisites should be empty" assert t.actions.empty?, "actions should be empty" end def test_clear_prerequisites t = task("t" => ["a", "b"]) assert_equal ['a', 'b'], t.prerequisites t.clear_prerequisites assert_equal [], t.prerequisites end def test_clear_actions t = task("t") { } t.clear_actions assert t.actions.empty?, "actions should be empty" end def test_find task :tfind assert_equal "tfind", Task[:tfind].name ex = assert_exception(RuntimeError) { Task[:leaves] } assert_equal "Don't know how to build task 'leaves'", ex.message end def test_defined assert ! Task.task_defined?(:a) task :a assert Task.task_defined?(:a) end def test_multi_invocations runs = [] p = proc do |t| runs << t.name end task({:t1=>[:t2,:t3]}, &p) task({:t2=>[:t3]}, &p) task(:t3, &p) Task[:t1].invoke assert_equal ["t1", "t2", "t3"], runs.sort end def test_task_list task :t2 task :t1 => [:t2] assert_equal ["t1", "t2"], Task.tasks.collect {|t| t.name} end def test_task_gives_name_on_to_s task :abc assert_equal "abc", Task[:abc].to_s end def test_symbols_can_be_prerequisites task :a => :b assert_equal ["b"], Task[:a].prerequisites end def test_strings_can_be_prerequisites task :a => "b" assert_equal ["b"], Task[:a].prerequisites end def test_arrays_can_be_prerequisites task :a => ["b", "c"] assert_equal ["b", "c"], Task[:a].prerequisites end def test_filelists_can_be_prerequisites task :a => FileList.new.include("b", "c") assert_equal ["b", "c"], Task[:a].prerequisites end def test_investigation_output t1 = task(:t1 => [:t2, :t3]) { |t| runlist << t.name; 3321 } task(:t2) task(:t3) out = t1.investigation assert_match(/class:\s*Rake::Task/, out) assert_match(/needed:\s*true/, out) assert_match(/pre-requisites:\s*--t[23]/, out) end def test_extended_comments desc %{ This is a comment. And this is the extended comment. name -- Name of task to execute. rev -- Software revision to use. } t = task(:t, :name, :rev) assert_equal "[name,rev]", t.arg_description assert_equal "This is a comment.", t.comment assert_match(/^\s*name -- Name/, t.full_comment) assert_match(/^\s*rev -- Software/, t.full_comment) assert_match(/\A\s*This is a comment\.$/, t.full_comment) end def test_multiple_comments desc "line one" t = task(:t) desc "line two" task(:t) assert_equal "line one / line two", t.comment end def test_settable_comments t = task(:t) t.comment = "HI" assert_equal "HI", t.comment end end ###################################################################### class TestTaskWithArguments < Test::Unit::TestCase include CaptureStdout include Rake include TestMethods def setup Task.clear end def test_no_args_given t = task :t assert_equal [], t.arg_names end def test_args_given t = task :t, :a, :b assert_equal [:a, :b], t.arg_names end def test_name_and_needs t = task(:t => [:pre]) assert_equal "t", t.name assert_equal [], t.arg_names assert_equal ["pre"], t.prerequisites end def test_name_and_explicit_needs t = task(:t, :needs => [:pre]) assert_equal "t", t.name assert_equal [], t.arg_names assert_equal ["pre"], t.prerequisites end def test_name_args_and_explicit_needs t = task(:t, :x, :y, :needs => [:pre]) assert_equal "t", t.name assert_equal [:x, :y], t.arg_names assert_equal ["pre"], t.prerequisites end def test_illegal_keys_in_task_name_hash assert_exception RuntimeError do t = task(:t, :x, :y => 1, :needs => [:pre]) end end def test_arg_list_is_empty_if_no_args_given t = task(:t) { |tt, args| assert_equal({}, args.to_hash) } t.invoke(1, 2, 3) end def test_tasks_can_access_arguments_as_hash t = task :t, :a, :b, :c do |tt, args| assert_equal({:a => 1, :b => 2, :c => 3}, args.to_hash) assert_equal 1, args[:a] assert_equal 2, args[:b] assert_equal 3, args[:c] assert_equal 1, args.a assert_equal 2, args.b assert_equal 3, args.c end t.invoke(1, 2, 3) end def test_actions_of_various_arity_are_ok_with_args notes = [] t = task(:t, :x) do notes << :a end t.enhance do | | notes << :b end t.enhance do |task| notes << :c assert_kind_of Task, task end t.enhance do |t2, args| notes << :d assert_equal t, t2 assert_equal({:x => 1}, args.to_hash) end assert_nothing_raised do t.invoke(1) end assert_equal [:a, :b, :c, :d], notes end def test_arguments_are_passed_to_block t = task(:t, :a, :b) { |tt, args| assert_equal( { :a => 1, :b => 2 }, args.to_hash ) } t.invoke(1, 2) end def test_extra_parameters_are_ignored t = task(:t, :a) { |tt, args| assert_equal 1, args.a assert_nil args.b } t.invoke(1, 2) end def test_arguments_are_passed_to_all_blocks counter = 0 t = task :t, :a task :t do |tt, args| assert_equal 1, args.a counter += 1 end task :t do |tt, args| assert_equal 1, args.a counter += 1 end t.invoke(1) assert_equal 2, counter end def test_block_with_no_parameters_is_ok t = task(:t) { } t.invoke(1, 2) end def test_name_with_args desc "T" t = task(:tt, :a, :b) assert_equal "tt", t.name assert_equal "T", t.comment assert_equal "[a,b]", t.arg_description assert_equal "tt[a,b]", t.name_with_args assert_equal [:a, :b],t.arg_names end def test_named_args_are_passed_to_prereqs value = nil pre = task(:pre, :rev) { |t, args| value = args.rev } t = task(:t, :name, :rev, :needs => [:pre]) t.invoke("bill", "1.2") assert_equal "1.2", value end def test_args_not_passed_if_no_prereq_names pre = task(:pre) { |t, args| assert_equal({}, args.to_hash) assert_equal "bill", args.name } t = task(:t, :name, :rev, :needs => [:pre]) t.invoke("bill", "1.2") end def test_args_not_passed_if_no_arg_names pre = task(:pre, :rev) { |t, args| assert_equal({}, args.to_hash) } t = task(:t, :needs => [:pre]) t.invoke("bill", "1.2") end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/shellcommand.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/shellcommand.rb
#!/usr/bin/env ruby exit((ARGV[0] || "0").to_i)
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/rake_test_setup.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/rake_test_setup.rb
# Common setup for all test files. begin require 'rubygems' gem 'flexmock' rescue LoadError # got no gems end require 'flexmock/test_unit' if RUBY_VERSION >= "1.9.0" class Test::Unit::TestCase # def passed? # true # end end end module TestMethods def assert_exception(ex, msg=nil, &block) assert_raise(ex, msg, &block) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/capture_stdout.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/capture_stdout.rb
#!/usr/bin/env ruby require 'stringio' # Mix-in for capturing standard output. module CaptureStdout def capture_stdout s = StringIO.new oldstdout = $stdout $stdout = s yield s.string ensure $stdout = oldstdout end def capture_stderr s = StringIO.new oldstderr = $stderr $stderr = s yield s.string ensure $stderr = oldstderr end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_package_task.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_package_task.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake/packagetask' require 'test/rake_test_setup' class TestPackageTask < Test::Unit::TestCase include Rake include TestMethods def test_create pkg = Rake::PackageTask.new("pkgr", "1.2.3") { |p| p.package_files << "install.rb" p.package_files.include( '[A-Z]*', 'bin/**/*', 'lib/**/*.rb', 'test/**/*.rb', 'doc/**/*', 'build/rubyapp.rb', '*.blurb') p.package_files.exclude(/\bCVS\b/) p.package_files.exclude(/~$/) p.package_dir = 'pkg' p.need_tar = true p.need_tar_gz = true p.need_tar_bz2 = true p.need_zip = true } assert_equal "pkg", pkg.package_dir assert pkg.package_files.include?("bin/rake") assert "pkgr", pkg.name assert "1.2.3", pkg.version assert Task[:package] assert Task['pkg/pkgr-1.2.3.tgz'] assert Task['pkg/pkgr-1.2.3.tar.gz'] assert Task['pkg/pkgr-1.2.3.tar.bz2'] assert Task['pkg/pkgr-1.2.3.zip'] assert Task["pkg/pkgr-1.2.3"] assert Task[:clobber_package] assert Task[:repackage] end def test_missing_version assert_exception(RuntimeError) { pkg = Rake::PackageTask.new("pkgr") { |p| } } end def test_no_version pkg = Rake::PackageTask.new("pkgr", :noversion) { |p| } assert "pkgr", pkg.send(:package_name) end def test_clone pkg = Rake::PackageTask.new("x", :noversion) p2 = pkg.clone pkg.package_files << "y" p2.package_files << "x" assert_equal ["y"], pkg.package_files assert_equal ["x"], p2.package_files end end begin require 'rubygems' require 'rake/gempackagetask' rescue Exception puts "WARNING: RubyGems not installed" end if ! defined?(Gem) puts "WARNING: Unable to test GemPackaging ... requires RubyGems" else class TestGemPackageTask < Test::Unit::TestCase def test_gem_package gem = Gem::Specification.new do |g| g.name = "pkgr" g.version = "1.2.3" g.files = FileList["x"].resolve end pkg = Rake::GemPackageTask.new(gem) do |p| p.package_files << "y" end assert_equal ["x", "y"], pkg.package_files assert_equal "pkgr-1.2.3.gem", pkg.gem_file end def test_gem_package_with_current_platform gem = Gem::Specification.new do |g| g.name = "pkgr" g.version = "1.2.3" g.files = FileList["x"].resolve g.platform = Gem::Platform::CURRENT end pkg = Rake::GemPackageTask.new(gem) do |p| p.package_files << "y" end assert_equal ["x", "y"], pkg.package_files assert_match(/^pkgr-1\.2\.3-(\S+)\.gem$/, pkg.gem_file) end def test_gem_package_with_ruby_platform gem = Gem::Specification.new do |g| g.name = "pkgr" g.version = "1.2.3" g.files = FileList["x"].resolve g.platform = Gem::Platform::RUBY end pkg = Rake::GemPackageTask.new(gem) do |p| p.package_files << "y" end assert_equal ["x", "y"], pkg.package_files assert_equal "pkgr-1.2.3.gem", pkg.gem_file end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_ftp.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_ftp.rb
#!/usr/bin/env ruby require 'date' require 'time' require 'test/unit' require 'rake/contrib/ftptools' class FakeDate def self.today Date.new(2003,10,3) end def self.now Time.local(2003,10,3,12,00,00) end end class TestFtpFile < Test::Unit::TestCase def setup Rake::FtpFile.class_eval { @date_class = FakeDate; @time_class = FakeDate } end def test_general file = Rake::FtpFile.new("here", "-rw-r--r-- 1 a279376 develop 121770 Mar 6 14:50 wiki.pl") assert_equal "wiki.pl", file.name assert_equal "here/wiki.pl", file.path assert_equal "a279376", file.owner assert_equal "develop", file.group assert_equal 0644, file.mode assert_equal 121770, file.size assert_equal Time.mktime(2003,3,6,14,50,0,0), file.time assert ! file.directory? assert ! file.symlink? end def test_far_date file = Rake::FtpFile.new(".", "drwxr-xr-x 3 a279376 develop 4096 Nov 26 2001 vss") assert_equal Time.mktime(2001,11,26,0,0,0,0), file.time end def test_close_date file = Rake::FtpFile.new(".", "drwxr-xr-x 3 a279376 develop 4096 Nov 26 15:35 vss") assert_equal Time.mktime(2002,11,26,15,35,0,0), file.time end def test_directory file = Rake::FtpFile.new(".", "drwxrwxr-x 9 a279376 develop 4096 Mar 13 14:32 working") assert file.directory? assert !file.symlink? end def test_symlink file = Rake::FtpFile.new(".", "lrwxrwxrwx 1 a279376 develop 64 Mar 26 2002 xtrac -> /home/a279376/working/ics/development/java/com/fmr/fwp/ics/xtrac") assert_equal 'xtrac', file.name assert file.symlink? assert !file.directory? end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_pseudo_status.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_pseudo_status.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' require 'test/capture_stdout' require 'test/rake_test_setup' class PseudoStatusTest < Test::Unit::TestCase def test_with_zero_exit_status s = Rake::PseudoStatus.new assert_equal 0, s.exitstatus assert_equal 0, s.to_i assert_equal 0, s >> 8 assert ! s.stopped? assert s.exited? end def test_with_99_exit_status s = Rake::PseudoStatus.new(99) assert_equal 99, s.exitstatus assert_equal 25344, s.to_i assert_equal 99, s >> 8 assert ! s.stopped? assert s.exited? end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/functional.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/functional.rb
#!/usr/bin/env ruby begin require 'rubygems' gem 'session' require 'session' rescue LoadError puts "UNABLE TO RUN FUNCTIONAL TESTS" puts "No Session Found (gem install session)" end if defined?(Session) puts "RUNNING WITH SESSIONS" require 'test/session_functional' end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_rdoc_task.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_rdoc_task.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake/rdoctask' require 'test/rake_test_setup' class TestRDocTask < Test::Unit::TestCase include Rake include TestMethods def setup Task.clear end def test_tasks_creation Rake::RDocTask.new assert Task[:rdoc] assert Task[:clobber_rdoc] assert Task[:rerdoc] end def test_tasks_creation_with_custom_name_symbol rd = Rake::RDocTask.new(:rdoc_dev) assert Task[:rdoc_dev] assert Task[:clobber_rdoc_dev] assert Task[:rerdoc_dev] assert_equal :rdoc_dev, rd.name end def test_tasks_creation_with_custom_name_string rd = Rake::RDocTask.new("rdoc_dev") assert Task[:rdoc_dev] assert Task[:clobber_rdoc_dev] assert Task[:rerdoc_dev] assert_equal "rdoc_dev", rd.name end def test_tasks_creation_with_custom_name_hash options = { :rdoc => "rdoc", :clobber_rdoc => "rdoc:clean", :rerdoc => "rdoc:force" } rd = Rake::RDocTask.new(options) assert Task[:"rdoc"] assert Task[:"rdoc:clean"] assert Task[:"rdoc:force"] assert_raises(RuntimeError) { Task[:clobber_rdoc] } assert_equal options, rd.name end def test_tasks_creation_with_custom_name_hash_will_use_default_if_an_option_isnt_given rd = Rake::RDocTask.new(:clobber_rdoc => "rdoc:clean") assert Task[:rdoc] assert Task[:"rdoc:clean"] assert Task[:rerdoc] end def test_tasks_creation_with_custom_name_hash_raises_exception_if_invalid_option_given assert_raises(ArgumentError) do Rake::RDocTask.new(:foo => "bar") end begin Rake::RDocTask.new(:foo => "bar") rescue ArgumentError => e assert_match(/foo/, e.message) end end def test_inline_source_is_enabled_by_default rd = Rake::RDocTask.new assert rd.option_list.include?('--inline-source') end def test_inline_source_option_is_only_appended_if_option_not_already_given rd = Rake::RDocTask.new rd.options << '--inline-source' assert_equal 1, rd.option_list.grep('--inline-source').size rd = Rake::RDocTask.new rd.options << '-S' assert_equal 1, rd.option_list.grep('-S').size assert_equal 0, rd.option_list.grep('--inline-source').size end def test_inline_source_option_can_be_disabled rd = Rake::RDocTask.new rd.inline_source = false assert !rd.option_list.include?('--inline-source') end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/reqfile2.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/reqfile2.rb
# For --require testing TESTING_REQUIRE << 2
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_rake.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_rake.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' class TestRake < Test::Unit::TestCase def test_each_dir_parent assert_equal ['a'], alldirs('a') assert_equal ['a/b', 'a'], alldirs('a/b') assert_equal ['/a/b', '/a', '/'], alldirs('/a/b') if File.dirname("c:/foo") == "c:" # Under Unix assert_equal ['c:/a/b', 'c:/a', 'c:'], alldirs('c:/a/b') assert_equal ['c:a/b', 'c:a'], alldirs('c:a/b') else # Under Windows assert_equal ['c:/a/b', 'c:/a', 'c:/'], alldirs('c:/a/b') assert_equal ['c:a/b', 'c:a'], alldirs('c:a/b') end end def alldirs(fn) result = [] Rake.each_dir_parent(fn) { |d| result << d } result end def test_can_override_application old_app = Rake.application fake_app = Object.new Rake.application = fake_app assert_equal fake_app, Rake.application ensure Rake.application = old_app end def test_original_dir_reports_current_dir assert_equal Dir.pwd, Rake.original_dir end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_rules.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_rules.rb
#!/usr/bin/env ruby require 'test/unit' require 'fileutils' require 'rake' require 'test/filecreation' require 'test/rake_test_setup' ###################################################################### class TestRules < Test::Unit::TestCase include Rake include FileCreation include TestMethods SRCFILE = "testdata/abc.c" SRCFILE2 = "testdata/xyz.c" FTNFILE = "testdata/abc.f" OBJFILE = "testdata/abc.o" FOOFILE = "testdata/foo" DOTFOOFILE = "testdata/.foo" def setup Task.clear @runs = [] end def teardown FileList['testdata/*'].uniq.each do |f| rm_r(f, :verbose=>false) end end def test_multiple_rules1 create_file(FTNFILE) delete_file(SRCFILE) delete_file(OBJFILE) rule(/\.o$/ => ['.c']) do @runs << :C end rule(/\.o$/ => ['.f']) do @runs << :F end t = Task[OBJFILE] t.invoke Task[OBJFILE].invoke assert_equal [:F], @runs end def test_multiple_rules2 create_file(FTNFILE) delete_file(SRCFILE) delete_file(OBJFILE) rule(/\.o$/ => ['.f']) do @runs << :F end rule(/\.o$/ => ['.c']) do @runs << :C end Task[OBJFILE].invoke assert_equal [:F], @runs end def test_create_with_source create_file(SRCFILE) rule(/\.o$/ => ['.c']) do |t| @runs << t.name assert_equal OBJFILE, t.name assert_equal SRCFILE, t.source end Task[OBJFILE].invoke assert_equal [OBJFILE], @runs end def test_single_dependent create_file(SRCFILE) rule(/\.o$/ => '.c') do |t| @runs << t.name end Task[OBJFILE].invoke assert_equal [OBJFILE], @runs end def test_rule_can_be_created_by_string create_file(SRCFILE) rule '.o' => ['.c'] do |t| @runs << t.name end Task[OBJFILE].invoke assert_equal [OBJFILE], @runs end def test_rule_prereqs_can_be_created_by_string create_file(SRCFILE) rule '.o' => '.c' do |t| @runs << t.name end Task[OBJFILE].invoke assert_equal [OBJFILE], @runs end def test_plain_strings_as_dependents_refer_to_files create_file(SRCFILE) rule '.o' => SRCFILE do |t| @runs << t.name end Task[OBJFILE].invoke assert_equal [OBJFILE], @runs end def test_file_names_beginning_with_dot_can_be_tricked_into_refering_to_file verbose(false) do chdir("testdata") do create_file('.foo') rule '.o' => "./.foo" do |t| @runs << t.name end Task[OBJFILE].invoke assert_equal [OBJFILE], @runs end end end def test_file_names_beginning_with_dot_can_be_wrapped_in_lambda verbose(false) do chdir("testdata") do create_file(".foo") rule '.o' => lambda{".foo"} do |t| @runs << "#{t.name} - #{t.source}" end Task[OBJFILE].invoke assert_equal ["#{OBJFILE} - .foo"], @runs end end end def test_file_names_containing_percent_can_be_wrapped_in_lambda verbose(false) do chdir("testdata") do create_file("foo%x") rule '.o' => lambda{"foo%x"} do |t| @runs << "#{t.name} - #{t.source}" end Task[OBJFILE].invoke assert_equal ["#{OBJFILE} - foo%x"], @runs end end end def test_non_extension_rule_name_refers_to_file verbose(false) do chdir("testdata") do create_file("abc.c") rule "abc" => '.c' do |t| @runs << t.name end Task["abc"].invoke assert_equal ["abc"], @runs end end end def test_pathmap_automatically_applies_to_name verbose(false) do chdir("testdata") do create_file("zzabc.c") rule ".o" => 'zz%{x,a}n.c' do |t| @runs << "#{t.name} - #{t.source}" end Task["xbc.o"].invoke assert_equal ["xbc.o - zzabc.c"], @runs end end end def test_plain_strings_are_just_filenames verbose(false) do chdir("testdata") do create_file("plainname") rule ".o" => 'plainname' do |t| @runs << "#{t.name} - #{t.source}" end Task["xbc.o"].invoke assert_equal ["xbc.o - plainname"], @runs end end end def test_rule_runs_when_explicit_task_has_no_actions create_file(SRCFILE) create_file(SRCFILE2) delete_file(OBJFILE) rule '.o' => '.c' do |t| @runs << t.source end file OBJFILE => [SRCFILE2] Task[OBJFILE].invoke assert_equal [SRCFILE], @runs end def test_close_matches_on_name_do_not_trigger_rule create_file("testdata/x.c") rule '.o' => ['.c'] do |t| @runs << t.name end assert_exception(RuntimeError) { Task['testdata/x.obj'].invoke } assert_exception(RuntimeError) { Task['testdata/x.xyo'].invoke } end def test_rule_rebuilds_obj_when_source_is_newer create_timed_files(OBJFILE, SRCFILE) rule(/\.o$/ => ['.c']) do @runs << :RULE end Task[OBJFILE].invoke assert_equal [:RULE], @runs end def test_rule_with_two_sources_runs_if_both_sources_are_present create_timed_files(OBJFILE, SRCFILE, SRCFILE2) rule OBJFILE => [lambda{SRCFILE}, lambda{SRCFILE2}] do @runs << :RULE end Task[OBJFILE].invoke assert_equal [:RULE], @runs end def test_rule_with_two_sources_but_one_missing_does_not_run create_timed_files(OBJFILE, SRCFILE) delete_file(SRCFILE2) rule OBJFILE => [lambda{SRCFILE}, lambda{SRCFILE2}] do @runs << :RULE end Task[OBJFILE].invoke assert_equal [], @runs end def test_rule_with_two_sources_builds_both_sources task 'x.aa' task 'x.bb' rule '.a' => '.aa' do @runs << "A" end rule '.b' => '.bb' do @runs << "B" end rule ".c" => ['.a', '.b'] do @runs << "C" end Task["x.c"].invoke assert_equal ["A", "B", "C"], @runs.sort end def test_second_rule_runs_when_first_rule_doesnt create_timed_files(OBJFILE, SRCFILE) delete_file(SRCFILE2) rule OBJFILE => [lambda{SRCFILE}, lambda{SRCFILE2}] do @runs << :RULE1 end rule OBJFILE => [lambda{SRCFILE}] do @runs << :RULE2 end Task[OBJFILE].invoke assert_equal [:RULE2], @runs end def test_second_rule_doest_run_if_first_triggers create_timed_files(OBJFILE, SRCFILE, SRCFILE2) rule OBJFILE => [lambda{SRCFILE}, lambda{SRCFILE2}] do @runs << :RULE1 end rule OBJFILE => [lambda{SRCFILE}] do @runs << :RULE2 end Task[OBJFILE].invoke assert_equal [:RULE1], @runs end def test_second_rule_doest_run_if_first_triggers_with_reversed_rules create_timed_files(OBJFILE, SRCFILE, SRCFILE2) rule OBJFILE => [lambda{SRCFILE}] do @runs << :RULE1 end rule OBJFILE => [lambda{SRCFILE}, lambda{SRCFILE2}] do @runs << :RULE2 end Task[OBJFILE].invoke assert_equal [:RULE1], @runs end def test_rule_with_proc_dependent_will_trigger ran = false mkdir_p("testdata/src/jw") create_file("testdata/src/jw/X.java") rule %r(classes/.*\.class) => [ proc { |fn| fn.pathmap("%{classes,testdata/src}d/%n.java") } ] do |task| assert_equal task.name, 'classes/jw/X.class' assert_equal task.source, 'testdata/src/jw/X.java' @runs << :RULE end Task['classes/jw/X.class'].invoke assert_equal [:RULE], @runs ensure rm_r("testdata/src", :verbose=>false) rescue nil end def test_proc_returning_lists_are_flattened_into_prereqs ran = false mkdir_p("testdata/flatten") create_file("testdata/flatten/a.txt") task 'testdata/flatten/b.data' do |t| ran = true touch t.name, :verbose => false end rule '.html' => proc { |fn| [ fn.ext("txt"), "testdata/flatten/b.data" ] } do |task| end Task['testdata/flatten/a.html'].invoke assert ran, "Should have triggered flattened dependency" ensure rm_r("testdata/flatten", :verbose=>false) rescue nil end def test_recursive_rules_will_work_as_long_as_they_terminate actions = [] create_file("testdata/abc.xml") rule '.y' => '.xml' do actions << 'y' end rule '.c' => '.y' do actions << 'c'end rule '.o' => '.c' do actions << 'o'end rule '.exe' => '.o' do actions << 'exe'end Task["testdata/abc.exe"].invoke assert_equal ['y', 'c', 'o', 'exe'], actions end def test_recursive_rules_that_dont_terminate_will_overflow create_file("testdata/a.a") prev = 'a' ('b'..'z').each do |letter| rule ".#{letter}" => ".#{prev}" do |t| puts "#{t.name}" end prev = letter end ex = assert_exception(Rake::RuleRecursionOverflowError) { Task["testdata/a.z"].invoke } assert_match(/a\.z => testdata\/a.y/, ex.message) end def test_rules_with_bad_dependents_will_fail rule "a" => [ 1 ] do |t| puts t.name end assert_exception(RuntimeError) do Task['a'].invoke end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/session_functional.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/session_functional.rb
#!/usr/bin/env ruby begin require 'rubygems' rescue LoadError => ex end require 'test/unit' require 'fileutils' require 'session' require 'test/in_environment' require 'test/rake_test_setup' # Version 2.1.9 of session has a bug where the @debug instance # variable is not initialized, causing warning messages. This snippet # of code fixes that problem. module Session class AbstractSession alias old_initialize initialize def initialize(*args) @debug = nil old_initialize(*args) end end end class FunctionalTest < Test::Unit::TestCase include InEnvironment include TestMethods RUBY_COMMAND = 'ruby' def setup @rake_path = File.expand_path("bin/rake") lib_path = File.expand_path("lib") @ruby_options = "-I#{lib_path} -I." @verbose = ! ENV['VERBOSE'].nil? if @verbose puts puts puts "--------------------------------------------------------------------" puts name puts "--------------------------------------------------------------------" end end def test_rake_default Dir.chdir("test/data/default") do rake end assert_match(/^DEFAULT$/, @out) assert_status end def test_rake_error_on_bad_task Dir.chdir("test/data/default") do rake "xyz" end assert_match(/rake aborted/, @err) assert_status(1) end def test_env_availabe_at_top_scope Dir.chdir("test/data/default") do rake "TESTTOPSCOPE=1" end assert_match(/^TOPSCOPE$/, @out) assert_status end def test_env_availabe_at_task_scope Dir.chdir("test/data/default") do rake "TESTTASKSCOPE=1 task_scope" end assert_match(/^TASKSCOPE$/, @out) assert_status end def test_multi_desc in_environment( 'RAKE_COLUMNS' => "80", "PWD" => "test/data/multidesc" ) do rake "-T" end assert_match %r{^rake a *# A / A2 *$}, @out assert_match %r{^rake b *# B *$}, @out assert_no_match %r{^rake c}, @out assert_match %r{^rake d *# x{65}\.\.\.$}, @out end def test_long_description in_environment("PWD" => "test/data/multidesc") do rake "--describe" end assert_match %r{^rake a\n *A / A2 *$}m, @out assert_match %r{^rake b\n *B *$}m, @out assert_match %r{^rake d\n *x{80}}m, @out assert_no_match %r{^rake c\n}m, @out end def test_rbext in_environment("PWD" => "test/data/rbext") do rake "-N" end assert_match %r{^OK$}, @out end def test_system in_environment('RAKE_SYSTEM' => 'test/data/sys') do rake '-g', "sys1" end assert_match %r{^SYS1}, @out end def test_system_excludes_rakelib_files_too in_environment('RAKE_SYSTEM' => 'test/data/sys') do rake '-g', "sys1", '-T', 'extra' end assert_no_match %r{extra:extra}, @out end def test_by_default_rakelib_files_are_include in_environment('RAKE_SYSTEM' => 'test/data/sys') do rake '-T', 'extra' end assert_match %r{extra:extra}, @out end def test_implicit_system in_environment('RAKE_SYSTEM' => File.expand_path('test/data/sys'), "PWD" => "/") do rake "sys1", "--trace" end assert_match %r{^SYS1}, @out end def test_no_system in_environment('RAKE_SYSTEM' => 'test/data/sys') do rake '-G', "sys1" end assert_match %r{^Don't know how to build task}, @err # emacs wart: ' end def test_nosearch_with_rakefile_uses_local_rakefile in_environment("PWD" => "test/data/default") do rake "--nosearch" end assert_match %r{^DEFAULT}, @out end def test_nosearch_without_rakefile_finds_system in_environment( "PWD" => "test/data/nosearch", "RAKE_SYSTEM" => File.expand_path("test/data/sys") ) do rake "--nosearch", "sys1" end assert_match %r{^SYS1}, @out end def test_nosearch_without_rakefile_and_no_system_fails in_environment("PWD" => "test/data/nosearch", "RAKE_SYSTEM" => "not_exist") do rake "--nosearch" end assert_match %r{^No Rakefile found}, @err end def test_dry_run in_environment("PWD" => "test/data/default") do rake "-n", "other" end assert_match %r{Execute \(dry run\) default}, @out assert_match %r{Execute \(dry run\) other}, @out assert_no_match %r{DEFAULT}, @out assert_no_match %r{OTHER}, @out end # Test for the trace/dry_run bug found by Brian Chandler def test_dry_run_bug in_environment("PWD" => "test/data/dryrun") do rake end FileUtils.rm_f "test/data/dryrun/temp_one" in_environment("PWD" => "test/data/dryrun") do rake "--dry-run" end assert_no_match(/No such file/, @out) assert_status end # Test for the trace/dry_run bug found by Brian Chandler def test_trace_bug in_environment("PWD" => "test/data/dryrun") do rake end FileUtils.rm_f "test/data/dryrun/temp_one" in_environment("PWD" => "test/data/dryrun") do rake "--trace" end assert_no_match(/No such file/, @out) assert_status end def test_imports open("test/data/imports/static_deps", "w") do |f| f.puts 'puts "STATIC"' end FileUtils.rm_f "test/data/imports/dynamic_deps" in_environment("PWD" => "test/data/imports") do rake end assert File.exist?("test/data/imports/dynamic_deps"), "'dynamic_deps' file should exist" assert_match(/^FIRST$\s+^DYNAMIC$\s+^STATIC$\s+^OTHER$/, @out) assert_status FileUtils.rm_f "test/data/imports/dynamic_deps" FileUtils.rm_f "test/data/imports/static_deps" end def test_rules_chaining_to_file_task remove_chaining_files in_environment("PWD" => "test/data/chains") do rake end assert File.exist?("test/data/chains/play.app"), "'play.app' file should exist" assert_status remove_chaining_files end def test_file_creation_task in_environment("PWD" => "test/data/file_creation_task") do rake "prep" rake "run" rake "run" end assert(@err !~ /^cp src/, "Should not recopy data") end def test_dash_f_with_no_arg_foils_rakefile_lookup rake "-I test/data/rakelib -rtest1 -f" assert_match(/^TEST1$/, @out) end def test_dot_rake_files_can_be_loaded_with_dash_r rake "-I test/data/rakelib -rtest2 -f" assert_match(/^TEST2$/, @out) end def test_can_invoke_task_in_toplevel_namespace in_environment("PWD" => "test/data/namespace") do rake "copy" end assert_match(/^COPY$/, @out) end def test_can_invoke_task_in_nested_namespace in_environment("PWD" => "test/data/namespace") do rake "nest:copy" assert_match(/^NEST COPY$/, @out) end end def test_tasks_can_reference_task_in_same_namespace in_environment("PWD" => "test/data/namespace") do rake "nest:xx" assert_match(/^NEST COPY$/m, @out) end end def test_tasks_can_reference_task_in_other_namespaces in_environment("PWD" => "test/data/namespace") do rake "b:run" assert_match(/^IN A\nIN B$/m, @out) end end def test_anonymous_tasks_can_be_invoked_indirectly in_environment("PWD" => "test/data/namespace") do rake "anon" assert_match(/^ANON COPY$/m, @out) end end def test_rake_namespace_refers_to_toplevel in_environment("PWD" => "test/data/namespace") do rake "very:nested:run" assert_match(/^COPY$/m, @out) end end def test_file_task_are_not_scoped_by_namespaces in_environment("PWD" => "test/data/namespace") do rake "xyz.rb" assert_match(/^XYZ1\nXYZ2$/m, @out) end end def test_rake_returns_status_error_values in_environment("PWD" => "test/data/statusreturn") do rake "exit5" assert_status(5) end end def test_rake_returns_no_status_error_on_normal_exit in_environment("PWD" => "test/data/statusreturn") do rake "normal" assert_status(0) end end private def remove_chaining_files %w(play.scpt play.app base).each do |fn| FileUtils.rm_f File.join("test/data/chains", fn) end end class << self def format_command @format_command ||= lambda { |ruby_options, rake_path, options| "ruby #{ruby_options} #{rake_path} #{options}" } end def format_command=(fmt_command) @format_command = fmt_command end end def rake(*option_list) options = option_list.join(' ') shell = Session::Shell.new command = self.class.format_command[@ruby_options, @rake_path, options] puts "COMMAND: [#{command}]" if @verbose @out, @err = shell.execute command @status = shell.exit_status puts "STATUS: [#{@status}]" if @verbose puts "OUTPUT: [#{@out}]" if @verbose puts "ERROR: [#{@err}]" if @verbose puts "PWD: [#{Dir.pwd}]" if @verbose shell.close end def assert_status(expected_status=0) assert_equal expected_status, @status end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_test_task.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_test_task.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake/testtask' class TestTestTask < Test::Unit::TestCase include Rake include TestMethods def setup Task.clear ENV.delete('TEST') end def teardown FileUtils.rm_rf("testdata") end def test_no_task assert ! Task.task_defined?(:test) end def test_defaults tt = Rake::TestTask.new do |t| end assert_not_nil tt assert_equal :test, tt.name assert_equal ['lib'], tt.libs assert_equal 'test/test*.rb', tt.pattern assert_equal false, tt.verbose assert Task.task_defined?(:test) end def test_non_defaults tt = Rake::TestTask.new(:example) do |t| t.libs = ['src', 'ext'] t.pattern = 'test/tc_*.rb' t.verbose = true end assert_not_nil tt assert_equal :example, tt.name assert_equal ['src', 'ext'], tt.libs assert_equal 'test/tc_*.rb', tt.pattern assert_equal true, tt.verbose assert Task.task_defined?(:example) end def test_pattern tt = Rake::TestTask.new do |t| t.pattern = '*.rb' end assert_equal ['install.rb'], tt.file_list.to_a end def test_env_test ENV['TEST'] = 'testfile.rb' tt = Rake::TestTask.new do |t| t.pattern = '*' end assert_equal ["testfile.rb"], tt.file_list.to_a end def test_test_files tt = Rake::TestTask.new do |t| t.test_files = FileList['a.rb', 'b.rb'] end assert_equal ["a.rb", 'b.rb'], tt.file_list.to_a end def test_both_pattern_and_test_files tt = Rake::TestTask.new do |t| t.test_files = FileList['a.rb', 'b.rb'] t.pattern = '*.rb' end assert_equal ['a.rb', 'b.rb', 'install.rb'], tt.file_list.to_a end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/filecreation.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/filecreation.rb
#!/usr/bin/env ruby module FileCreation OLDFILE = "testdata/old" NEWFILE = "testdata/new" def create_timed_files(oldfile, *newfiles) return if File.exist?(oldfile) && newfiles.all? { |newfile| File.exist?(newfile) } old_time = create_file(oldfile) newfiles.each do |newfile| while create_file(newfile) <= old_time sleep(0.1) File.delete(newfile) rescue nil end end end def create_dir(dirname) FileUtils.mkdir_p(dirname) unless File.exist?(dirname) File.stat(dirname).mtime end def create_file(name) create_dir(File.dirname(name)) FileUtils.touch(name) unless File.exist?(name) File.stat(name).mtime end def delete_file(name) File.delete(name) rescue nil end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_pathmap.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_pathmap.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' # ==================================================================== class TestPathMap < Test::Unit::TestCase include TestMethods def test_returns_self_with_no_args assert_equal "abc.rb", "abc.rb".pathmap end def test_s_returns_file_separator sep = File::ALT_SEPARATOR || File::SEPARATOR assert_equal sep, "abc.rb".pathmap("%s") assert_equal sep, "".pathmap("%s") assert_equal "a#{sep}b", "a/b".pathmap("%d%s%f") end def test_f_returns_basename assert_equal "abc.rb", "abc.rb".pathmap("%f") assert_equal "abc.rb", "this/is/a/dir/abc.rb".pathmap("%f") assert_equal "abc.rb", "/this/is/a/dir/abc.rb".pathmap("%f") end def test_n_returns_basename_without_extension assert_equal "abc", "abc.rb".pathmap("%n") assert_equal "abc", "abc".pathmap("%n") assert_equal "abc", "this/is/a/dir/abc.rb".pathmap("%n") assert_equal "abc", "/this/is/a/dir/abc.rb".pathmap("%n") assert_equal "abc", "/this/is/a/dir/abc".pathmap("%n") end def test_d_returns_dirname assert_equal ".", "abc.rb".pathmap("%d") assert_equal "/", "/abc".pathmap("%d") assert_equal "this/is/a/dir", "this/is/a/dir/abc.rb".pathmap("%d") assert_equal "/this/is/a/dir", "/this/is/a/dir/abc.rb".pathmap("%d") end def test_9d_returns_partial_dirname assert_equal "this/is", "this/is/a/dir/abc.rb".pathmap("%2d") assert_equal "this", "this/is/a/dir/abc.rb".pathmap("%1d") assert_equal ".", "this/is/a/dir/abc.rb".pathmap("%0d") assert_equal "dir", "this/is/a/dir/abc.rb".pathmap("%-1d") assert_equal "a/dir", "this/is/a/dir/abc.rb".pathmap("%-2d") assert_equal "this/is/a/dir", "this/is/a/dir/abc.rb".pathmap("%100d") assert_equal "this/is/a/dir", "this/is/a/dir/abc.rb".pathmap("%-100d") end def test_x_returns_extension assert_equal "", "abc".pathmap("%x") assert_equal ".rb", "abc.rb".pathmap("%x") assert_equal ".rb", "abc.xyz.rb".pathmap("%x") assert_equal "", ".depends".pathmap("%x") assert_equal "", "dir/.depends".pathmap("%x") end def test_X_returns_everything_but_extension assert_equal "abc", "abc".pathmap("%X") assert_equal "abc", "abc.rb".pathmap("%X") assert_equal "abc.xyz", "abc.xyz.rb".pathmap("%X") assert_equal "ab.xyz", "ab.xyz.rb".pathmap("%X") assert_equal "a.xyz", "a.xyz.rb".pathmap("%X") assert_equal "abc", "abc.rb".pathmap("%X") assert_equal "ab", "ab.rb".pathmap("%X") assert_equal "a", "a.rb".pathmap("%X") assert_equal ".depends", ".depends".pathmap("%X") assert_equal "a/dir/.depends", "a/dir/.depends".pathmap("%X") assert_equal "/.depends", "/.depends".pathmap("%X") end def test_p_returns_entire_pathname assert_equal "abc.rb", "abc.rb".pathmap("%p") assert_equal "this/is/a/dir/abc.rb", "this/is/a/dir/abc.rb".pathmap("%p") assert_equal "/this/is/a/dir/abc.rb", "/this/is/a/dir/abc.rb".pathmap("%p") end def test_dash_returns_empty_string assert_equal "", "abc.rb".pathmap("%-") assert_equal "abc.rb", "abc.rb".pathmap("%X%-%x") end def test_percent_percent_returns_percent assert_equal "a%b", "".pathmap("a%%b") end def test_undefined_percent_causes_error ex = assert_exception(ArgumentError) { "dir/abc.rb".pathmap("%z") } end def test_pattern_returns_substitutions assert_equal "bin/org/osb", "src/org/osb/Xyz.java".pathmap("%{src,bin}d") end def test_pattern_can_use_backreferences assert_equal "dir/hi/is", "dir/this/is".pathmap("%{t(hi)s,\\1}p") end def test_pattern_with_star_replacement_string_uses_block assert_equal "src/ORG/osb", "src/org/osb/Xyz.java".pathmap("%{/org,*}d") { |d| d.upcase } assert_equal "Xyz.java", "src/org/osb/Xyz.java".pathmap("%{.*,*}f") { |f| f.capitalize } end def test_pattern_with_no_replacement_nor_block_substitutes_empty_string assert_equal "bc.rb", "abc.rb".pathmap("%{a}f") end def test_pattern_works_with_certain_valid_operators assert_equal "dir/xbc.rb", "dir/abc.rb".pathmap("%{a,x}p") assert_equal "d1r", "dir/abc.rb".pathmap("%{i,1}d") assert_equal "xbc.rb", "dir/abc.rb".pathmap("%{a,x}f") assert_equal ".Rb", "dir/abc.rb".pathmap("%{r,R}x") assert_equal "xbc", "dir/abc.rb".pathmap("%{a,x}n") end def test_multiple_patterns assert_equal "this/is/b/directory/abc.rb", "this/is/a/dir/abc.rb".pathmap("%{a,b;dir,\\0ectory}p") end def test_partial_directory_selection_works_with_patterns assert_equal "this/is/a/long", "this/is/a/really/long/path/ok.rb".pathmap("%{/really/,/}5d") end def test_pattern_with_invalid_operator ex = assert_exception(ArgumentError) do "abc.xyz".pathmap("%{src,bin}z") end assert_match(/unknown.*pathmap.*spec.*z/i, ex.message) end def test_works_with_windows_separators if File::ALT_SEPARATOR assert_equal "abc", 'dir\abc.rb'.pathmap("%n") assert_equal 'this\is\a\dir', 'this\is\a\dir\abc.rb'.pathmap("%d") end end def test_complex_patterns sep = "".pathmap("%s") assert_equal "dir/abc.rb", "dir/abc.rb".pathmap("%d/%n%x") assert_equal "./abc.rb", "abc.rb".pathmap("%d/%n%x") assert_equal "Your file extension is '.rb'", "dir/abc.rb".pathmap("Your file extension is '%x'") assert_equal "bin/org/onstepback/proj/A.class", "src/org/onstepback/proj/A.java".pathmap("%{src,bin}d/%n.class") assert_equal "src_work/bin/org/onstepback/proj/A.class", "src_work/src/org/onstepback/proj/A.java".pathmap('%{\bsrc\b,bin}X.class') assert_equal ".depends.bak", ".depends".pathmap("%X.bak") assert_equal "d#{sep}a/b/c#{sep}file.txt", "a/b/c/d/file.txt".pathmap("%-1d%s%3d%s%f") end end class TestPathMapExplode < Test::Unit::TestCase def setup String.class_eval { public :pathmap_explode } end def teardown String.class_eval { protected :pathmap_explode } end def test_explode assert_equal ['a'], 'a'.pathmap_explode assert_equal ['a', 'b'], 'a/b'.pathmap_explode assert_equal ['a', 'b', 'c'], 'a/b/c'.pathmap_explode assert_equal ['/', 'a'], '/a'.pathmap_explode assert_equal ['/', 'a', 'b'], '/a/b'.pathmap_explode assert_equal ['/', 'a', 'b', 'c'], '/a/b/c'.pathmap_explode if File::ALT_SEPARATOR assert_equal ['c:.', 'a'], 'c:a'.pathmap_explode assert_equal ['c:.', 'a', 'b'], 'c:a/b'.pathmap_explode assert_equal ['c:.', 'a', 'b', 'c'], 'c:a/b/c'.pathmap_explode assert_equal ['c:/', 'a'], 'c:/a'.pathmap_explode assert_equal ['c:/', 'a', 'b'], 'c:/a/b'.pathmap_explode assert_equal ['c:/', 'a', 'b', 'c'], 'c:/a/b/c'.pathmap_explode end end end class TestPathMapPartial < Test::Unit::TestCase def test_pathmap_partial @path = "1/2/file" def @path.call(n) pathmap_partial(n) end assert_equal("1", @path.call(1)) assert_equal("1/2", @path.call(2)) assert_equal("1/2", @path.call(3)) assert_equal(".", @path.call(0)) assert_equal("2", @path.call(-1)) assert_equal("1/2", @path.call(-2)) assert_equal("1/2", @path.call(-3)) end end class TestFileListPathMap < Test::Unit::TestCase def test_file_list_supports_pathmap assert_equal ['a', 'b'], FileList['dir/a.rb', 'dir/b.rb'].pathmap("%n") end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_file_task.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_file_task.rb
#!/usr/bin/env ruby require 'test/unit' require 'fileutils' require 'rake' require 'test/filecreation' require 'test/rake_test_setup' ###################################################################### class TestFileTask < Test::Unit::TestCase include Rake include FileCreation include TestMethods def setup Task.clear @runs = Array.new FileUtils.rm_f NEWFILE FileUtils.rm_f OLDFILE end def test_file_need name = "testdata/dummy" file name ftask = Task[name] assert_equal name.to_s, ftask.name File.delete(ftask.name) rescue nil assert ftask.needed?, "file should be needed" open(ftask.name, "w") { |f| f.puts "HI" } assert_equal nil, ftask.prerequisites.collect{|n| Task[n].timestamp}.max assert ! ftask.needed?, "file should not be needed" File.delete(ftask.name) rescue nil end def test_file_times_new_depends_on_old create_timed_files(OLDFILE, NEWFILE) t1 = Rake.application.intern(FileTask, NEWFILE).enhance([OLDFILE]) t2 = Rake.application.intern(FileTask, OLDFILE) assert ! t2.needed?, "Should not need to build old file" assert ! t1.needed?, "Should not need to rebuild new file because of old" end def test_file_times_old_depends_on_new create_timed_files(OLDFILE, NEWFILE) t1 = Rake.application.intern(FileTask,OLDFILE).enhance([NEWFILE]) t2 = Rake.application.intern(FileTask, NEWFILE) assert ! t2.needed?, "Should not need to build new file" preq_stamp = t1.prerequisites.collect{|t| Task[t].timestamp}.max assert_equal t2.timestamp, preq_stamp assert t1.timestamp < preq_stamp, "T1 should be older" assert t1.needed?, "Should need to rebuild old file because of new" end def test_file_depends_on_task_depend_on_file create_timed_files(OLDFILE, NEWFILE) file NEWFILE => [:obj] do |t| @runs << t.name end task :obj => [OLDFILE] do |t| @runs << t.name end file OLDFILE do |t| @runs << t.name end Task[:obj].invoke Task[NEWFILE].invoke assert ! @runs.include?(NEWFILE) end def test_existing_file_depends_on_non_existing_file create_file(OLDFILE) delete_file(NEWFILE) file NEWFILE file OLDFILE => NEWFILE assert_nothing_raised do Task[OLDFILE].invoke end end # I have currently disabled this test. I'm not convinced that # deleting the file target on failure is always the proper thing to # do. I'm willing to hear input on this topic. def ztest_file_deletes_on_failure task :obj file NEWFILE => [:obj] do |t| FileUtils.touch NEWFILE fail "Ooops" end assert Task[NEWFILE] begin Task[NEWFILE].invoke rescue Exception end assert( ! File.exist?(NEWFILE), "NEWFILE should be deleted") end end ###################################################################### class TestDirectoryTask < Test::Unit::TestCase include Rake def setup rm_rf "testdata", :verbose=>false end def teardown rm_rf "testdata", :verbose=>false end def test_directory desc "DESC" directory "testdata/a/b/c" assert_equal FileCreationTask, Task["testdata"].class assert_equal FileCreationTask, Task["testdata/a"].class assert_equal FileCreationTask, Task["testdata/a/b/c"].class assert_nil Task["testdata"].comment assert_equal "DESC", Task["testdata/a/b/c"].comment assert_nil Task["testdata/a/b"].comment verbose(false) { Task['testdata/a/b'].invoke } assert File.exist?("testdata/a/b") assert ! File.exist?("testdata/a/b/c") end if Rake::Win32.windows? def test_directory_win32 desc "WIN32 DESC" FileUtils.mkdir_p("testdata") Dir.chdir("testdata") do directory 'c:/testdata/a/b/c' assert_equal FileCreationTask, Task['c:/testdata'].class assert_equal FileCreationTask, Task['c:/testdata/a'].class assert_equal FileCreationTask, Task['c:/testdata/a/b/c'].class assert_nil Task['c:/testdata'].comment assert_equal "WIN32 DESC", Task['c:/testdata/a/b/c'].comment assert_nil Task['c:/testdata/a/b'].comment verbose(false) { Task['c:/testdata/a/b'].invoke } assert File.exist?('c:/testdata/a/b') assert ! File.exist?('c:/testdata/a/b/c') end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_makefile_loader.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_makefile_loader.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' require 'rake/loaders/makefile' class TestMakefileLoader < Test::Unit::TestCase include Rake def test_parse Task.clear loader = Rake::MakefileLoader.new loader.load("test/data/sample.mf") %w(a b c d).each do |t| assert Task.task_defined?(t), "#{t} should be a defined task" end assert_equal %w(a1 a2 a3 a4 a5 a6 a7).sort, Task['a'].prerequisites.sort assert_equal %w(b1 b2 b3 b4 b5 b6 b7).sort, Task['b'].prerequisites.sort assert_equal %w(c1).sort, Task['c'].prerequisites.sort assert_equal %w(d1 d2).sort, Task['d'].prerequisites.sort assert_equal %w(e1 f1).sort, Task['e'].prerequisites.sort assert_equal %w(e1 f1).sort, Task['f'].prerequisites.sort assert_equal ["g1", "g 2", "g 3", "g4"].sort, Task['g 0'].prerequisites.sort assert_equal 7, Task.tasks.size end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_top_level_functions.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_top_level_functions.rb
#!/usr/bin/env ruby begin require 'rubygems' rescue LoadError # got no gems end require 'test/unit' require 'flexmock/test_unit' require 'test/capture_stdout' require 'test/rake_test_setup' require 'rake' class TestTopLevelFunctions < Test::Unit::TestCase include CaptureStdout include TestMethods def setup super @app = Rake.application Rake.application = flexmock("app") end def teardown Rake.application = @app super end def test_namespace Rake.application.should_receive(:in_namespace).with("xyz", any).once namespace "xyz" do end end def test_import Rake.application.should_receive(:add_import).with("x").once.ordered Rake.application.should_receive(:add_import).with("y").once.ordered Rake.application.should_receive(:add_import).with("z").once.ordered import('x', 'y', 'z') end def test_when_writing out = capture_stdout do when_writing("NOTWRITING") do puts "WRITING" end end assert_equal "WRITING\n", out end def test_when_not_writing RakeFileUtils.nowrite_flag = true out = capture_stdout do when_writing("NOTWRITING") do puts "WRITING" end end assert_equal "DRYRUN: NOTWRITING\n", out ensure RakeFileUtils.nowrite_flag = false end def test_missing_constants_task Rake.application.should_receive(:const_warning).with(:Task).once Object.const_missing(:Task) end def test_missing_constants_file_task Rake.application.should_receive(:const_warning).with(:FileTask).once Object.const_missing(:FileTask) end def test_missing_constants_file_creation_task Rake.application.should_receive(:const_warning).with(:FileCreationTask).once Object.const_missing(:FileCreationTask) end def test_missing_constants_rake_app Rake.application.should_receive(:const_warning).with(:RakeApp).once Object.const_missing(:RakeApp) end def test_missing_other_constant assert_exception(NameError) do Object.const_missing(:Xyz) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_fileutils.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_fileutils.rb
#!/usr/bin/env ruby require 'rake' require 'test/unit' require 'test/filecreation' require 'fileutils' require 'stringio' require 'test/rake_test_setup' class TestFileUtils < Test::Unit::TestCase include FileCreation include TestMethods def setup File.chmod(0750,"test/shellcommand.rb") end def teardown FileUtils.rm_rf("testdata") FileUtils::LN_SUPPORTED[0] = true end def test_rm_one_file create_file("testdata/a") FileUtils.rm_rf "testdata/a" assert ! File.exist?("testdata/a") end def test_rm_two_files create_file("testdata/a") create_file("testdata/b") FileUtils.rm_rf ["testdata/a", "testdata/b"] assert ! File.exist?("testdata/a") assert ! File.exist?("testdata/b") end def test_rm_filelist list = Rake::FileList.new << "testdata/a" << "testdata/b" list.each { |fn| create_file(fn) } FileUtils.rm_r list assert ! File.exist?("testdata/a") assert ! File.exist?("testdata/b") end def test_ln create_dir("testdata") open("testdata/a", "w") { |f| f.puts "TEST_LN" } RakeFileUtils.safe_ln("testdata/a", "testdata/b", :verbose => false) assert_equal "TEST_LN\n", open("testdata/b") { |f| f.read } end class BadLink include RakeFileUtils attr_reader :cp_args def initialize(klass) @failure_class = klass end def cp(*args) @cp_args = args end def ln(*args) fail @failure_class, "ln not supported" end public :safe_ln end def test_safe_ln_failover_to_cp_on_standard_error FileUtils::LN_SUPPORTED[0] = true c = BadLink.new(StandardError) c.safe_ln "a", "b" assert_equal ['a', 'b'], c.cp_args c.safe_ln "x", "y" assert_equal ['x', 'y'], c.cp_args end def test_safe_ln_failover_to_cp_on_not_implemented_error FileUtils::LN_SUPPORTED[0] = true c = BadLink.new(NotImplementedError) c.safe_ln "a", "b" assert_equal ['a', 'b'], c.cp_args end def test_safe_ln_fails_on_script_error FileUtils::LN_SUPPORTED[0] = true c = BadLink.new(ScriptError) assert_exception(ScriptError) do c.safe_ln "a", "b" end end def test_verbose verbose true assert_equal true, verbose verbose false assert_equal false, verbose verbose(true) { assert_equal true, verbose } assert_equal false, verbose end def test_nowrite nowrite true assert_equal true, nowrite nowrite false assert_equal false, nowrite nowrite(true){ assert_equal true, nowrite } assert_equal false, nowrite end def test_file_utils_methods_are_available_at_top_level create_file("testdata/a") rm_rf "testdata/a" assert ! File.exist?("testdata/a") end def test_fileutils_methods_dont_leak obj = Object.new assert_exception(NoMethodError) { obj.copy } # from FileUtils assert_exception(NoMethodError) { obj.ruby } # from RubyFileUtils end def test_sh verbose(false) { sh %{ruby test/shellcommand.rb} } assert true, "should not fail" end # If the :sh method is invoked directly from a test unit instance # (under mini/test), the mini/test version of fail is invoked rather # than the kernel version of fail. So we run :sh from within a # non-test class to avoid the problem. class Sh include FileUtils def run(*args) sh(*args) end def self.run(*args) new.run(*args) end end def test_sh_with_a_single_string_argument ENV['RAKE_TEST_SH'] = 'someval' verbose(false) { sh %{ruby test/check_expansion.rb #{env_var} someval} } end def test_sh_with_multiple_arguments ENV['RAKE_TEST_SH'] = 'someval' verbose(false) { Sh.run 'ruby', 'test/check_no_expansion.rb', env_var, 'someval' } end def test_sh_failure assert_exception(RuntimeError) { verbose(false) { Sh.run %{ruby test/shellcommand.rb 1} } } end def test_sh_special_handling count = 0 verbose(false) { sh(%{ruby test/shellcommand.rb}) do |ok, res| assert(ok) assert_equal 0, res.exitstatus count += 1 end sh(%{ruby test/shellcommand.rb 1}) do |ok, res| assert(!ok) assert_equal 1, res.exitstatus count += 1 end } assert_equal 2, count, "Block count should be 2" end def test_sh_noop verbose(false) { sh %{test/shellcommand.rb 1}, :noop=>true } assert true, "should not fail" end def test_sh_bad_option ex = assert_exception(ArgumentError) { verbose(false) { sh %{test/shellcommand.rb}, :bad_option=>true } } assert_match(/bad_option/, ex.message) end def test_sh_verbose out = redirect_stderr { verbose(true) { sh %{test/shellcommand.rb}, :noop=>true } } assert_match(/^test\/shellcommand\.rb$/, out) end def test_sh_no_verbose out = redirect_stderr { verbose(false) { sh %{test/shellcommand.rb}, :noop=>true } } assert_equal '', out end def test_ruby_with_a_single_string_argument ENV['RAKE_TEST_SH'] = 'someval' verbose(false) { ruby %{test/check_expansion.rb #{env_var} someval} } end def test_ruby_with_multiple_arguments ENV['RAKE_TEST_SH'] = 'someval' verbose(false) { ruby 'test/check_no_expansion.rb', env_var, 'someval' } end def test_split_all assert_equal ['a'], RakeFileUtils.split_all('a') assert_equal ['..'], RakeFileUtils.split_all('..') assert_equal ['/'], RakeFileUtils.split_all('/') assert_equal ['a', 'b'], RakeFileUtils.split_all('a/b') assert_equal ['/', 'a', 'b'], RakeFileUtils.split_all('/a/b') assert_equal ['..', 'a', 'b'], RakeFileUtils.split_all('../a/b') end private def redirect_stderr old_err = $stderr $stderr = StringIO.new yield $stderr.string ensure $stderr = old_err end def windows? ! File::ALT_SEPARATOR.nil? end def env_var windows? ? '%RAKE_TEST_SH%' : '$RAKE_TEST_SH' end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/check_no_expansion.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/check_no_expansion.rb
if ARGV[0] != ARGV[1] exit 0 else exit 1 end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_extension.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_extension.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' require 'stringio' ###################################################################### class TestExtension < Test::Unit::TestCase module Redirect def error_redirect old_err = $stderr result = StringIO.new $stderr = result yield result ensure $stderr = old_err end end class Sample extend Redirect def duplicate_method :original end OK_ERRS = error_redirect do rake_extension("a") do def ok_method end end end DUP_ERRS = error_redirect do rake_extension("duplicate_method") do def duplicate_method :override end end end end def test_methods_actually_exist sample = Sample.new sample.ok_method sample.duplicate_method end def test_no_warning_when_defining_ok_method assert_equal "", Sample::OK_ERRS.string end def test_extension_complains_when_a_method_that_is_present assert_match(/warning:/i, Sample::DUP_ERRS.string) assert_match(/already exists/i, Sample::DUP_ERRS.string) assert_match(/duplicate_method/i, Sample::DUP_ERRS.string) assert_equal :original, Sample.new.duplicate_method end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_clean.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_clean.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake/clean' class TestClean < Test::Unit::TestCase include Rake def test_clean assert Task['clean'], "Should define clean" assert Task['clobber'], "Should define clobber" assert Task['clobber'].prerequisites.include?("clean"), "Clobber should require clean" end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_multitask.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/test_multitask.rb
#!/usr/bin/env ruby require 'test/unit' require 'rake' ###################################################################### class TestMultiTask < Test::Unit::TestCase include Rake def setup Task.clear @runs = Array.new end def test_running_multitasks task :a do 3.times do |i| @runs << "A#{i}"; sleep 0.01; end end task :b do 3.times do |i| @runs << "B#{i}"; sleep 0.01; end end multitask :both => [:a, :b] Task[:both].invoke assert_equal 6, @runs.size assert @runs.index("A0") < @runs.index("A1") assert @runs.index("A1") < @runs.index("A2") assert @runs.index("B0") < @runs.index("B1") assert @runs.index("B1") < @runs.index("B2") end def test_all_multitasks_wait_on_slow_prerequisites task :slow do 3.times do |i| @runs << "S#{i}"; sleep 0.05 end end task :a => [:slow] do 3.times do |i| @runs << "A#{i}"; sleep 0.01 end end task :b => [:slow] do 3.times do |i| @runs << "B#{i}"; sleep 0.01 end end multitask :both => [:a, :b] Task[:both].invoke assert_equal 9, @runs.size assert @runs.index("S0") < @runs.index("S1") assert @runs.index("S1") < @runs.index("S2") assert @runs.index("S2") < @runs.index("A0") assert @runs.index("S2") < @runs.index("B0") assert @runs.index("A0") < @runs.index("A1") assert @runs.index("A1") < @runs.index("A2") assert @runs.index("B0") < @runs.index("B1") assert @runs.index("B1") < @runs.index("B2") end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/check_expansion.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/check_expansion.rb
if ARGV[0] != ARGV[1] exit 1 else exit 0 end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/contrib/test_sys.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/contrib/test_sys.rb
#!/usr/bin/env ruby require 'test/unit' require 'test/filecreation' require 'rake/contrib/sys' class TestSys < Test::Unit::TestCase include FileCreation # def test_delete # create_file("testdata/a") # Sys.delete_all("testdata/a") # assert ! File.exist?("testdata/a") # end # def test_copy # create_file("testdata/a") # Sys.copy("testdata/a", "testdata/b") # assert File.exist?("testdata/b") # end # def test_for_files # test_files = ["testdata/a.pl", "testdata/c.pl", "testdata/b.rb"] # test_files.each { |fn| create_file(fn) } # list = [] # Sys.for_files("testdata/*.pl", "testdata/*.rb") { |fn| # list << fn # } # assert_equal test_files.sort, list.sort # end # def test_indir # here = Dir.pwd # Sys.makedirs("testdata/dir") # assert_equal "#{here}/testdata/dir", Sys.indir("testdata/dir") { Dir.pwd } # assert_equal here, Dir.pwd # end def test_split_all assert_equal ['a'], Sys.split_all('a') assert_equal ['..'], Sys.split_all('..') assert_equal ['/'], Sys.split_all('/') assert_equal ['a', 'b'], Sys.split_all('a/b') assert_equal ['/', 'a', 'b'], Sys.split_all('/a/b') assert_equal ['..', 'a', 'b'], Sys.split_all('../a/b') end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/data/rakelib/test1.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/data/rakelib/test1.rb
task :default do puts "TEST1" end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/data/rbext/rakefile.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/test/data/rbext/rakefile.rb
task :default do puts "OK" end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb
#!/usr/bin/env ruby #-- # Copyright 2003, 2004, 2005, 2006, 2007, 2008 by Jim Weirich (jim@weirichhouse.org) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. #++ # # = Rake -- Ruby Make # # This is the main file for the Rake application. Normally it is referenced # as a library via a require statement, but it can be distributed # independently as an application. RAKEVERSION = '0.8.7' require 'rbconfig' require 'fileutils' require 'singleton' require 'monitor' require 'optparse' require 'ostruct' require 'rake/win32' $trace = false ###################################################################### # Rake extensions to Module. # class Module # Check for an existing method in the current class before extending. IF # the method already exists, then a warning is printed and the extension is # not added. Otherwise the block is yielded and any definitions in the # block will take effect. # # Usage: # # class String # rake_extension("xyz") do # def xyz # ... # end # end # end # def rake_extension(method) if method_defined?(method) $stderr.puts "WARNING: Possible conflict with Rake extension: #{self}##{method} already exists" else yield end end end # module Module ###################################################################### # User defined methods to be added to String. # class String rake_extension("ext") do # Replace the file extension with +newext+. If there is no extension on # the string, append the new extension to the end. If the new extension # is not given, or is the empty string, remove any existing extension. # # +ext+ is a user added method for the String class. def ext(newext='') return self.dup if ['.', '..'].include? self if newext != '' newext = (newext =~ /^\./) ? newext : ("." + newext) end self.chomp(File.extname(self)) << newext end end rake_extension("pathmap") do # Explode a path into individual components. Used by +pathmap+. def pathmap_explode head, tail = File.split(self) return [self] if head == self return [tail] if head == '.' || tail == '/' return [head, tail] if head == '/' return head.pathmap_explode + [tail] end protected :pathmap_explode # Extract a partial path from the path. Include +n+ directories from the # front end (left hand side) if +n+ is positive. Include |+n+| # directories from the back end (right hand side) if +n+ is negative. def pathmap_partial(n) dirs = File.dirname(self).pathmap_explode partial_dirs = if n > 0 dirs[0...n] elsif n < 0 dirs.reverse[0...-n].reverse else "." end File.join(partial_dirs) end protected :pathmap_partial # Preform the pathmap replacement operations on the given path. The # patterns take the form 'pat1,rep1;pat2,rep2...'. def pathmap_replace(patterns, &block) result = self patterns.split(';').each do |pair| pattern, replacement = pair.split(',') pattern = Regexp.new(pattern) if replacement == '*' && block_given? result = result.sub(pattern, &block) elsif replacement result = result.sub(pattern, replacement) else result = result.sub(pattern, '') end end result end protected :pathmap_replace # Map the path according to the given specification. The specification # controls the details of the mapping. The following special patterns are # recognized: # # * <b>%p</b> -- The complete path. # * <b>%f</b> -- The base file name of the path, with its file extension, # but without any directories. # * <b>%n</b> -- The file name of the path without its file extension. # * <b>%d</b> -- The directory list of the path. # * <b>%x</b> -- The file extension of the path. An empty string if there # is no extension. # * <b>%X</b> -- Everything *but* the file extension. # * <b>%s</b> -- The alternate file separater if defined, otherwise use # the standard file separator. # * <b>%%</b> -- A percent sign. # # The %d specifier can also have a numeric prefix (e.g. '%2d'). If the # number is positive, only return (up to) +n+ directories in the path, # starting from the left hand side. If +n+ is negative, return (up to) # |+n+| directories from the right hand side of the path. # # Examples: # # 'a/b/c/d/file.txt'.pathmap("%2d") => 'a/b' # 'a/b/c/d/file.txt'.pathmap("%-2d") => 'c/d' # # Also the %d, %p, %f, %n, %x, and %X operators can take a # pattern/replacement argument to perform simple string substititions on a # particular part of the path. The pattern and replacement are speparated # by a comma and are enclosed by curly braces. The replacement spec comes # after the % character but before the operator letter. (e.g. # "%{old,new}d"). Muliple replacement specs should be separated by # semi-colons (e.g. "%{old,new;src,bin}d"). # # Regular expressions may be used for the pattern, and back refs may be # used in the replacement text. Curly braces, commas and semi-colons are # excluded from both the pattern and replacement text (let's keep parsing # reasonable). # # For example: # # "src/org/onestepback/proj/A.java".pathmap("%{^src,bin}X.class") # # returns: # # "bin/org/onestepback/proj/A.class" # # If the replacement text is '*', then a block may be provided to perform # some arbitrary calculation for the replacement. # # For example: # # "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext| # ext.downcase # } # # Returns: # # "/path/to/file.txt" # def pathmap(spec=nil, &block) return self if spec.nil? result = '' spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag| case frag when '%f' result << File.basename(self) when '%n' result << File.basename(self).ext when '%d' result << File.dirname(self) when '%x' result << File.extname(self) when '%X' result << self.ext when '%p' result << self when '%s' result << (File::ALT_SEPARATOR || File::SEPARATOR) when '%-' # do nothing when '%%' result << "%" when /%(-?\d+)d/ result << pathmap_partial($1.to_i) when /^%\{([^}]*)\}(\d*[dpfnxX])/ patterns, operator = $1, $2 result << pathmap('%' + operator).pathmap_replace(patterns, &block) when /^%/ fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'" else result << frag end end result end end end # class String ############################################################################## module Rake # Errors ----------------------------------------------------------- # Error indicating an ill-formed task declaration. class TaskArgumentError < ArgumentError end # Error indicating a recursion overflow error in task selection. class RuleRecursionOverflowError < StandardError def initialize(*args) super @targets = [] end def add_target(target) @targets << target end def message super + ": [" + @targets.reverse.join(' => ') + "]" end end # -------------------------------------------------------------------------- # Rake module singleton methods. # class << self # Current Rake Application def application @application ||= Rake::Application.new end # Set the current Rake application object. def application=(app) @application = app end # Return the original directory where the Rake application was started. def original_dir application.original_dir end end #################################################################### # Mixin for creating easily cloned objects. # module Cloneable # Clone an object by making a new object and setting all the instance # variables to the same values. def dup sibling = self.class.new instance_variables.each do |ivar| value = self.instance_variable_get(ivar) new_value = value.clone rescue value sibling.instance_variable_set(ivar, new_value) end sibling.taint if tainted? sibling end def clone sibling = dup sibling.freeze if frozen? sibling end end #################################################################### # Exit status class for times the system just gives us a nil. class PseudoStatus attr_reader :exitstatus def initialize(code=0) @exitstatus = code end def to_i @exitstatus << 8 end def >>(n) to_i >> n end def stopped? false end def exited? true end end #################################################################### # TaskAguments manage the arguments passed to a task. # class TaskArguments include Enumerable attr_reader :names # Create a TaskArgument object with a list of named arguments # (given by :names) and a set of associated values (given by # :values). :parent is the parent argument object. def initialize(names, values, parent=nil) @names = names @parent = parent @hash = {} names.each_with_index { |name, i| @hash[name.to_sym] = values[i] unless values[i].nil? } end # Create a new argument scope using the prerequisite argument # names. def new_scope(names) values = names.collect { |n| self[n] } self.class.new(names, values, self) end # Find an argument value by name or index. def [](index) lookup(index.to_sym) end # Specify a hash of default values for task arguments. Use the # defaults only if there is no specific value for the given # argument. def with_defaults(defaults) @hash = defaults.merge(@hash) end def each(&block) @hash.each(&block) end def method_missing(sym, *args, &block) lookup(sym.to_sym) end def to_hash @hash end def to_s @hash.inspect end def inspect to_s end protected def lookup(name) if @hash.has_key?(name) @hash[name] elsif ENV.has_key?(name.to_s) ENV[name.to_s] elsif ENV.has_key?(name.to_s.upcase) ENV[name.to_s.upcase] elsif @parent @parent.lookup(name) end end end EMPTY_TASK_ARGS = TaskArguments.new([], []) #################################################################### # InvocationChain tracks the chain of task invocations to detect # circular dependencies. class InvocationChain def initialize(value, tail) @value = value @tail = tail end def member?(obj) @value == obj || @tail.member?(obj) end def append(value) if member?(value) fail RuntimeError, "Circular dependency detected: #{to_s} => #{value}" end self.class.new(value, self) end def to_s "#{prefix}#{@value}" end def self.append(value, chain) chain.append(value) end private def prefix "#{@tail.to_s} => " end class EmptyInvocationChain def member?(obj) false end def append(value) InvocationChain.new(value, self) end def to_s "TOP" end end EMPTY = EmptyInvocationChain.new end # class InvocationChain end # module Rake module Rake ########################################################################### # A Task is the basic unit of work in a Rakefile. Tasks have associated # actions (possibly more than one) and a list of prerequisites. When # invoked, a task will first ensure that all of its prerequisites have an # opportunity to run and then it will execute its own actions. # # Tasks are not usually created directly using the new method, but rather # use the +file+ and +task+ convenience methods. # class Task # List of prerequisites for a task. attr_reader :prerequisites # List of actions attached to a task. attr_reader :actions # Application owning this task. attr_accessor :application # Comment for this task. Restricted to a single line of no more than 50 # characters. attr_reader :comment # Full text of the (possibly multi-line) comment. attr_reader :full_comment # Array of nested namespaces names used for task lookup by this task. attr_reader :scope # Return task name def to_s name end def inspect "<#{self.class} #{name} => [#{prerequisites.join(', ')}]>" end # List of sources for task. attr_writer :sources def sources @sources ||= [] end # First source from a rule (nil if no sources) def source @sources.first if defined?(@sources) end # Create a task named +task_name+ with no actions or prerequisites. Use # +enhance+ to add actions and prerequisites. def initialize(task_name, app) @name = task_name.to_s @prerequisites = [] @actions = [] @already_invoked = false @full_comment = nil @comment = nil @lock = Monitor.new @application = app @scope = app.current_scope @arg_names = nil end # Enhance a task with prerequisites or actions. Returns self. def enhance(deps=nil, &block) @prerequisites |= deps if deps @actions << block if block_given? self end # Name of the task, including any namespace qualifiers. def name @name.to_s end # Name of task with argument list description. def name_with_args # :nodoc: if arg_description "#{name}#{arg_description}" else name end end # Argument description (nil if none). def arg_description # :nodoc: @arg_names ? "[#{(arg_names || []).join(',')}]" : nil end # Name of arguments for this task. def arg_names @arg_names || [] end # Reenable the task, allowing its tasks to be executed if the task # is invoked again. def reenable @already_invoked = false end # Clear the existing prerequisites and actions of a rake task. def clear clear_prerequisites clear_actions self end # Clear the existing prerequisites of a rake task. def clear_prerequisites prerequisites.clear self end # Clear the existing actions on a rake task. def clear_actions actions.clear self end # Invoke the task if it is needed. Prerequites are invoked first. def invoke(*args) task_args = TaskArguments.new(arg_names, args) invoke_with_call_chain(task_args, InvocationChain::EMPTY) end # Same as invoke, but explicitly pass a call chain to detect # circular dependencies. def invoke_with_call_chain(task_args, invocation_chain) # :nodoc: new_chain = InvocationChain.append(self, invocation_chain) @lock.synchronize do if application.options.trace puts "** Invoke #{name} #{format_trace_flags}" end return if @already_invoked @already_invoked = true invoke_prerequisites(task_args, new_chain) execute(task_args) if needed? end end protected :invoke_with_call_chain # Invoke all the prerequisites of a task. def invoke_prerequisites(task_args, invocation_chain) # :nodoc: @prerequisites.each { |n| prereq = application[n, @scope] prereq_args = task_args.new_scope(prereq.arg_names) prereq.invoke_with_call_chain(prereq_args, invocation_chain) } end # Format the trace flags for display. def format_trace_flags flags = [] flags << "first_time" unless @already_invoked flags << "not_needed" unless needed? flags.empty? ? "" : "(" + flags.join(", ") + ")" end private :format_trace_flags # Execute the actions associated with this task. def execute(args=nil) args ||= EMPTY_TASK_ARGS if application.options.dryrun puts "** Execute (dry run) #{name}" return end if application.options.trace puts "** Execute #{name}" end application.enhance_with_matching_rule(name) if @actions.empty? @actions.each do |act| case act.arity when 1 act.call(self) else act.call(self, args) end end end # Is this task needed? def needed? true end # Timestamp for this task. Basic tasks return the current time for their # time stamp. Other tasks can be more sophisticated. def timestamp @prerequisites.collect { |p| application[p].timestamp }.max || Time.now end # Add a description to the task. The description can consist of an option # argument list (enclosed brackets) and an optional comment. def add_description(description) return if ! description comment = description.strip add_comment(comment) if comment && ! comment.empty? end # Writing to the comment attribute is the same as adding a description. def comment=(description) add_description(description) end # Add a comment to the task. If a comment alread exists, separate # the new comment with " / ". def add_comment(comment) if @full_comment @full_comment << " / " else @full_comment = '' end @full_comment << comment if @full_comment =~ /\A([^.]+?\.)( |$)/ @comment = $1 else @comment = @full_comment end end private :add_comment # Set the names of the arguments for this task. +args+ should be # an array of symbols, one for each argument name. def set_arg_names(args) @arg_names = args.map { |a| a.to_sym } end # Return a string describing the internal state of a task. Useful for # debugging. def investigation result = "------------------------------\n" result << "Investigating #{name}\n" result << "class: #{self.class}\n" result << "task needed: #{needed?}\n" result << "timestamp: #{timestamp}\n" result << "pre-requisites: \n" prereqs = @prerequisites.collect {|name| application[name]} prereqs.sort! {|a,b| a.timestamp <=> b.timestamp} prereqs.each do |p| result << "--#{p.name} (#{p.timestamp})\n" end latest_prereq = @prerequisites.collect{|n| application[n].timestamp}.max result << "latest-prerequisite time: #{latest_prereq}\n" result << "................................\n\n" return result end # ---------------------------------------------------------------- # Rake Module Methods # class << self # Clear the task list. This cause rake to immediately forget all the # tasks that have been assigned. (Normally used in the unit tests.) def clear Rake.application.clear end # List of all defined tasks. def tasks Rake.application.tasks end # Return a task with the given name. If the task is not currently # known, try to synthesize one from the defined rules. If no rules are # found, but an existing file matches the task name, assume it is a file # task with no dependencies or actions. def [](task_name) Rake.application[task_name] end # TRUE if the task name is already defined. def task_defined?(task_name) Rake.application.lookup(task_name) != nil end # Define a task given +args+ and an option block. If a rule with the # given name already exists, the prerequisites and actions are added to # the existing task. Returns the defined task. def define_task(*args, &block) Rake.application.define_task(self, *args, &block) end # Define a rule for synthesizing tasks. def create_rule(*args, &block) Rake.application.create_rule(*args, &block) end # Apply the scope to the task name according to the rules for # this kind of task. Generic tasks will accept the scope as # part of the name. def scope_name(scope, task_name) (scope + [task_name]).join(':') end end # class << Rake::Task end # class Rake::Task ########################################################################### # A FileTask is a task that includes time based dependencies. If any of a # FileTask's prerequisites have a timestamp that is later than the file # represented by this task, then the file must be rebuilt (using the # supplied actions). # class FileTask < Task # Is this file task needed? Yes if it doesn't exist, or if its time stamp # is out of date. def needed? ! File.exist?(name) || out_of_date?(timestamp) end # Time stamp for file task. def timestamp if File.exist?(name) File.mtime(name.to_s) else Rake::EARLY end end private # Are there any prerequisites with a later time than the given time stamp? def out_of_date?(stamp) @prerequisites.any? { |n| application[n].timestamp > stamp} end # ---------------------------------------------------------------- # Task class methods. # class << self # Apply the scope to the task name according to the rules for this kind # of task. File based tasks ignore the scope when creating the name. def scope_name(scope, task_name) task_name end end end # class Rake::FileTask ########################################################################### # A FileCreationTask is a file task that when used as a dependency will be # needed if and only if the file has not been created. Once created, it is # not re-triggered if any of its dependencies are newer, nor does trigger # any rebuilds of tasks that depend on it whenever it is updated. # class FileCreationTask < FileTask # Is this file task needed? Yes if it doesn't exist. def needed? ! File.exist?(name) end # Time stamp for file creation task. This time stamp is earlier # than any other time stamp. def timestamp Rake::EARLY end end ########################################################################### # Same as a regular task, but the immediate prerequisites are done in # parallel using Ruby threads. # class MultiTask < Task private def invoke_prerequisites(args, invocation_chain) threads = @prerequisites.collect { |p| Thread.new(p) { |r| application[r].invoke_with_call_chain(args, invocation_chain) } } threads.each { |t| t.join } end end end # module Rake ## ########################################################################### # Task Definition Functions ... # Declare a basic task. # # Example: # task :clobber => [:clean] do # rm_rf "html" # end # def task(*args, &block) Rake::Task.define_task(*args, &block) end # Declare a file task. # # Example: # file "config.cfg" => ["config.template"] do # open("config.cfg", "w") do |outfile| # open("config.template") do |infile| # while line = infile.gets # outfile.puts line # end # end # end # end # def file(*args, &block) Rake::FileTask.define_task(*args, &block) end # Declare a file creation task. # (Mainly used for the directory command). def file_create(args, &block) Rake::FileCreationTask.define_task(args, &block) end # Declare a set of files tasks to create the given directories on demand. # # Example: # directory "testdata/doc" # def directory(dir) Rake.each_dir_parent(dir) do |d| file_create d do |t| mkdir_p t.name if ! File.exist?(t.name) end end end # Declare a task that performs its prerequisites in parallel. Multitasks does # *not* guarantee that its prerequisites will execute in any given order # (which is obvious when you think about it) # # Example: # multitask :deploy => [:deploy_gem, :deploy_rdoc] # def multitask(args, &block) Rake::MultiTask.define_task(args, &block) end # Create a new rake namespace and use it for evaluating the given block. # Returns a NameSpace object that can be used to lookup tasks defined in the # namespace. # # E.g. # # ns = namespace "nested" do # task :run # end # task_run = ns[:run] # find :run in the given namespace. # def namespace(name=nil, &block) Rake.application.in_namespace(name, &block) end # Declare a rule for auto-tasks. # # Example: # rule '.o' => '.c' do |t| # sh %{cc -o #{t.name} #{t.source}} # end # def rule(*args, &block) Rake::Task.create_rule(*args, &block) end # Describe the next rake task. # # Example: # desc "Run the Unit Tests" # task :test => [:build] # runtests # end # def desc(description) Rake.application.last_description = description end # Import the partial Rakefiles +fn+. Imported files are loaded _after_ the # current file is completely loaded. This allows the import statement to # appear anywhere in the importing file, and yet allowing the imported files # to depend on objects defined in the importing file. # # A common use of the import statement is to include files containing # dependency declarations. # # See also the --rakelibdir command line option. # # Example: # import ".depend", "my_rules" # def import(*fns) fns.each do |fn| Rake.application.add_import(fn) end end ############################################################################# # This a FileUtils extension that defines several additional commands to be # added to the FileUtils utility functions. # module FileUtils RUBY_EXT = ((Config::CONFIG['ruby_install_name'] =~ /\.(com|cmd|exe|bat|rb|sh)$/) ? "" : Config::CONFIG['EXEEXT']) RUBY = File.join( Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'] + RUBY_EXT). sub(/.*\s.*/m, '"\&"') OPT_TABLE['sh'] = %w(noop verbose) OPT_TABLE['ruby'] = %w(noop verbose) # Run the system command +cmd+. If multiple arguments are given the command # is not run with the shell (same semantics as Kernel::exec and # Kernel::system). # # Example: # sh %{ls -ltr} # # sh 'ls', 'file with spaces' # # # check exit status after command runs # sh %{grep pattern file} do |ok, res| # if ! ok # puts "pattern not found (status = #{res.exitstatus})" # end # end # def sh(*cmd, &block) options = (Hash === cmd.last) ? cmd.pop : {} unless block_given? show_command = cmd.join(" ") show_command = show_command[0,42] + "..." unless $trace # TODO code application logic heref show_command.length > 45 block = lambda { |ok, status| ok or fail "Command failed with status (#{status.exitstatus}): [#{show_command}]" } end if RakeFileUtils.verbose_flag == :default options[:verbose] = true else options[:verbose] ||= RakeFileUtils.verbose_flag end options[:noop] ||= RakeFileUtils.nowrite_flag rake_check_options options, :noop, :verbose rake_output_message cmd.join(" ") if options[:verbose] unless options[:noop] res = rake_system(*cmd) status = $? status = PseudoStatus.new(1) if !res && status.nil? block.call(res, status) end end def rake_system(*cmd) Rake::AltSystem.system(*cmd) end private :rake_system # Run a Ruby interpreter with the given arguments. # # Example: # ruby %{-pe '$_.upcase!' <README} # def ruby(*args,&block) options = (Hash === args.last) ? args.pop : {} if args.length > 1 then sh(*([RUBY] + args + [options]), &block) else sh("#{RUBY} #{args.first}", options, &block) end end LN_SUPPORTED = [true] # Attempt to do a normal file link, but fall back to a copy if the link # fails. def safe_ln(*args) unless LN_SUPPORTED[0] cp(*args) else begin ln(*args) rescue StandardError, NotImplementedError => ex LN_SUPPORTED[0] = false cp(*args) end end end # Split a file path into individual directory names. # # Example: # split_all("a/b/c") => ['a', 'b', 'c'] # def split_all(path) head, tail = File.split(path) return [tail] if head == '.' || tail == '/' return [head, tail] if head == '/' return split_all(head) + [tail] end end ############################################################################# # RakeFileUtils provides a custom version of the FileUtils methods that # respond to the <tt>verbose</tt> and <tt>nowrite</tt> commands. # module RakeFileUtils include FileUtils class << self attr_accessor :verbose_flag, :nowrite_flag end RakeFileUtils.verbose_flag = :default RakeFileUtils.nowrite_flag = false $fileutils_verbose = true $fileutils_nowrite = false FileUtils::OPT_TABLE.each do |name, opts| default_options = [] if opts.include?(:verbose) || opts.include?("verbose") default_options << ':verbose => RakeFileUtils.verbose_flag' end if opts.include?(:noop) || opts.include?("noop") default_options << ':noop => RakeFileUtils.nowrite_flag' end next if default_options.empty? module_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{name}( *args, &block ) super( *rake_merge_option(args, #{default_options.join(', ')} ), &block) end EOS end # Get/set the verbose flag controlling output from the FileUtils utilities. # If verbose is true, then the utility method is echoed to standard output. # # Examples: # verbose # return the current value of the verbose flag # verbose(v) # set the verbose flag to _v_. # verbose(v) { code } # Execute code with the verbose flag set temporarily to _v_. # # Return to the original value when code is done. def verbose(value=nil) oldvalue = RakeFileUtils.verbose_flag RakeFileUtils.verbose_flag = value unless value.nil? if block_given? begin yield ensure RakeFileUtils.verbose_flag = oldvalue end end RakeFileUtils.verbose_flag end # Get/set the nowrite flag controlling output from the FileUtils utilities. # If verbose is true, then the utility method is echoed to standard output. # # Examples: # nowrite # return the current value of the nowrite flag # nowrite(v) # set the nowrite flag to _v_. # nowrite(v) { code } # Execute code with the nowrite flag set temporarily to _v_. # # Return to the original value when code is done. def nowrite(value=nil) oldvalue = RakeFileUtils.nowrite_flag RakeFileUtils.nowrite_flag = value unless value.nil? if block_given? begin yield ensure RakeFileUtils.nowrite_flag = oldvalue end end oldvalue end # Use this function to prevent protentially destructive ruby code from # running when the :nowrite flag is set. # # Example: # # when_writing("Building Project") do # project.build # end # # The following code will build the project under normal conditions. If the
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/gempackagetask.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/gempackagetask.rb
#!/usr/bin/env ruby # Define a package task library to aid in the definition of GEM # packages. require 'rubygems' require 'rake' require 'rake/packagetask' require 'rubygems/user_interaction' require 'rubygems/builder' module Rake # Create a package based upon a Gem spec. Gem packages, as well as # zip files and tar/gzipped packages can be produced by this task. # # In addition to the Rake targets generated by PackageTask, a # GemPackageTask will also generate the following tasks: # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.gem"</b>] # Create a Ruby GEM package with the given name and version. # # Example using a Ruby GEM spec: # # require 'rubygems' # # spec = Gem::Specification.new do |s| # s.platform = Gem::Platform::RUBY # s.summary = "Ruby based make-like utility." # s.name = 'rake' # s.version = PKG_VERSION # s.requirements << 'none' # s.require_path = 'lib' # s.autorequire = 'rake' # s.files = PKG_FILES # s.description = <<EOF # Rake is a Make-like program implemented in Ruby. Tasks # and dependencies are specified in standard Ruby syntax. # EOF # end # # Rake::GemPackageTask.new(spec) do |pkg| # pkg.need_zip = true # pkg.need_tar = true # end # class GemPackageTask < PackageTask # Ruby GEM spec containing the metadata for this package. The # name, version and package_files are automatically determined # from the GEM spec and don't need to be explicitly provided. attr_accessor :gem_spec # Create a GEM Package task library. Automatically define the gem # if a block is given. If no block is supplied, then +define+ # needs to be called to define the task. def initialize(gem_spec) init(gem_spec) yield self if block_given? define if block_given? end # Initialization tasks without the "yield self" or define # operations. def init(gem) super(gem.name, gem.version) @gem_spec = gem @package_files += gem_spec.files if gem_spec.files end # Create the Rake tasks and actions specified by this # GemPackageTask. (+define+ is automatically called if a block is # given to +new+). def define super task :package => [:gem] desc "Build the gem file #{gem_file}" task :gem => ["#{package_dir}/#{gem_file}"] file "#{package_dir}/#{gem_file}" => [package_dir] + @gem_spec.files do when_writing("Creating GEM") { Gem::Builder.new(gem_spec).build verbose(true) { mv gem_file, "#{package_dir}/#{gem_file}" } } end end def gem_file if @gem_spec.platform == Gem::Platform::RUBY "#{package_name}.gem" else "#{package_name}-#{@gem_spec.platform}.gem" end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/win32.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/win32.rb
module Rake require 'rake/alt_system' # Win 32 interface methods for Rake. Windows specific functionality # will be placed here to collect that knowledge in one spot. module Win32 # Error indicating a problem in locating the home directory on a # Win32 system. class Win32HomeError < RuntimeError end class << self # True if running on a windows system. def windows? AltSystem::WINDOWS end # Run a command line on windows. def rake_system(*cmd) AltSystem.system(*cmd) end # The standard directory containing system wide rake files on # Win 32 systems. Try the following environment variables (in # order): # # * HOME # * HOMEDRIVE + HOMEPATH # * APPDATA # * USERPROFILE # # If the above are not defined, the return nil. def win32_system_dir #:nodoc: win32_shared_path = ENV['HOME'] if win32_shared_path.nil? && ENV['HOMEDRIVE'] && ENV['HOMEPATH'] win32_shared_path = ENV['HOMEDRIVE'] + ENV['HOMEPATH'] end win32_shared_path ||= ENV['APPDATA'] win32_shared_path ||= ENV['USERPROFILE'] raise Win32HomeError, "Unable to determine home path environment variable." if win32_shared_path.nil? or win32_shared_path.empty? normalize(File.join(win32_shared_path, 'Rake')) end # Normalize a win32 path so that the slashes are all forward slashes. def normalize(path) path.gsub(/\\/, '/') end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rdoctask.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rdoctask.rb
#!/usr/bin/env ruby require 'rake' require 'rake/tasklib' module Rake # Create a documentation task that will generate the RDoc files for # a project. # # The RDocTask will create the following targets: # # [<b><em>rdoc</em></b>] # Main task for this RDOC task. # # [<b>:clobber_<em>rdoc</em></b>] # Delete all the rdoc files. This target is automatically # added to the main clobber target. # # [<b>:re<em>rdoc</em></b>] # Rebuild the rdoc files from scratch, even if they are not out # of date. # # Simple Example: # # Rake::RDocTask.new do |rd| # rd.main = "README.rdoc" # rd.rdoc_files.include("README.rdoc", "lib/**/*.rb") # end # # The +rd+ object passed to the block is an RDocTask object. See the # attributes list for the RDocTask class for available customization options. # # == Specifying different task names # # You may wish to give the task a different name, such as if you are # generating two sets of documentation. For instance, if you want to have a # development set of documentation including private methods: # # Rake::RDocTask.new(:rdoc_dev) do |rd| # rd.main = "README.doc" # rd.rdoc_files.include("README.rdoc", "lib/**/*.rb") # rd.options << "--all" # end # # The tasks would then be named :<em>rdoc_dev</em>, :clobber_<em>rdoc_dev</em>, and # :re<em>rdoc_dev</em>. # # If you wish to have completely different task names, then pass a Hash as # first argument. With the <tt>:rdoc</tt>, <tt>:clobber_rdoc</tt> and # <tt>:rerdoc</tt> options, you can customize the task names to your liking. # For example: # # Rake::RDocTask.new(:rdoc => "rdoc", :clobber_rdoc => "rdoc:clean", :rerdoc => "rdoc:force") # # This will create the tasks <tt>:rdoc</tt>, <tt>:rdoc_clean</tt> and # <tt>:rdoc:force</tt>. # class RDocTask < TaskLib # Name of the main, top level task. (default is :rdoc) attr_accessor :name # Name of directory to receive the html output files. (default is "html") attr_accessor :rdoc_dir # Title of RDoc documentation. (defaults to rdoc's default) attr_accessor :title # Name of file to be used as the main, top level file of the # RDoc. (default is none) attr_accessor :main # Name of template to be used by rdoc. (defaults to rdoc's default) attr_accessor :template # List of files to be included in the rdoc generation. (default is []) attr_accessor :rdoc_files # Additional list of options to be passed rdoc. (default is []) attr_accessor :options # Whether to run the rdoc process as an external shell (default is false) attr_accessor :external attr_accessor :inline_source # Create an RDoc task with the given name. See the RDocTask class overview # for documentation. def initialize(name = :rdoc) # :yield: self if name.is_a?(Hash) invalid_options = name.keys.map { |k| k.to_sym } - [:rdoc, :clobber_rdoc, :rerdoc] if !invalid_options.empty? raise ArgumentError, "Invalid option(s) passed to RDocTask.new: #{invalid_options.join(", ")}" end end @name = name @rdoc_files = Rake::FileList.new @rdoc_dir = 'html' @main = nil @title = nil @template = nil @external = false @inline_source = true @options = [] yield self if block_given? define end # Create the tasks defined by this task lib. def define if rdoc_task_name != "rdoc" desc "Build the RDOC HTML Files" else desc "Build the #{rdoc_task_name} HTML Files" end task rdoc_task_name desc "Force a rebuild of the RDOC files" task rerdoc_task_name => [clobber_task_name, rdoc_task_name] desc "Remove rdoc products" task clobber_task_name do rm_r rdoc_dir rescue nil end task :clobber => [clobber_task_name] directory @rdoc_dir task rdoc_task_name => [rdoc_target] file rdoc_target => @rdoc_files + [Rake.application.rakefile] do rm_r @rdoc_dir rescue nil @before_running_rdoc.call if @before_running_rdoc args = option_list + @rdoc_files if @external argstring = args.join(' ') sh %{ruby -Ivendor vendor/rd #{argstring}} else require 'rdoc/rdoc' RDoc::RDoc.new.document(args) end end self end def option_list result = @options.dup result << "-o" << @rdoc_dir result << "--main" << quote(main) if main result << "--title" << quote(title) if title result << "-T" << quote(template) if template result << "--inline-source" if inline_source && !@options.include?("--inline-source") && !@options.include?("-S") result end def quote(str) if @external "'#{str}'" else str end end def option_string option_list.join(' ') end # The block passed to this method will be called just before running the # RDoc generator. It is allowed to modify RDocTask attributes inside the # block. def before_running_rdoc(&block) @before_running_rdoc = block end private def rdoc_target "#{rdoc_dir}/index.html" end def rdoc_task_name case name when Hash (name[:rdoc] || "rdoc").to_s else name.to_s end end def clobber_task_name case name when Hash (name[:clobber_rdoc] || "clobber_rdoc").to_s else "clobber_#{name}" end end def rerdoc_task_name case name when Hash (name[:rerdoc] || "rerdoc").to_s else "re#{name}" end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/clean.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/clean.rb
#!/usr/bin/env ruby # The 'rake/clean' file defines two file lists (CLEAN and CLOBBER) and # two rake tasks (:clean and :clobber). # # [:clean] Clean up the project by deleting scratch files and backup # files. Add files to the CLEAN file list to have the :clean # target handle them. # # [:clobber] Clobber all generated and non-source files in a project. # The task depends on :clean, so all the clean files will # be deleted as well as files in the CLOBBER file list. # The intent of this task is to return a project to its # pristine, just unpacked state. require 'rake' CLEAN = Rake::FileList["**/*~", "**/*.bak", "**/core"] CLEAN.clear_exclude.exclude { |fn| fn.pathmap("%f") == 'core' && File.directory?(fn) } desc "Remove any temporary products." task :clean do CLEAN.each { |fn| rm_r fn rescue nil } end CLOBBER = Rake::FileList.new desc "Remove any generated file." task :clobber => [:clean] do CLOBBER.each { |fn| rm_r fn rescue nil } end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/alt_system.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/alt_system.rb
# # Copyright (c) 2008 James M. Lawrence # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # require 'rbconfig' # # Alternate implementations of system() and backticks `` on Windows # for ruby-1.8 and earlier. # module Rake::AltSystem WINDOWS = Config::CONFIG["host_os"] =~ %r!(msdos|mswin|djgpp|mingw)! class << self def define_module_function(name, &block) define_method(name, &block) module_function(name) end end if WINDOWS and RUBY_VERSION < "1.9.0" RUNNABLE_EXTS = %w[com exe bat cmd] RUNNABLE_PATTERN = %r!\.(#{RUNNABLE_EXTS.join('|')})\Z!i define_module_function :kernel_system, &Kernel.method(:system) define_module_function :kernel_backticks, &Kernel.method(:'`') module_function def repair_command(cmd) "call " + ( if cmd =~ %r!\A\s*\".*?\"! # already quoted cmd elsif match = cmd.match(%r!\A\s*(\S+)!) if match[1] =~ %r!/! # avoid x/y.bat interpretation as x with option /y %Q!"#{match[1]}"! + match.post_match else # a shell command will fail if quoted cmd end else # empty or whitespace cmd end ) end def find_runnable(file) if file =~ RUNNABLE_PATTERN file else RUNNABLE_EXTS.each { |ext| if File.exist?(test = "#{file}.#{ext}") return test end } nil end end def system(cmd, *args) repaired = ( if args.empty? [repair_command(cmd)] elsif runnable = find_runnable(cmd) [File.expand_path(runnable), *args] else # non-existent file [cmd, *args] end ) kernel_system(*repaired) end def backticks(cmd) kernel_backticks(repair_command(cmd)) end define_module_function :'`', &method(:backticks) else # Non-Windows or ruby-1.9+: same as Kernel versions define_module_function :system, &Kernel.method(:system) define_module_function :backticks, &Kernel.method(:'`') define_module_function :'`', &Kernel.method(:'`') end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/testtask.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/testtask.rb
#!/usr/bin/env ruby # Define a task library for running unit tests. require 'rake' require 'rake/tasklib' module Rake # Create a task that runs a set of tests. # # Example: # # Rake::TestTask.new do |t| # t.libs << "test" # t.test_files = FileList['test/test*.rb'] # t.verbose = true # end # # If rake is invoked with a "TEST=filename" command line option, # then the list of test files will be overridden to include only the # filename specified on the command line. This provides an easy way # to run just one test. # # If rake is invoked with a "TESTOPTS=options" command line option, # then the given options are passed to the test process after a # '--'. This allows Test::Unit options to be passed to the test # suite. # # Examples: # # rake test # run tests normally # rake test TEST=just_one_file.rb # run just one test file. # rake test TESTOPTS="-v" # run in verbose mode # rake test TESTOPTS="--runner=fox" # use the fox test runner # class TestTask < TaskLib # Name of test task. (default is :test) attr_accessor :name # List of directories to added to $LOAD_PATH before running the # tests. (default is 'lib') attr_accessor :libs # True if verbose test output desired. (default is false) attr_accessor :verbose # Test options passed to the test suite. An explicit # TESTOPTS=opts on the command line will override this. (default # is NONE) attr_accessor :options # Request that the tests be run with the warning flag set. # E.g. warning=true implies "ruby -w" used to run the tests. attr_accessor :warning # Glob pattern to match test files. (default is 'test/test*.rb') attr_accessor :pattern # Style of test loader to use. Options are: # # * :rake -- Rake provided test loading script (default). # * :testrb -- Ruby provided test loading script. # * :direct -- Load tests using command line loader. # attr_accessor :loader # Array of commandline options to pass to ruby when running test loader. attr_accessor :ruby_opts # Explicitly define the list of test files to be included in a # test. +list+ is expected to be an array of file names (a # FileList is acceptable). If both +pattern+ and +test_files+ are # used, then the list of test files is the union of the two. def test_files=(list) @test_files = list end # Create a testing task. def initialize(name=:test) @name = name @libs = ["lib"] @pattern = nil @options = nil @test_files = nil @verbose = false @warning = false @loader = :rake @ruby_opts = [] yield self if block_given? @pattern = 'test/test*.rb' if @pattern.nil? && @test_files.nil? define end # Create the tasks defined by this task lib. def define lib_path = @libs.join(File::PATH_SEPARATOR) desc "Run tests" + (@name==:test ? "" : " for #{@name}") task @name do run_code = '' RakeFileUtils.verbose(@verbose) do run_code = case @loader when :direct "-e 'ARGV.each{|f| load f}'" when :testrb "-S testrb #{fix}" when :rake rake_loader end @ruby_opts.unshift( "-I\"#{lib_path}\"" ) @ruby_opts.unshift( "-w" ) if @warning ruby @ruby_opts.join(" ") + " \"#{run_code}\" " + file_list.collect { |fn| "\"#{fn}\"" }.join(' ') + " #{option_list}" end end self end def option_list # :nodoc: ENV['TESTOPTS'] || @options || "" end def file_list # :nodoc: if ENV['TEST'] FileList[ ENV['TEST'] ] else result = [] result += @test_files.to_a if @test_files result += FileList[ @pattern ].to_a if @pattern FileList[result] end end def fix # :nodoc: case RUBY_VERSION when '1.8.2' find_file 'rake/ruby182_test_unit_fix' else nil end || '' end def rake_loader # :nodoc: find_file('rake/rake_test_loader') or fail "unable to find rake test loader" end def find_file(fn) # :nodoc: $LOAD_PATH.each do |path| file_path = File.join(path, "#{fn}.rb") return file_path if File.exist? file_path end nil end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/runtest.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/runtest.rb
#!/usr/bin/env ruby require 'test/unit' require 'test/unit/assertions' module Rake include Test::Unit::Assertions def run_tests(pattern='test/test*.rb', log_enabled=false) Dir["#{pattern}"].each { |fn| puts fn if log_enabled begin load fn rescue Exception => ex puts "Error in #{fn}: #{ex.message}" puts ex.backtrace assert false end } end extend self end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/ruby182_test_unit_fix.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/ruby182_test_unit_fix.rb
module Test module Unit module Collector class Dir undef collect_file def collect_file(name, suites, already_gathered) # loadpath = $:.dup dir = File.dirname(File.expand_path(name)) $:.unshift(dir) unless $:.first == dir if(@req) @req.require(name) else require(name) end find_test_cases(already_gathered).each{|t| add_suite(suites, t.suite)} ensure # $:.replace(loadpath) $:.delete_at $:.rindex(dir) end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/packagetask.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/packagetask.rb
#!/usr/bin/env ruby # Define a package task libarary to aid in the definition of # redistributable package files. require 'rake' require 'rake/tasklib' module Rake # Create a packaging task that will package the project into # distributable files (e.g zip archive or tar files). # # The PackageTask will create the following targets: # # [<b>:package</b>] # Create all the requested package files. # # [<b>:clobber_package</b>] # Delete all the package files. This target is automatically # added to the main clobber target. # # [<b>:repackage</b>] # Rebuild the package files from scratch, even if they are not out # of date. # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tgz"</b>] # Create a gzipped tar package (if <em>need_tar</em> is true). # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.gz"</b>] # Create a gzipped tar package (if <em>need_tar_gz</em> is true). # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.bz2"</b>] # Create a bzip2'd tar package (if <em>need_tar_bz2</em> is true). # # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.zip"</b>] # Create a zip package archive (if <em>need_zip</em> is true). # # Example: # # Rake::PackageTask.new("rake", "1.2.3") do |p| # p.need_tar = true # p.package_files.include("lib/**/*.rb") # end # class PackageTask < TaskLib # Name of the package (from the GEM Spec). attr_accessor :name # Version of the package (e.g. '1.3.2'). attr_accessor :version # Directory used to store the package files (default is 'pkg'). attr_accessor :package_dir # True if a gzipped tar file (tgz) should be produced (default is false). attr_accessor :need_tar # True if a gzipped tar file (tar.gz) should be produced (default is false). attr_accessor :need_tar_gz # True if a bzip2'd tar file (tar.bz2) should be produced (default is false). attr_accessor :need_tar_bz2 # True if a zip file should be produced (default is false) attr_accessor :need_zip # List of files to be included in the package. attr_accessor :package_files # Tar command for gzipped or bzip2ed archives. The default is 'tar'. attr_accessor :tar_command # Zip command for zipped archives. The default is 'zip'. attr_accessor :zip_command # Create a Package Task with the given name and version. def initialize(name=nil, version=nil) init(name, version) yield self if block_given? define unless name.nil? end # Initialization that bypasses the "yield self" and "define" step. def init(name, version) @name = name @version = version @package_files = Rake::FileList.new @package_dir = 'pkg' @need_tar = false @need_tar_gz = false @need_tar_bz2 = false @need_zip = false @tar_command = 'tar' @zip_command = 'zip' end # Create the tasks defined by this task library. def define fail "Version required (or :noversion)" if @version.nil? @version = nil if :noversion == @version desc "Build all the packages" task :package desc "Force a rebuild of the package files" task :repackage => [:clobber_package, :package] desc "Remove package products" task :clobber_package do rm_r package_dir rescue nil end task :clobber => [:clobber_package] [ [need_tar, tgz_file, "z"], [need_tar_gz, tar_gz_file, "z"], [need_tar_bz2, tar_bz2_file, "j"] ].each do |(need, file, flag)| if need task :package => ["#{package_dir}/#{file}"] file "#{package_dir}/#{file}" => [package_dir_path] + package_files do chdir(package_dir) do sh %{#{@tar_command} #{flag}cvf #{file} #{package_name}} end end end end if need_zip task :package => ["#{package_dir}/#{zip_file}"] file "#{package_dir}/#{zip_file}" => [package_dir_path] + package_files do chdir(package_dir) do sh %{#{@zip_command} -r #{zip_file} #{package_name}} end end end directory package_dir file package_dir_path => @package_files do mkdir_p package_dir rescue nil @package_files.each do |fn| f = File.join(package_dir_path, fn) fdir = File.dirname(f) mkdir_p(fdir) if !File.exist?(fdir) if File.directory?(fn) mkdir_p(f) else rm_f f safe_ln(fn, f) end end end self end def package_name @version ? "#{@name}-#{@version}" : @name end def package_dir_path "#{package_dir}/#{package_name}" end def tgz_file "#{package_name}.tgz" end def tar_gz_file "#{package_name}.tar.gz" end def tar_bz2_file "#{package_name}.tar.bz2" end def zip_file "#{package_name}.zip" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/tasklib.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/tasklib.rb
#!/usr/bin/env ruby require 'rake' module Rake # Base class for Task Libraries. class TaskLib include Cloneable # Make a symbol by pasting two strings together. # # NOTE: DEPRECATED! This method is kinda stupid. I don't know why # I didn't just use string interpolation. But now other task # libraries depend on this so I can't remove it without breaking # other people's code. So for now it stays for backwards # compatibility. BUT DON'T USE IT. def paste(a,b) # :nodoc: (a.to_s + b.to_s).intern end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/classic_namespace.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/classic_namespace.rb
# The following classes used to be in the top level namespace. # Loading this file enables compatibility with older Rakefile that # referenced Task from the top level. Task = Rake::Task FileTask = Rake::FileTask FileCreationTask = Rake::FileCreationTask RakeApp = Rake::Application
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb
#!/usr/bin/env ruby # Load the test files from the command line. ARGV.each { |f| load f unless f =~ /^-/ }
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/rubyforgepublisher.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/rubyforgepublisher.rb
#!/usr/bin/env ruby require 'rake/contrib/sshpublisher' module Rake class RubyForgePublisher < SshDirPublisher attr_reader :project, :proj_id, :user def initialize(projname, user) super( "#{user}@rubyforge.org", "/var/www/gforge-projects/#{projname}", "html") end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false