Permalink
Browse files

Merge branch 'master' of git://github.com/Sixeight/termtter into Sixe…

…ight
  • Loading branch information...
2 parents 831e64f + 9ba0983 commit 5baa1fc33ca934121132260a3bbe9c1d3950ff2f @ujihisa ujihisa committed Oct 4, 2009
Showing with 733 additions and 353 deletions.
  1. +1 −1 lib/plugins/defaults/command_line.rb
  2. 0 lib/plugins/{ → delete}/april_fool.rb
  3. 0 lib/plugins/{ → delete}/bomb.rb
  4. 0 lib/plugins/{ → delete}/clear.rb
  5. 0 lib/plugins/{ → delete}/confirm.rb
  6. 0 lib/plugins/{ → delete}/english.rb
  7. 0 lib/plugins/{ → delete}/fib_filter.rb
  8. 0 lib/plugins/{ → delete}/fibyou.rb
  9. 0 lib/plugins/{ → delete}/filter.rb
  10. 0 lib/plugins/{ → delete}/graduatter.rb
  11. 0 lib/plugins/{ → delete}/hatebu_and_update.rb
  12. 0 lib/plugins/{ → delete}/history.rb
  13. 0 lib/plugins/{ → delete}/hugeurl.rb
  14. 0 lib/plugins/{ → delete}/jakigan.rb
  15. 0 lib/plugins/{ → delete}/otsune.rb
  16. 0 lib/plugins/{ → delete}/reply.rb
  17. 0 lib/plugins/{ → delete}/reverse.rb
  18. 0 lib/plugins/{ → delete}/scrape.rb
  19. 0 lib/plugins/{ → delete}/storage.rb
  20. 0 lib/plugins/{ → delete}/storage/DB.rb
  21. 0 lib/plugins/{ → delete}/storage/status.rb
  22. 0 lib/plugins/{ → delete}/storage/status_mook.rb
  23. 0 lib/plugins/{ → delete}/typable_id.rb
  24. 0 lib/plugins/{ → delete}/whois.rb
  25. 0 lib/plugins/{ → delete}/yhara_filter.rb
  26. 0 lib/plugins/{ → deprecate}/grass.rb
  27. 0 lib/plugins/{ → deprecate}/hatebu.rb
  28. 0 lib/plugins/{ → deprecate}/l2.rb
  29. 0 lib/plugins/{ → deprecate}/me.rb
  30. 0 lib/plugins/{ → deprecate}/modify_arg_hook_sample.rb
  31. 0 lib/plugins/{ → deprecate}/notify-send.rb
  32. 0 lib/plugins/{ → deprecate}/notify-send2.rb
  33. 0 lib/plugins/{ → deprecate}/notify-send3.rb
  34. 0 lib/plugins/{ → deprecate}/outputz.rb
  35. 0 lib/plugins/{ → deprecate}/pool.rb
  36. 0 lib/plugins/{ → deprecate}/post_exec_hook_sample.rb
  37. 0 lib/plugins/{ → deprecate}/pre_exec_hook_sample.rb
  38. 0 lib/plugins/{ → deprecate}/primes.rb
  39. 0 lib/plugins/{ → deprecate}/protected_filter.rb
  40. 0 lib/plugins/{ → deprecate}/quicklook.rb
  41. 0 lib/plugins/{ → deprecate}/random.rb
  42. 0 lib/plugins/{ → deprecate}/reblog.rb
  43. 0 lib/plugins/{ → deprecate}/reload.rb
  44. 0 lib/plugins/{ → deprecate}/say.rb
  45. 0 lib/plugins/{ → deprecate}/saykanji.rb
  46. 0 lib/plugins/{ → deprecate}/screen-notify.rb
  47. 0 lib/plugins/{ → deprecate}/screen.rb
  48. 0 lib/plugins/{ → deprecate}/search_url.rb
  49. 0 lib/plugins/{ → deprecate}/searchline.rb
  50. 0 lib/plugins/{ → deprecate}/sl.rb
  51. 0 lib/plugins/{ → deprecate}/spam.rb
  52. 0 lib/plugins/{ → deprecate}/tinyurl.rb
  53. 0 lib/plugins/{ → deprecate}/train.rb
  54. 0 lib/plugins/{ → deprecate}/translation.rb
  55. 0 lib/plugins/{ → deprecate}/update_editor.rb
  56. 0 lib/plugins/{ → deprecate}/wassr.rb
  57. 0 lib/plugins/{ → deprecate}/wassr_post.rb
  58. 0 lib/plugins/{ → deprecate}/yhara.rb
  59. 0 lib/plugins/{ → deprecate}/yonda.rb
  60. +1 −1 lib/plugins/paranoid.rb
  61. +2 −3 lib/termtter.rb
  62. +14 −17 lib/termtter/api.rb
  63. +28 −67 lib/termtter/client.rb
  64. +3 −3 lib/termtter/command.rb
  65. +4 −4 lib/termtter/config_setup.rb
  66. +5 −5 lib/termtter/config_template.erb
  67. +0 −41 lib/termtter/connection.rb
  68. +86 −0 lib/termtter/for_windows.rb
  69. +2 −2 lib/termtter/hook.rb
  70. +50 −40 lib/termtter/optparse.rb
  71. +2 −121 lib/termtter/system_extensions.rb
  72. +4 −4 lib/termtter/task.rb
  73. +3 −5 lib/termtter/task_manager.rb
  74. +1 −0 run_termtter.rb
  75. +27 −2 spec/plugins/cool_spec.rb
  76. 0 spec/plugins/{english_spec.rb → english_spec_.rb}
  77. 0 spec/plugins/{filter_spec.rb → filter_spec_.rb}
  78. 0 spec/plugins/{primes_spec.rb → primes_spec_.rb}
  79. 0 spec/plugins/{sl_spec.rb → sl_spec_.rb}
  80. 0 spec/plugins/storage/{DB_spec.rb → DB_spec_.rb}
  81. 0 spec/plugins/storage/{status_spec.rb → status_spec_.rb}
  82. 0 spec/plugins/{whois_spec.rb → whois_spec_.rb}
  83. +5 −0 spec/termtter/active_rubytter_spec.rb
  84. +38 −0 spec/termtter/api_spec.rb
  85. +234 −28 spec/termtter/client_spec.rb
  86. +5 −0 spec/termtter/command_spec.rb
  87. +19 −0 spec/termtter/config_setup_spec.rb
  88. +17 −0 spec/termtter/config_spec.rb
  89. +12 −0 spec/termtter/hook_spec.rb
  90. +64 −9 spec/termtter/optparse_spec.rb
  91. +41 −0 spec/termtter/system_extensions_spec.rb
  92. +54 −0 spec/termtter/task_manager_spec.rb
  93. +11 −0 spec/termtter_spec.rb
View
2 lib/plugins/defaults/command_line.rb
@@ -20,7 +20,7 @@ def start
end
def stop
- @input_thread.kill
+ @input_thread.kill rescue nil
end
def call(command_text)
View
0 lib/plugins/april_fool.rb → lib/plugins/delete/april_fool.rb
File renamed without changes.
View
0 lib/plugins/bomb.rb → lib/plugins/delete/bomb.rb
File renamed without changes.
View
0 lib/plugins/clear.rb → lib/plugins/delete/clear.rb
File renamed without changes.
View
0 lib/plugins/confirm.rb → lib/plugins/delete/confirm.rb
File renamed without changes.
View
0 lib/plugins/english.rb → lib/plugins/delete/english.rb
File renamed without changes.
View
0 lib/plugins/fib_filter.rb → lib/plugins/delete/fib_filter.rb
File renamed without changes.
View
0 lib/plugins/fibyou.rb → lib/plugins/delete/fibyou.rb
File renamed without changes.
View
0 lib/plugins/filter.rb → lib/plugins/delete/filter.rb
File renamed without changes.
View
0 lib/plugins/graduatter.rb → lib/plugins/delete/graduatter.rb
File renamed without changes.
View
0 lib/plugins/hatebu_and_update.rb → lib/plugins/delete/hatebu_and_update.rb
File renamed without changes.
View
0 lib/plugins/history.rb → lib/plugins/delete/history.rb
File renamed without changes.
View
0 lib/plugins/hugeurl.rb → lib/plugins/delete/hugeurl.rb
File renamed without changes.
View
0 lib/plugins/jakigan.rb → lib/plugins/delete/jakigan.rb
File renamed without changes.
View
0 lib/plugins/otsune.rb → lib/plugins/delete/otsune.rb
File renamed without changes.
View
0 lib/plugins/reply.rb → lib/plugins/delete/reply.rb
File renamed without changes.
View
0 lib/plugins/reverse.rb → lib/plugins/delete/reverse.rb
File renamed without changes.
View
0 lib/plugins/scrape.rb → lib/plugins/delete/scrape.rb
File renamed without changes.
View
0 lib/plugins/storage.rb → lib/plugins/delete/storage.rb
File renamed without changes.
View
0 lib/plugins/storage/DB.rb → lib/plugins/delete/storage/DB.rb
File renamed without changes.
View
0 lib/plugins/storage/status.rb → lib/plugins/delete/storage/status.rb
File renamed without changes.
View
0 lib/plugins/storage/status_mook.rb → lib/plugins/delete/storage/status_mook.rb
File renamed without changes.
View
0 lib/plugins/typable_id.rb → lib/plugins/delete/typable_id.rb
File renamed without changes.
View
0 lib/plugins/whois.rb → lib/plugins/delete/whois.rb
File renamed without changes.
View
0 lib/plugins/yhara_filter.rb → lib/plugins/delete/yhara_filter.rb
File renamed without changes.
View
0 lib/plugins/grass.rb → lib/plugins/deprecate/grass.rb
File renamed without changes.
View
0 lib/plugins/hatebu.rb → lib/plugins/deprecate/hatebu.rb
File renamed without changes.
View
0 lib/plugins/l2.rb → lib/plugins/deprecate/l2.rb
File renamed without changes.
View
0 lib/plugins/me.rb → lib/plugins/deprecate/me.rb
File renamed without changes.
View
0 lib/plugins/modify_arg_hook_sample.rb → ...ugins/deprecate/modify_arg_hook_sample.rb
File renamed without changes.
View
0 lib/plugins/notify-send.rb → lib/plugins/deprecate/notify-send.rb
File renamed without changes.
View
0 lib/plugins/notify-send2.rb → lib/plugins/deprecate/notify-send2.rb
File renamed without changes.
View
0 lib/plugins/notify-send3.rb → lib/plugins/deprecate/notify-send3.rb
File renamed without changes.
View
0 lib/plugins/outputz.rb → lib/plugins/deprecate/outputz.rb
File renamed without changes.
View
0 lib/plugins/pool.rb → lib/plugins/deprecate/pool.rb
File renamed without changes.
View
0 lib/plugins/post_exec_hook_sample.rb → ...lugins/deprecate/post_exec_hook_sample.rb
File renamed without changes.
View
0 lib/plugins/pre_exec_hook_sample.rb → ...plugins/deprecate/pre_exec_hook_sample.rb
File renamed without changes.
View
0 lib/plugins/primes.rb → lib/plugins/deprecate/primes.rb
File renamed without changes.
View
0 lib/plugins/protected_filter.rb → lib/plugins/deprecate/protected_filter.rb
File renamed without changes.
View
0 lib/plugins/quicklook.rb → lib/plugins/deprecate/quicklook.rb
File renamed without changes.
View
0 lib/plugins/random.rb → lib/plugins/deprecate/random.rb
File renamed without changes.
View
0 lib/plugins/reblog.rb → lib/plugins/deprecate/reblog.rb
File renamed without changes.
View
0 lib/plugins/reload.rb → lib/plugins/deprecate/reload.rb
File renamed without changes.
View
0 lib/plugins/say.rb → lib/plugins/deprecate/say.rb
File renamed without changes.
View
0 lib/plugins/saykanji.rb → lib/plugins/deprecate/saykanji.rb
File renamed without changes.
View
0 lib/plugins/screen-notify.rb → lib/plugins/deprecate/screen-notify.rb
File renamed without changes.
View
0 lib/plugins/screen.rb → lib/plugins/deprecate/screen.rb
File renamed without changes.
View
0 lib/plugins/search_url.rb → lib/plugins/deprecate/search_url.rb
File renamed without changes.
View
0 lib/plugins/searchline.rb → lib/plugins/deprecate/searchline.rb
File renamed without changes.
View
0 lib/plugins/sl.rb → lib/plugins/deprecate/sl.rb
File renamed without changes.
View
0 lib/plugins/spam.rb → lib/plugins/deprecate/spam.rb
File renamed without changes.
View
0 lib/plugins/tinyurl.rb → lib/plugins/deprecate/tinyurl.rb
File renamed without changes.
View
0 lib/plugins/train.rb → lib/plugins/deprecate/train.rb
File renamed without changes.
View
0 lib/plugins/translation.rb → lib/plugins/deprecate/translation.rb
File renamed without changes.
View
0 lib/plugins/update_editor.rb → lib/plugins/deprecate/update_editor.rb
File renamed without changes.
View
0 lib/plugins/wassr.rb → lib/plugins/deprecate/wassr.rb
File renamed without changes.
View
0 lib/plugins/wassr_post.rb → lib/plugins/deprecate/wassr_post.rb
File renamed without changes.
View
0 lib/plugins/yhara.rb → lib/plugins/deprecate/yhara.rb
File renamed without changes.
View
0 lib/plugins/yonda.rb → lib/plugins/deprecate/yonda.rb
File renamed without changes.
View
2 lib/plugins/paranoid.rb
@@ -4,7 +4,7 @@ module Termtter::Client
:paranoid,
:help => ['paranoid message', 'Something like `update`'],
:alias => :pd) do |arg|
- str = arg.gsub(/\w+/, '@\0').gsub(/#@/, '#')
+ str = arg.gsub(/\w+/, '@\0').gsub(/\#@/, '#')
result = Termtter::API.twitter.update(str)
puts "paranoid'ed=> " << result.text
end
View
5 lib/termtter.rb
@@ -2,8 +2,7 @@
$KCODE = "u" unless Object.const_defined? :Encoding
-$:.unshift(File.dirname(__FILE__)) unless
- $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
+$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
require 'rubygems'
@@ -18,14 +17,14 @@
require 'termtter/config'
require 'termtter/version'
require 'termtter/optparse'
-require 'termtter/connection'
require 'termtter/command'
require 'termtter/hook'
require 'termtter/task'
require 'termtter/task_manager'
require 'termtter/client'
require 'termtter/api'
require 'termtter/system_extensions'
+require 'termtter/for_windows' if win?
module Termtter
APP_NAME = 'termtter'
View
31 lib/termtter/api.rb
@@ -13,20 +13,17 @@
module Termtter
module API
class << self
- attr_reader :connection, :twitter
+ attr_reader :twitter
def setup
- @connection = Connection.new
@twitter = create_twitter(config.user_name, config.password)
end
- def restore_user
- @twitter = create_twitter(config.user_name, config.password)
- end
+ alias restore_user setup
- def switch_user(username = nil)
+ def switch_user(username = nil, password = nil)
highline = create_highline
username = highline.ask('your twitter username: ') if username.nil? || username.empty?
- password = highline.ask('your twitter password: ') { |q| q.echo = false }
+ password = highline.ask('your twitter password: ') { |q| q.echo = false } if username.nil? || username.empty?
@twitter = create_twitter(username, password)
end
@@ -36,22 +33,22 @@ def create_twitter(user_name, password)
password,
{
:app_name => config.app_name.empty? ? Termtter::APP_NAME : config.app_name,
- :host => config.host,
- :header => {
- 'User-Agent' => 'Termtter http://github.com/jugyo/termtter',
- 'X-Twitter-Client' => 'Termtter',
- 'X-Twitter-Client-URL' => 'http://github.com/jugyo/termtter',
+ :host => config.host,
+ :header => {
+ 'User-Agent' => 'Termtter http://github.com/jugyo/termtter',
+ 'X-Twitter-Client' => 'Termtter',
+ 'X-Twitter-Client-URL' => 'http://github.com/jugyo/termtter',
'X-Twitter-Client-Version' => Termtter::VERSION
},
- :enable_ssl => config.enable_ssl,
- :proxy_host => config.proxy.host,
- :proxy_port => config.proxy.port,
+ :enable_ssl => config.enable_ssl,
+ :proxy_host => config.proxy.host,
+ :proxy_port => config.proxy.port,
:proxy_user_name => config.proxy.user_name,
- :proxy_password => config.proxy.password
+ :proxy_password => config.proxy.password
}
)
end
end
end
end
-# Termtter::API.connection, Termtter::API.twitter can be accessed.
+# Termtter::API.twitter can be accessed.
View
95 lib/termtter/client.rb
@@ -10,10 +10,10 @@ class CommandCanceled < StandardError; end
module Client
- @hooks = {}
- @commands = {}
- @filters = []
- @since_id = nil
+ @hooks = {}
+ @commands = {}
+ @filters = []
+ @since_id = nil
@task_manager = Termtter::TaskManager.new
config.set_default(:logger, nil)
@@ -25,7 +25,7 @@ module Client
class << self
- attr_reader :commands, :hooks
+ attr_reader :commands, :hooks, :logger
# plug :: Name -> (Hash) -> IO () where NAME = String | Symbol | [NAME]
def plug(name, options = {})
@@ -45,30 +45,27 @@ def public_storage
@public_storage ||= {}
end
- def add_filter(&b)
- warn "add_filter method will be removed. Use Termtter::Client.register_hook(:name => ..., :point => :filter_for_output, :exec => ... ) instead."
- @filters << b
- end
-
- def clear_filter
- @filters.clear
+ def register_hook(arg, opts = {}, &block)
+ register_(:hook, arg, opts, &block)
end
- def register_hook(arg, opts = {}, &block)
- hook = case arg
- when Hook
+ def register_(type, arg, opts = {}, &block)
+ type = type.to_s.capitalize
+ klass = Termtter.const_get(type)
+ target = case arg
+ when klass
arg
when Hash
- Hook.new(arg)
+ klass.new(arg)
when String, Symbol
options = { :name => arg }
options.merge!(opts)
options[:exec_proc] = block
- Hook.new(options)
+ klass.new(options)
else
- raise ArgumentError, 'must be given Termtter::Hook, Hash, String or Symbol'
+ raise ArgumentError, "must be given Termtter::#{type}, Hash or String(Symbol) with block"
end
- @hooks[hook.name] = hook
+ instance_variable_get(:"@#{type.downcase}s")[target.name] = target
end
def get_hook(name)
@@ -83,20 +80,7 @@ def get_hooks(point)
end
def register_command(arg, opts = {}, &block)
- command = case arg
- when Command
- arg
- when Hash
- Command.new(arg)
- when String, Symbol
- options = { :name => arg }
- options.merge!(opts)
- options[:exec_proc] = block
- Command.new(options)
- else
- raise ArgumentError, 'must be given Termtter::Command, Hash or String(Symbol) with block'
- end
- @commands[command.name] = command
+ register_(:command, arg, opts, &block)
end
def add_command(name)
@@ -145,14 +129,10 @@ def output(statuses, event)
filtered = apply_filters_for_hook(:filter_for_output, statuses.map(&:clone), event)
- @filters.each do |f| # TODO: code for compatibility. delete someday.
- filtered = f.call(filtered, event)
- end
-
call_hooks(:post_filter, filtered, event)
get_hooks(:output).each do |hook|
hook.call(
- apply_filters_for_hook("filter_for_#{hook.name}", filtered, event),
+ apply_filters_for_hook(:"filter_for_#{hook.name}", filtered, event),
event
)
end
@@ -175,6 +155,11 @@ def call_hooks(point, *args)
end
def call_commands(text)
+ # status
+ # 0: done
+ # 1: canceled
+ status = 0
+
@task_manager.invoke_and_wait do
# FIXME: This block can become Maybe Monad
get_hooks("pre_command").each {|hook|
@@ -201,9 +186,11 @@ def call_commands(text)
result = command.call(command_str, modified_arg, text) # exec command
call_hooks("post_exec_#{command.name.to_s}", command_str, modified_arg, result)
rescue CommandCanceled
+ status = 1
end
end
call_hooks("post_command", text)
+ status
end
end
@@ -234,37 +221,13 @@ def exit
end
def load_config
- legacy_config_support() if File.exist? Termtter::CONF_DIR
unless File.exist?(Termtter::CONF_FILE)
require 'termtter/config_setup'
ConfigSetup.run
end
load Termtter::CONF_FILE
end
- def legacy_config_support
- case File.ftype(File.expand_path('~/.termtter'))
- when 'directory'
- # nop
- when 'file'
- move_legacy_config_file
- end
- end
-
- def move_legacy_config_file
- FileUtils.mv(
- Termtter::CONF_DIR,
- File.expand_path('~/.termtter___'))
- Dir.mkdir(Termtter::CONF_DIR)
- FileUtils.mv(
- File.expand_path('~/.termtter___'),
- Termtter::CONF_FILE)
- end
-
- def logger
- @logger
- end
-
def setup_logger
@logger = config.logger || default_logger
end
@@ -339,8 +302,8 @@ def handle_error(e)
end
get_hooks(:on_error).each {|hook| hook.call(e) }
rescue Exception => e
- puts "Error: #{e}"
- puts e.backtrace.join("\n")
+ $stderr.puts "Error: #{e}"
+ $stderr.puts e.backtrace.join("\n")
end
def confirm(message, default_yes = true, &block)
@@ -354,9 +317,7 @@ def confirm(message, default_yes = true, &block)
end
result = !!(/^y?$/i =~ Readline.readline(prompt, false))
- if result && block
- block.call
- end
+ block.call if result && block
result
ensure
View
6 lib/termtter/command.rb
@@ -13,9 +13,9 @@ class Command
def initialize(args)
raise ArgumentError, ":name is not given." unless args.has_key?(:name)
args = args.dup
- args[:exec_proc] ||= args[:exec]
+ args[:exec_proc] ||= args[:exec]
args[:completion_proc] ||= args[:completion]
- args[:aliases] ||= [args[:alias]].compact
+ args[:aliases] ||= [args[:alias]].compact
cfg = {
:aliases => [],
@@ -29,7 +29,7 @@ def initialize(args)
# set :: Hash -> ()
def set(cfg)
self.name = cfg[:name].to_sym
- self.aliases = cfg[:aliases]
+ self.aliases = cfg[:aliases]
self.exec_proc = cfg[:exec_proc]
self.completion_proc = cfg[:completion_proc]
self.help = cfg[:help]
View
8 lib/termtter/config_setup.rb
@@ -6,17 +6,17 @@ module Termtter
module ConfigSetup
module_function
def run
- ui = create_highline
+ ui = create_highline
user_name = ui.ask('your twitter user name: ')
- password = ui.ask('your twitter password: ') { |q| q.echo = false }
+ password = ui.ask('your twitter password: ') { |q| q.echo = false }
- plugins = Dir.glob(File.expand_path(File.dirname(__FILE__) + "/../plugins/*.rb")).map {|f|
+ plugins = Dir.glob(File.expand_path(File.dirname(__FILE__) + "/../plugins/*.rb")).map {|f|
f.match(%r|lib/plugins/(.*?).rb$|)[1]
}
standard_plugins = %w[stdout standard_commands auto_reload]
template = open(File.dirname(__FILE__) + '/config_template.erb').read
- config = ERB.new(template, nil, '-').result(binding) # trim_mode => '-'
+ config = ERB.new(template, nil, '-').result(binding) # trim_mode => '-'
Dir.mkdir(Termtter::CONF_DIR) unless File.exists?(Termtter::CONF_DIR)
File.open(Termtter::CONF_FILE, 'w', 0600) {|io|
View
10 lib/termtter/config_template.erb
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
-config.user_name = '<%= user_name %>'
-config.password = '<%= password %>'
+config.user_name = '<%= user_name %>'
+config.password = '<%= password %>'
#config.update_interval = 120
-#config.proxy.host = 'proxy host'
-#config.proxy.port = '8080'
+#config.proxy.host = 'proxy host'
+#config.proxy.port = '8080'
#config.proxy.user_name = 'proxy user'
-#config.proxy.password = 'proxy password'
+#config.proxy.password = 'proxy password'
Termtter::Client.init do |t|
<%- (plugins - standard_plugins).each do |plugin| -%>
View
41 lib/termtter/connection.rb
@@ -1,41 +0,0 @@
-# -*- coding: utf-8 -*-
-
-module Termtter
- class Connection
- attr_reader :protocol, :port, :proxy_uri
-
- def initialize
- unless config.proxy.empty?
- @proxy_host = config.proxy.host
- @proxy_port = config.proxy.port
- @proxy_user = config.proxy.user_name
- @proxy_password = config.proxy.password
- @proxy_uri = nil
- @enable_ssl = config.enable_ssl
- end
- @protocol = "http"
- @port = 80
-
- if @proxy_host
- @http_class = Net::HTTP::Proxy(@proxy_host, @proxy_port,
- @proxy_user, @proxy_password)
- @proxy_uri = "http://" + @proxy_host + ":" + @proxy_port + "/"
- else
- @http_class = Net::HTTP
- end
-
- if @enable_ssl
- @protocol = "https"
- @port = 443
- end
- end
-
- def start(host, port, &block)
- http = @http_class.new(host, port)
- http.use_ssl = @enable_ssl
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?
- http.start(&block)
- end
- end
-end
-
View
86 lib/termtter/for_windows.rb
@@ -0,0 +1,86 @@
+# -*- coding: utf-8 -*-
+
+require 'iconv'
+require 'Win32API'
+$wGetACP = Win32API.new('kernel32','GetACP','','I')
+
+module Readline
+ $iconv_sj_to_u8 = Iconv.new('UTF-8', "CP#{$wGetACP.call()}")
+ alias :old_readline :readline
+ def readline(*a)
+ str = old_readline(*a)
+ out = ''
+ loop do
+ begin
+ out << $iconv_sj_to_u8.iconv(str)
+ break
+ rescue Iconv::Failure
+ out << "#{$!.success}?"
+ str = $!.failed[1..-1]
+ end
+ end
+ return out
+ end
+ module_function :old_readline, :readline
+end
+
+$wSetConsoleTextAttribute = Win32API.new('kernel32','SetConsoleTextAttribute','II','I')
+$wGetConsoleScreenBufferInfo = Win32API.new("kernel32", "GetConsoleScreenBufferInfo", ['l', 'p'], 'i')
+$wGetStdHandle = Win32API.new('kernel32','GetStdHandle','I','I')
+$wGetACP = Win32API.new('kernel32','GetACP','','I')
+
+$hStdOut = $wGetStdHandle.call(0xFFFFFFF5)
+lpBuffer = ' ' * 22
+$wGetConsoleScreenBufferInfo.call($hStdOut, lpBuffer)
+$oldColor = lpBuffer.unpack('SSSSSssssSS')[4]
+
+$colorMap = {
+ 0 => 0x07|0x00|0x00|0x00, # black/white
+ 37 => 0x08|0x00|0x00|0x00, # white/intensity
+ 31 => 0x04|0x08|0x00|0x00, # red/red
+ 32 => 0x02|0x08|0x00|0x00, # green/green
+ 33 => 0x06|0x08|0x00|0x00, # yellow/yellow
+ 34 => 0x01|0x08|0x00|0x00, # blue/blue
+ 35 => 0x05|0x08|0x00|0x00, # magenta/purple
+ 36 => 0x03|0x08|0x00|0x00, # cyan/aqua
+ 39 => 0x07, # default
+ 40 => 0x00|0x00|0xf0|0x00, # background:white
+ 41 => 0x07|0x00|0x40|0x00, # background:red
+ 42 => 0x07|0x00|0x20|0x00, # background:green
+ 43 => 0x07|0x00|0x60|0x00, # background:yellow
+ 44 => 0x07|0x00|0x10|0x00, # background:blue
+ 45 => 0x07|0x00|0x50|0x80, # background:magenta
+ 46 => 0x07|0x00|0x30|0x80, # background:cyan
+ 47 => 0x07|0x00|0x70|0x80, # background:gray
+ 49 => 0x70, # default
+ 90 => 0x07|0x00|0x00|0x00, # erase/white
+}
+$iconv_u8_to_sj = Iconv.new("CP#{$wGetACP.call()}", 'UTF-8')
+def print(str)
+ str.to_s.gsub("\xef\xbd\x9e", "\xe3\x80\x9c").split(/(\e\[\d*[a-zA-Z])/).each do |token|
+ case token
+ when /\e\[(\d+)m/
+ color = $1.to_i > 90 ? ($1.to_i % 60) : $1.to_i
+ $wSetConsoleTextAttribute.call $hStdOut, $colorMap[color].to_i
+ when /\e\[\d*[a-zA-Z]/
+ # do nothing
+ else
+ loop do
+ begin
+ STDOUT.print $iconv_u8_to_sj.iconv(token)
+ break
+ rescue Iconv::Failure
+ STDOUT.print "#{$!.success}?"
+ token = $!.failed[1..-1]
+ end
+ end
+ end
+ end
+ $wSetConsoleTextAttribute.call $hStdOut, $oldColor
+ $iconv_u8_to_sj.iconv(nil)
+end
+def puts(str)
+ print str
+ STDOUT.puts
+end
+
View
4 lib/termtter/hook.rb
@@ -6,8 +6,8 @@ class Hook
def initialize(args)
raise ArgumentError, ":name is not given." unless args.has_key?(:name)
- @name = args[:name].to_sym
- @points = args[:points] || [args[:point]].compact
+ @name = args[:name].to_sym
+ @points = args[:points] || [args[:point]].compact
@exec_proc = args[:exec_proc] || args[:exec] || lambda {}
end
View
90 lib/termtter/optparse.rb
@@ -1,51 +1,61 @@
-OptionParser.new { |opt|
- opt.program_name = 'Termtter'
+module Termtter
+ module OptParser
+ class << self
+ def parse!(argv)
+ @optionparser.parse!(argv)
+ end
+ end
- opt.on('-f', '--config-file file', 'Set path to configfile') do |val|
- config.system.__assign__(:conf_file, val)
- end
+ @optionparser = OptionParser.new { |opt|
+ opt.program_name = 'Termtter'
- opt.on('-t', '--termtter-directory directory', 'Set termtter directory') do |val|
- config.system.__assign__(:conf_dir, val)
- end
+ opt.on('-f', '--config-file file', 'Set path to configfile') do |val|
+ config.system.__assign__(:conf_file, val)
+ end
- opt.on('-d', '--devel', 'Start in developer mode') do |flg|
- config.__assign__(:devel, true) if flg
- end
+ opt.on('-t', '--termtter-directory directory', 'Set termtter directory') do |val|
+ config.system.__assign__(:conf_dir, val)
+ end
- config.system.cmd_mode = false
- opt.on('-c', '--command-mode', 'Run as command mode') do |flg|
- config.system.cmd_mode = flg
- end
+ opt.on('-d', '--devel', 'Start in developer mode') do |flg|
+ config.__assign__(:devel, true) if flg
+ end
- config.system.run_commands = []
- opt.on('-r', '--run-command command', 'Run command') do |cmd|
- config.system.run_commands << cmd
- end
+ config.system.cmd_mode = false
+ opt.on('-c', '--command-mode', 'Run as command mode') do |flg|
+ config.system.cmd_mode = flg
+ end
- config.system.load_plugins = []
- opt.on('-p', '--plugin plugin', 'Load plugin') do |plugin|
- config.system.load_plugins << plugin
- end
+ config.system.run_commands = []
+ opt.on('-r', '--run-command command', 'Run command') do |cmd|
+ config.system.run_commands << cmd
+ end
- config.system.eval_scripts = []
- opt.on('-e', '--eval-script script', 'Eval script') do |script|
- config.system.eval_scripts << script
- end
+ config.system.load_plugins = []
+ opt.on('-p', '--plugin plugin', 'Load plugin') do |plugin|
+ config.system.load_plugins << plugin
+ end
+
+ config.system.eval_scripts = []
+ opt.on('-e', '--eval-script script', 'Eval script') do |script|
+ config.system.eval_scripts << script
+ end
- config.system.eval_scripts = []
- opt.on('-m', '--monochrome', 'No shell escapes for color highlightings') do |script|
- require 'termcolor'
- module TermColor
- class << self
- alias parse_orig parse
- def parse(o)
- o.gsub(/<.+?>(.*?)<\/.+?>/, '\1')
+ config.system.eval_scripts = []
+ opt.on('-m', '--monochrome', 'No shell escapes for color highlightings') do |script|
+ require 'termcolor'
+ module ::TermColor
+ class << self
+ alias parse_orig parse
+ def parse(o)
+ o.gsub(/<.+?>(.*?)<\/.+?>/, '\1')
+ end
+ end
end
end
- end
- end
- opt.version = Termtter::VERSION
- opt.parse!(ARGV)
-}
+ opt.version = Termtter::VERSION
+ }
+
+ end
+end
View
123 lib/termtter/system_extensions.rb
@@ -1,22 +1,5 @@
# -*- coding: utf-8 -*-
-def plugin(name, init = {})
- warn "plugin method will be removed. Use Termtter::Client.plug instead."
- unless init.empty?
- init.each do |key, value|
- config.plugins.__refer__(name.to_sym).__assign__(key.to_sym, value)
- end
- end
- load "plugins/#{name}.rb"
-rescue Exception => e
- Termtter::Client.handle_error(e)
-end
-
-def filter(name, init = {})
- warn "filter method will be removed. Use plugin instead."
- plugin(name, init)
-end
-
require 'dl/import'
module Readline
begin
@@ -44,116 +27,14 @@ def self.refresh_line;end
end
def win?
- RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/
-end
-
-if win?
- require 'iconv'
- require 'Win32API'
- $wGetACP = Win32API.new('kernel32','GetACP','','I')
-
- module Readline
- $iconv_sj_to_u8 = Iconv.new('UTF-8', "CP#{$wGetACP.call()}")
- alias :old_readline :readline
- def readline(*a)
- str = old_readline(*a)
- out = ''
- loop do
- begin
- out << $iconv_sj_to_u8.iconv(str)
- break
- rescue Iconv::Failure
- out << "#{$!.success}?"
- str = $!.failed[1..-1]
- end
- end
- return out
- end
- module_function :old_readline, :readline
- end
-
- $wSetConsoleTextAttribute = Win32API.new('kernel32','SetConsoleTextAttribute','II','I')
- $wGetConsoleScreenBufferInfo = Win32API.new("kernel32", "GetConsoleScreenBufferInfo", ['l', 'p'], 'i')
- $wGetStdHandle = Win32API.new('kernel32','GetStdHandle','I','I')
- $wGetACP = Win32API.new('kernel32','GetACP','','I')
-
- $hStdOut = $wGetStdHandle.call(0xFFFFFFF5)
- lpBuffer = ' ' * 22
- $wGetConsoleScreenBufferInfo.call($hStdOut, lpBuffer)
- $oldColor = lpBuffer.unpack('SSSSSssssSS')[4]
-
- $colorMap = {
- 0 => 0x07|0x00|0x00|0x00, # black/white
- 37 => 0x08|0x00|0x00|0x00, # white/intensity
- 31 => 0x04|0x08|0x00|0x00, # red/red
- 32 => 0x02|0x08|0x00|0x00, # green/green
- 33 => 0x06|0x08|0x00|0x00, # yellow/yellow
- 34 => 0x01|0x08|0x00|0x00, # blue/blue
- 35 => 0x05|0x08|0x00|0x00, # magenta/purple
- 36 => 0x03|0x08|0x00|0x00, # cyan/aqua
- 39 => 0x07, # default
- 40 => 0x00|0x00|0xf0|0x00, # background:white
- 41 => 0x07|0x00|0x40|0x00, # background:red
- 42 => 0x07|0x00|0x20|0x00, # background:green
- 43 => 0x07|0x00|0x60|0x00, # background:yellow
- 44 => 0x07|0x00|0x10|0x00, # background:blue
- 45 => 0x07|0x00|0x50|0x80, # background:magenta
- 46 => 0x07|0x00|0x30|0x80, # background:cyan
- 47 => 0x07|0x00|0x70|0x80, # background:gray
- 49 => 0x70, # default
- 90 => 0x07|0x00|0x00|0x00, # erase/white
- }
- $iconv_u8_to_sj = Iconv.new("CP#{$wGetACP.call()}", 'UTF-8')
- def print(str)
- str.to_s.gsub("\xef\xbd\x9e", "\xe3\x80\x9c").split(/(\e\[\d*[a-zA-Z])/).each do |token|
- case token
- when /\e\[(\d+)m/
- color = $1.to_i > 90 ? ($1.to_i % 60) : $1.to_i
- $wSetConsoleTextAttribute.call $hStdOut, $colorMap[color].to_i
- when /\e\[\d*[a-zA-Z]/
- # do nothing
- else
- loop do
- begin
- STDOUT.print $iconv_u8_to_sj.iconv(token)
- break
- rescue Iconv::Failure
- STDOUT.print "#{$!.success}?"
- token = $!.failed[1..-1]
- end
- end
- end
- end
- $wSetConsoleTextAttribute.call $hStdOut, $oldColor
- $iconv_u8_to_sj.iconv(nil)
- end
- def puts(str)
- print str
- STDOUT.puts
- end
-end
-
-unless Array.instance_methods.include?('take')
- class Array
- def take(n) self[0...n] end
- end
-end
-
-unless Symbol.instance_methods.include?('to_proc')
- class Symbol
- def to_proc
- Proc.new { |*args| args.shift.__send__(self, *args) }
- end
- end
+ !!(RUBY_PLATFORM.downcase =~ /mswin(?!ce)|mingw|bccwin|cygwin/)
end
require 'highline'
def create_highline
HighLine.track_eof = false
if $stdin.respond_to?(:getbyte) # for ruby1.9
- def $stdin.getc
- getbyte
- end
+ def $stdin.getc; getbyte end
end
HighLine.new($stdin)
end
View
8 lib/termtter/task.rb
@@ -4,11 +4,11 @@ module Termtter
class Task
attr_accessor :name, :exec_at, :exec_proc, :interval, :work
def initialize(args = {}, &block)
- @name = args[:name]
- @exec_at = Time.now + (args[:after] || 0)
- @interval = args[:interval]
+ @name = args[:name]
+ @exec_at = Time.now + (args[:after] || 0)
+ @interval = args[:interval]
@exec_proc = block || lambda {}
- @work = true
+ @work = true
end
def execute
exec_proc.call(self) if work
View
8 lib/termtter/task_manager.rb
@@ -7,7 +7,7 @@ class TaskManager
def initialize()
@tasks = {}
- @work = true
+ @work = true
@mutex = Mutex.new
@pause = false
end
@@ -43,9 +43,7 @@ def step
def invoke_later
Thread.new do
- invoke_and_wait do
- yield
- end
+ invoke_and_wait { yield }
end
end
@@ -89,7 +87,7 @@ def synchronize
def pull_due_tasks()
synchronize do
- time_now = Time.now
+ time_now = Time.now
due_tasks = []
@tasks.delete_if do |key, task|
if task.work && task.exec_at <= time_now
View
1 run_termtter.rb
@@ -16,6 +16,7 @@
end
require 'termtter'
+Termtter::OptParser::parse!(ARGV)
Termtter::Client.run
# Startup scripts for development
View
29 spec/plugins/cool_spec.rb
@@ -3,8 +3,33 @@
require File.dirname(__FILE__) + '/../spec_helper'
describe Termtter::Client, 'when the plugin cool is loaded' do
- it 'should add something about cool' do
- Termtter::Client.should_receive(:register_macro)
+ before do
+ $stdout, @old_stdout = StringIO.new, $stdout # FIXME That suspends any debug informations!
+ @update_arg, @update_params = [], []
+ config.system.cmd_mode = true
+ Termtter::Client.run
+ Termtter::API.twitter.stub!(:update) {|arg, param|
+ @update_arg.push(arg)
+ @update_params.push(param)
+ a = mock('Foo')
+ a.should_receive(:text).and_return(arg)
+ a
+ }
Termtter::Client.plug 'cool'
end
+
+ after do
+ config.system.cmd_mode = false
+ Termtter::Client.exit
+ $stdout = @old_stdout
+ end
+
+ it 'register command cool' do
+ command = Termtter::Client.get_command(:cool)
+ Termtter::Client.call_commands('cool')
+ $stdout.rewind
+ $stdout.read.should == "updated => cool.\n"
+ @update_arg.should == ['cool.']
+ @update_params.should == [{ }]
+ end
end
View
0 spec/plugins/english_spec.rb → spec/plugins/english_spec_.rb
File renamed without changes.
View
0 spec/plugins/filter_spec.rb → spec/plugins/filter_spec_.rb
File renamed without changes.
View
0 spec/plugins/primes_spec.rb → spec/plugins/primes_spec_.rb
File renamed without changes.
View
0 spec/plugins/sl_spec.rb → spec/plugins/sl_spec_.rb
File renamed without changes.
View
0 spec/plugins/storage/DB_spec.rb → spec/plugins/storage/DB_spec_.rb
File renamed without changes.
View
0 spec/plugins/storage/status_spec.rb → spec/plugins/storage/status_spec_.rb
File renamed without changes.
View
0 spec/plugins/whois_spec.rb → spec/plugins/whois_spec_.rb
File renamed without changes.
View
5 spec/termtter/active_rubytter_spec.rb
@@ -12,6 +12,11 @@ module Termtter
d.age.should == 16
end
+ it 'Hashのキーでもメソッドでもないものは呼べない' do
+ d = ActiveRubytter.new(:name => 'termtter')
+ lambda{ d.undefined_method }.should raise_error(NoMethodError)
+ end
+
it '元のHashを得られること' do
data = { :test => 'test' }
d = ActiveRubytter.new(data)
View
38 spec/termtter/api_spec.rb
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+
+require File.dirname(__FILE__) + '/../spec_helper'
+
+module Termtter
+ describe API do
+ before do
+ API.module_eval{
+ @twitter = nil
+ }
+ end
+
+ it 'can create twitter' do
+ t = API.create_twitter('foo', 'username')
+ t.class.should == Rubytter
+ t.login.should == 'foo'
+ end
+
+ it 'can create twitter' do
+ API.setup
+ API.twitter.class.should == Rubytter
+ end
+
+ it 'can restore user' do
+ API.restore_user
+ API.twitter.class.should == Rubytter
+ end
+
+ it 'can switch user' do
+ API.switch_user('foo', 'password')
+ API.twitter.login.should == 'foo'
+ API.switch_user('bar', 'password')
+ API.twitter.login.should == 'bar'
+ end
+
+ end
+end
+
View
262 spec/termtter/client_spec.rb
@@ -7,6 +7,80 @@ module Termtter
Client.setup_logger
end
+ # FIXME: Depends recent implement
+ it 'can run' do
+ Client.should_receive(:load_config) {}
+ Termtter::API.should_receive(:setup) {}
+ Client.should_receive(:setup_logger) {}
+ Client.should_receive(:load_plugins) {}
+ Client.should_receive(:eval_init_block) {}
+
+ config.system.eval_scripts = []
+ config.system.cmd_mode = true
+ Client.run
+ end
+
+ it 'can run (eval script cannot eval)' do
+ Client.stub(:load_config) {}
+ Termtter::API.stub(:setup) {}
+ Client.stub(:setup_logger) {}
+ Client.stub(:load_plugins) {}
+ Client.stub(:eval_init_block) {}
+
+ config.system.eval_scripts = ['raise']
+ Client.should_receive(:handle_error)
+
+ config.system.cmd_mode = true
+ Client.run
+ end
+
+ it 'can run (eval script cannot eval)' do
+ Client.stub(:load_config) {}
+ Termtter::API.stub(:setup) {}
+ Client.stub(:setup_logger) {}
+ Client.stub(:load_plugins) {}
+ Client.stub(:eval_init_block) {}
+
+ config.system.eval_scripts = []
+ config.system.cmd_mode = false
+ Client.instance_variable_get(:@task_manager).should_receive(:run) {}
+ Client.should_receive(:call_hooks).with(:initialize)
+ Client.should_receive(:call_hooks).with(:launched)
+ Client.run
+ end
+
+ it 'set init block' do
+ dummy = lambda {}
+ Client.init(&dummy)
+ Client.instance_variable_get(:@init_block).should == dummy
+ end
+
+ it 'can run init block' do
+ Client.init() {}
+ Client.instance_variable_get(:@init_block).
+ should_receive(:call).with(Client)
+ Client.eval_init_block
+ end
+
+ it 'can load plugins when initializing stage (normal)' do
+ config.devel = false
+ Client.should_receive(:plug).exactly(2).times
+ Client.load_plugins
+ end
+
+ it 'can load plugins when initializing stage (devel)' do
+ Client.should_receive(:plug).exactly(2).times
+ Client.load_plugins
+ end
+
+ it 'can pause and resume' do
+ manager = Client.instance_variable_get(:@task_manager)
+ manager.should_receive(:pause)
+ Client.pause
+ manager.should_receive(:resume)
+ Client.resume
+ end
+
it 'takes command' do
command = Command.new(:name => :test)
Client.register_command(command)
@@ -41,6 +115,15 @@ module Termtter
}.should_not raise_error
end
+ it 'register_command can raise error when take invalid argument' do
+ [1, ['hoge', 'fuga'], nil, Object.new].each do |bad|
+ lambda {
+ Client.register_command(bad)
+ }.should raise_error(ArgumentError)
+ end
+ end
+
+
it 'takes add_command as block' do
Client.add_command('test') do |c|
c.aliases = ['t']
@@ -77,8 +160,9 @@ module Termtter
['test foo bar ', 'foo bar'],
['test foo bar ', 'foo bar'],
].each do |input, args|
- Client.call_commands(input)
+ status = Client.call_commands(input)
command_arg.should == args
+ status.should == 0
end
end
@@ -101,6 +185,14 @@ module Termtter
hook_called.should == true
end
+ it 'register_hook can raise error when take invalid argument' do
+ [1, ['hoge', 'fuga'], nil, Object.new].each do |bad|
+ lambda {
+ Client.register_hook(bad)
+ }.should raise_error(ArgumentError)
+ end
+ end
+
it 'calls new_hook with args' do
arg1 = nil
arg2 = nil
@@ -222,6 +314,8 @@ module Termtter
hook_called.should == false
Client.should_receive(:puts)
+ Client.instance_variable_get(:@task_manager).
+ should_receive(:kill) {}
Client.exit
hook_called.should == true
end
@@ -234,6 +328,7 @@ module Termtter
hook1_called.should == false
hook2_called.should == false
+ Client.instance_variable_get(:@task_manager).stub(:kill)
Client.should_receive(:puts)
Client.exit
hook1_called.should == true
@@ -277,40 +372,84 @@ module Termtter
}.should_not raise_error
end
- it 'runs' do
- pending
- Client.should_receive(:load_config)
- Termtter::API.should_receive(:setup)
- Client.should_receive(:start_input_thread)
- Client.run
- end
-
- it 'load_config'
-
- it 'does nothing when ~/.termtter is directory' do
- File.should_receive(:ftype).and_return('directory')
- Client.should_not_receive(:move_legacy_config_file)
- Client.legacy_config_support
- end
-
- it 'does "move_legacy_config_file" when ~/.termtter is file' do
- File.should_receive(:ftype).and_return('file')
- Client.should_receive(:move_legacy_config_file)
- Client.legacy_config_support
- end
-
- it 'moves legacy config file' do
- FileUtils.should_receive(:mv).twice
- Dir.should_receive(:mkdir)
- Client.move_legacy_config_file
+ it 'can apply filter' do
+ statuses = [
+ { :id => 2,
+ :created_at => Time.now,
+ :user_id => 2,
+ :name => 'name',
+ :screen_name => 'screen name',
+ :source => 'termtter',
+ :reply_to => 1,
+ :text => 'hi',
+ :original_data => 'hi' }
+ ]
+ event = :output_for_test
+ hook_name = :my_hook
+
+ hook = Client.register_hook(hook_name) {|s, e| s.text.should == 'hi'; e.should == event }
+ hook.should_receive(:call)
+ Client.should_receive(:get_hooks).with(hook_name).and_return([hook])
+ Client.apply_filters_for_hook(hook_name, statuses, event)
+ end
+
+ it 'can add macro' do
+ Client.should_receive(:register_command).
+ with {|arg| arg.should be_an_instance_of(Hash) }
+ Client.register_macro('greet', "update %s")
+ end
+
+ it 'can load config' do
+ Client.should_receive(:load).with(Termtter::CONF_FILE)
+ Client.load_config
+ end
+
+ it 'can create config file when load_config' do
+ File.should_receive(:exist?).and_return(false)
+ require 'termtter/config_setup'
+ ConfigSetup.should_receive(:run).and_return(false)
+ Client.stub(:load).with(Termtter::CONF_FILE)
+ Client.load_config
+ end
+
+ it 'can output status (bad)' do
+ Client.should_not_receive(:call_hooks)
+ Client.output(nil, :hoge)
+ Client.should_not_receive(:call_hooks)
+ Client.output([], :hoge)
+ end
+
+ # FIXME: too dirty
+ it 'can output status (good)' do
+ statuses = mock('statuses', :null_object => true)
+ statuses.stub(:empty? => false, :nil? => false)
+ event = :event
+ Client.should_receive(:call_hooks).with(:pre_filter, statuses, event)
+ Client.should_receive(:apply_filters_for_hook).exactly(2).times.
+ with(an_instance_of(Symbol), anything, event).
+ and_return(statuses)
+ Client.should_receive(:call_hooks).with(:post_filter, statuses, event)
+ hook = mock(:hook, :name => 'test')
+ hook.should_receive(:call).with(anything, event)
+ Client.should_receive(:get_hooks).with(:output).and_return([hook])
+ Client.output(statuses, event)
end
it 'handles error' do
- logger = Client.instance_eval{@logger}
+ logger = Client.instance_variable_get(:@logger)
logger.should_receive(:error).with("StandardError: error")
Client.handle_error StandardError.new('error')
end
+ it 'handle_error raise error when logger is nothing' do
+ Client.instance_variable_set(:@logger, nil)
+ $stderr, old = StringIO.new, $stderr
+ Client.handle_error(StandardError.new('error'))
+ $stderr.rewind
+ $stderr.gets.should match(/\AError: error/)
+ $stderr = old
+ end
+
it 'cancels command by hook' do
command = Command.new(:name => :test)
Client.register_command(command)
@@ -326,6 +465,7 @@ module Termtter
end
it 'gets default help' do
+ Client.plug 'defaults' # FIXME: Do not need
$stdout, old_stdout = StringIO.new, $stdout # FIXME That suspends any debug informations!
help_command = Client.get_command(:help)
help_command.should_not be_nil
@@ -335,6 +475,7 @@ module Termtter
end
it 'gets an added help' do
+ Client.plug 'defaults' # FIXME: Do not need
Client.register_command(
:name => :foo,
:help => [
@@ -350,6 +491,71 @@ module Termtter
$stdout.string.should match(/foo list/)
end
+ it 'can confirm before update (yes default)' do
+ message = 'hello'
+ Readline.should_receive(:readline).
+ with("\"#{message}".strip + "\" [Y/n] ", false)
+ Client.confirm(message)
+ end
+
+ it 'can confirm before update (no default)' do
+ message = 'hello'
+ Readline.should_receive(:readline).
+ with("\"#{message}".strip + "\" [N/y] ", false)
+ Client.confirm(message, false)
+ end
+
+ it 'can configm before update' do
+ ok_pattern = [ 'y', 'Y', '' ]
+ ng_pattern = [
+ 'n', 'N',
+ ('a'..'z').to_a,
+ ('A'..'Z').to_a ].flatten
+ ng_pattern -= ['y', 'Y']
+
+ ok_pattern.each do |ask|
+ Readline.should_receive(:readline).and_return(ask)
+ Client.confirm('hello').should be_true
+ end
+ ng_pattern.each do |ask|
+ Readline.should_receive(:readline).and_return(ask)
+ Client.confirm('hello').should be_false
+ end
+ end
+
+ it 'confirm can take block as callback' do
+ Readline.stub(:readline => 'y')
+ called = false
+ Client.confirm('hello') { called = true }
+ called.should be_true
+ end
+
+ it 'default logger can cahnge error to fit security level' do
+ logger = Client.default_logger
+ TermColor.should_receive(:parse).with(match(/blue/))
+ logger.debug 'hi'
+ TermColor.should_receive(:parse).with(match(/cyan/))
+ logger.info 'hi'
+ TermColor.should_receive(:parse).with(match(/magenta/))
+ logger.warn 'hi'
+ TermColor.should_receive(:parse).with(match(/red/))
+ logger.error 'hi'
+ TermColor.should_receive(:parse).with(match(/on_red/))
+ logger.fatal 'hi'
+ TermColor.should_receive(:parse).with(match(/white/))
+ logger.unknown 'hi'
+ end
+
+ it 'can cancel command' do
+ text = 'text'
+ command = mock('command', :null_object => true)
+ command.stub(:call) { raise CommandCanceled }
+ Client.stub(:find_commands).with(text).and_return([command])
+ lambda {
+ Client.call_commands(text).should == 1
+ }.should_not raise_error
+ end
+
describe 'add commands' do
before(:each) do
Client.clear_command
View
5 spec/termtter/command_spec.rb
@@ -77,6 +77,11 @@ module Termtter
end
end
+ it 'returns empty array as candidates when competition_proc is nil'do
+ command = Command.new(:name => :foo)
+ command.complement('foo bar').should == []
+ end
+
it 'returns command_info when call method "match?"' do
[
['update', true],
View
19 spec/termtter/config_setup_spec.rb
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+
+require File.dirname(__FILE__) + '/../spec_helper'
+require 'termtter/config_setup'
+
+module Termtter
+ describe ConfigSetup do
+ it "check inputed values" do
+ highline = mock('mock', :ask => 'username_or_password')
+ ConfigSetup.stub(:create_highline).and_return(highline)
+ File.stub(:exists?).and_return(true)
+ io = StringIO.new
+ File.stub(:open).and_yield(io)
+ ConfigSetup.run
+ io.rewind
+ io.read.should match(/username_or_password/)
+ end
+ end
+end
View
17 spec/termtter/config_spec.rb
@@ -29,6 +29,23 @@ module Termtter
@config.storage.should == :value2
end
+ it 'should be able to inspect' do
+ @config.storage = :value
+ @config.inspect.should == {:storage => :value}.inspect
+ end
+
+ it 'should be able to get __values__' do
+ @config.storage = :value
+ @config.__values__.should == {:storage => :value}
+ end
+
+ it 'should be able to __clear__' do
+ @config.storage = :value
+ @config.storage.should == :value
+ @config.__clear__
+ @config.__values__.should == {}
+ end
+
it 'should be able to store any data' do
[
['string', 'value' ],
View
12 spec/termtter/hook_spec.rb
@@ -62,6 +62,18 @@ module Termtter
hook.match?(:'_bar_').should == false
end
+ it 'should not match invalid point' do
+ hook = Hook.new(
+ :name => :spam,
+ :points => [1, { }, nil],
+ :exec_proc => lambda{|cmd, arg|
+ }
+ )
+ hook.match?(1).should == false
+ hook.match?({ }).should == false
+ hook.match?(nil).should == false
+ end
+
it 'call hook proc' do
proc_args = nil
hook = Hook.new(
View
73 spec/termtter/optparse_spec.rb
@@ -1,16 +1,71 @@
# -*- coding: utf-8 -*-
require File.dirname(__FILE__) + '/../spec_helper'
-describe 'optparse' do
- def run_termtter(opt)
- `./run_termtter.rb #{opt}`
- end
+module Termtter
+ describe OptParser do
- it 'accepts -h option' do
- run_termtter('-h').should match(/Usage/)
- end
+ before do
+ @original_conf ||= config
+ end
+
+ after do
+ conf = @original_conf
+ end
+
+ def run_termtter(opt)
+ `./run_termtter.rb #{opt}`
+ end
+
+ it 'accepts -h option' do
+ run_termtter('-h').should match(/Usage/)
+ end
+
+ it 'accepts -f option' do
+ Termtter::OptParser::parse!(%w{-f ~/config})
+ config.system.conf_file.should == '~/config'
+ end
+
+ it 'accepts -t option' do
+ Termtter::OptParser::parse!(%w{-t ~/termtter_directory})
+ config.system.conf_dir.should == '~/termtter_directory'
+ end
+
+ it 'accepts -d option' do
+ Termtter::OptParser::parse!(%w{-d})
+ config.devel.should be_true
+ end
+
+ it 'accepts -c option' do
+ Termtter::OptParser::parse!(%w{-c})
+ config.system.cmd_mode.should be_true
+ end
+
+ it 'accepts -r option' do
+ Termtter::OptParser::parse!(%w{-r cool})
+ config.system.run_commands.should == %w{cool}
+ end
+
+ it 'accepts -p option' do
+ Termtter::OptParser::parse!(%w{-p cool})
+ config.system.load_plugins.should == %w{cool}
+ end
+
+ it 'accepts -e option' do
+ Termtter::OptParser::parse!(%w{-e foo})
+ config.system.eval_scripts.should == %w{foo}
+ end
+
+ it 'accepts -m option' do
+ require 'termcolor'
+ TermColor.parse('<red>cool</red>').should == "\e[31mcool\e[0m"
+ Termtter::OptParser::parse!(%w{-m})
+ TermColor.parse('<red>cool</red>').should == 'cool'
+ module ::TermColor
+ class << self
+ alias parse parse_orig
+ end
+ end
+ end
- it 'accepts -m option' do
- pending
end
end
View
41 spec/termtter/system_extensions_spec.rb
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+
+require File.dirname(__FILE__) + '/../spec_helper'
+require 'highline'
+
+describe Termtter do
+
+ it 'provides create_highline' do
+ h = create_highline
+ h.class.should == HighLine
+ end
+
+ it 'provides win?' do
+ original_ruby_platform = RUBY_PLATFORM
+ RUBY_PLATFORM = 'darwin'
+ win?.should == false
+ RUBY_PLATFORM = 'mswin'
+ win?.should == true
+ RUBY_PLATFORM = original_ruby_platform
+ end
+
+ it 'Readline can refresh line' do
+ Readline::LIBREADLINE.should_receive(:rl_refresh_line).with(0, 0)
+ Readline.refresh_line
+ end
+
+ it 'extend DL::Impoter when not be able to find DL::Importable' do
+ DL::Importer = mock(:importer)
+ DL.stub(:const_defined?).with(:Importable).and_return(false)
+ Readline::LIBREADLINE.should_receive(:extend).with(DL::Importer)
+ load 'termtter/system_extensions.rb'
+ end
+
+ it 'can handle error when difine LIBREADLINE' do
+ Readline::LIBREADLINE.stub(:extend) { raise }
+ load 'termtter/system_extensions.rb'
+ Readline::LIBREADLINE.should_not_receive(:rl_refresh_line)
+ Readline.refresh_line
+ end
+end
+
View
54 spec/termtter/task_manager_spec.rb
@@ -68,11 +68,65 @@ module Termtter
@task_manager.instance_eval('@tasks').size.should == 1
end
+ it 'should run (not pause)' do
+ counter = 0
+ TaskManager::INTERVAL = 0
+ @task_manager.stub(:step) { counter += 1 }
+ @task_manager.instance_variable_set(:@work, true)
+ @task_manager.run
+ 100.times do
+ break if counter != 0
+ sleep 0.1
+ end
+ @task_manager.instance_variable_set(:@work, false)
+ counter.should > 0
+ end
+
+ it 'should run (pause)' do
+ counter = 0
+ TaskManager::INTERVAL = 0.1
+ @task_manager.stub(:step) { counter += 1 }
+ @task_manager.instance_variable_set(:@work, true)
+ @task_manager.instance_variable_set(:@pause, true)
+ @task_manager.run
+ sleep 0.1
+ counter.should == 0
+ @task_manager.instance_variable_set(:@pause, false)
+ 100.times do
+ break if counter != 0
+ sleep 0.1
+ end
+ @task_manager.instance_variable_set(:@work, false)
+ counter.should > 0
+ end
+
it 'should add task with :name' do
@task_manager.add_task(:name => 'foo')
@task_manager.get_task('foo').name.should == 'foo'
@task_manager.delete_task('foo')
@task_manager.get_task('foo').should == nil
end
+
+ it 'should be killed' do
+ @task_manager.instance_eval('@work').should == true
+ @task_manager.kill
+ @task_manager.instance_eval('@work').should == false
+ end
+
+ it 'should be paused or resumed' do
+ @task_manager.instance_eval('@pause').should == false
+ @task_manager.pause
+ @task_manager.instance_eval('@pause').should == true
+ @task_manager.resume
+ @task_manager.instance_eval('@pause').should == false
+ end
+
+ it 'invoke_later calls invoke_and_wait' do
+ called = false
+ block = lambda { called = true}
+ @task_manager.should_receive(:invoke_and_wait).with(&block)
+ @task_manager.invoke_later &block
+ called.should be_true
+ end
end
end
View
11 spec/termtter_spec.rb
@@ -26,3 +26,14 @@
config.plugins.aaa.bbb.should == :ccc
end
end
+
+describe Termtter, 'when termtter is loaded' do
+ it 'will add load path' do
+ termtter_path = File.expand_path(File.dirname(__FILE__) + '/../lib/termtter.rb')
+ original_load_path = $:.dup
+ $:.clear
+ load termtter_path
+ $:.include?(File.dirname(termtter_path)).should == true
+ $:.concat(original_load_path)
+ end
+end

0 comments on commit 5baa1fc

Please sign in to comment.