summaryrefslogtreecommitdiff
path: root/sample
diff options
context:
space:
mode:
Diffstat (limited to 'sample')
-rw-r--r--sample/README13
-rw-r--r--sample/biorhythm.rb118
-rw-r--r--sample/cal.rb84
-rw-r--r--sample/cbreak.rb4
-rw-r--r--sample/coverage.rb62
-rw-r--r--sample/dbmtest.rb14
-rw-r--r--sample/drb/darrayc.rb12
-rw-r--r--sample/drb/dhasenc.rb1
-rw-r--r--sample/dualstack-httpd.rb4
-rw-r--r--sample/eval.rb2
-rw-r--r--sample/exyacc.rb32
-rw-r--r--sample/from.rb161
-rw-r--r--sample/getopts.test36
-rw-r--r--sample/goodfriday.rb48
-rw-r--r--sample/mine.rb1
-rw-r--r--sample/mkproto.rb6
-rw-r--r--sample/mrshtest.rb13
-rw-r--r--sample/occur.rb4
-rw-r--r--sample/occur2.rb11
-rw-r--r--sample/openssl/c_rehash.rb4
-rw-r--r--sample/openssl/cert_store_view.rb911
-rw-r--r--sample/openssl/cipher.rb73
-rw-r--r--sample/openssl/echo_cli.rb21
-rw-r--r--sample/openssl/echo_svr.rb15
-rw-r--r--sample/openssl/gen_csr.rb13
-rw-r--r--sample/openssl/smime_read.rb10
-rw-r--r--sample/openssl/smime_write.rb10
-rw-r--r--sample/openssl/wget.rb17
-rw-r--r--sample/optparse/opttest.rb30
-rw-r--r--sample/philos.rb2
-rw-r--r--sample/pty/expect_sample.rb48
-rw-r--r--sample/pty/script.rb37
-rw-r--r--sample/pty/shl.rb92
-rw-r--r--sample/rdoc/markup/rdoc2latex.rb15
-rw-r--r--sample/rdoc/markup/sample.rb40
-rw-r--r--sample/regx.rb23
-rw-r--r--sample/ripper/ruby2html.rb112
-rw-r--r--sample/ripper/strip-comment.rb19
-rwxr-xr-xsample/rss/blend.rb6
-rwxr-xr-xsample/rss/convert.rb2
-rwxr-xr-x[-rw-r--r--]sample/rss/list_description.rb17
-rwxr-xr-xsample/rss/re_read.rb10
-rwxr-xr-x[-rw-r--r--]sample/rss/rss_recent.rb24
-rw-r--r--sample/svr.rb2
-rw-r--r--sample/test.rb802
-rw-r--r--sample/time.rb16
-rw-r--r--sample/timeout.rb42
-rw-r--r--sample/tsvr.rb2
48 files changed, 1373 insertions, 1668 deletions
diff --git a/sample/README b/sample/README
index 53d16de335..c1b9532203 100644
--- a/sample/README
+++ b/sample/README
@@ -3,11 +3,10 @@ biorhythm.rb biorhythm calculator
cal.rb cal(1) clone
cbreak.rb no echo done by ioctl
clnt.rb socket client
-dbmtest.rb test for dbm
+coverage.rb simple test code coverage tool
dir.rb directory access
dualstack-fetch.rb IPv6 demo
dualstack-httpd.rb IPv6 demo
-dstore.rb object database on dbm
eval.rb simple evaluator
export.rb method access example
exyacc.rb extrace BNF from yacc file
@@ -20,18 +19,13 @@ fib.scm Fibonacci number (Scheme)
freq.rb count word occurrence
from.rb scan mail spool
fullpath.rb convert ls -lR to fullpath format
-getopts.test test fot getopt.rb
-goodfriday.rb print various christian calendar event.
-io.rb io test
-irb.rb interactive ruby
less.rb front end for less
list.rb stupid object sample
list2.rb stupid object sample
list3.rb stupid object sample
mine.rb simple mine sweeper
-mkproto.rb extract prototype from C
+mkproto.rb extract prototype from C
mpart.rb split file int multi part
-mrshtest.rb test marshal
observ.rb observer design pattern sample
occur.pl count word occurrence (Perl)
occur.rb count word occurrence (Ruby)
@@ -41,12 +35,11 @@ pi.rb calculate PI
rcs.awk random character stereogram (AWK)
rcs.rb random character stereogram (Ruby)
rcs.dat data for random character stereogram
-rd2html.rb rd (Ruby Document) to HTML translator
-regx.rb regular expression tester
sieve.rb sieve of Eratosthenes
svr.rb socket server
test.rb test suite used by `make test'
time.rb /usr/bin/time clone
+timeout.rb timeout test
trojan.rb simple tool to find file that may be trojan horse.
tsvr.rb socket server using thread
uumerge.rb merge files and uudecode them
diff --git a/sample/biorhythm.rb b/sample/biorhythm.rb
index 0f89bb99e1..6465daa29f 100644
--- a/sample/biorhythm.rb
+++ b/sample/biorhythm.rb
@@ -2,8 +2,7 @@
#
# biorhythm.rb -
# $Release Version: $
-# $Revision: 1.9 $
-# $Date: 2003/05/05 14:02:14 $
+# $Revision$
# by Yasuo OHBA(STAFS Development Room)
#
# --
@@ -27,21 +26,8 @@
include Math
require "date.rb"
-require "parsearg.rb"
-require "parsedate.rb"
-
-def usage()
- print "Usage:\n"
- print "biorhythm.rb [options]\n"
- print " options...\n"
- print " -D YYYYMMDD(birthday) : use default values.\n"
- print " --sdate | --date YYYYMMDD : use system date; use specified date.\n"
- print " --birthday YYYYMMDD : specifies your birthday.\n"
- print " -v | -g : show values or graph.\n"
- print " --days DAYS : graph range (only in effect for graphs).\n"
- print " --help : help\n"
-end
-$USAGE = 'usage'
+require "optparse"
+require "optparse/date"
def printHeader(y, m, d, p, w)
print "\n>>> Biorhythm <<<\n"
@@ -58,60 +44,52 @@ def getPosition(z)
return phys, emot, geist
end
-def parsedate(s)
- ParseDate::parsedate(s).values_at(0, 1, 2)
-end
-
-def name_of_week(date)
- Date::DAYNAMES[date.wday]
+def prompt(msg)
+ $stderr.print msg
+ return gets.chomp
end
#
# main program
#
-parseArgs(0, nil, "vg", "D:", "sdate", "date:", "birthday:", "days:")
-
-if $OPT_D
- dd = Date.today
- bd = Date.new(*parsedate($OPT_D))
- ausgabeart = "g"
-else
- if $OPT_birthday
- bd = Date.new(*parsedate($OPT_birthday))
- else
- STDERR.print("Birthday (YYYYMMDD) : ")
- unless (si = STDIN.gets.chop).empty?
- bd = Date.new(*parsedate(si))
- end
- end
- if !bd
- STDERR.print "BAD Input Birthday!!\n"
- exit()
+options = {
+ :graph => true,
+ :date => Date.today,
+ :days => 9,
+}
+ARGV.options do |opts|
+ opts.on("-b", "--birthday=DATE", Date, "specify your birthday"){|v|
+ options[:birthday] = v
+ }
+ opts.on("--date=DATE", Date, "specify date to show"){|v|
+ options[:date] = v
+ }
+ opts.on("-g", "--show-graph", TrueClass, "show graph (default)"){|v|
+ options[:graph] = v
+ }
+ opts.on("-v", "--show-values", TrueClass, "show values"){|v|
+ options[:graph] = !v
+ }
+ opts.on("--days=DAYS", Integer, "graph range (only in effect for graph)"){|v|
+ options[:days] = v - 1
+ }
+ opts.on_tail("-h", "--help", "show this message"){puts opts; exit}
+ begin
+ opts.parse!
+ rescue => ex
+ puts "Error: #{ex.message}"
+ puts opts
+ exit
end
+end
- if $OPT_sdate
- dd = Date.today
- elsif $OPT_date
- dd = Date.new(*parsedate($OPT_date))
- else
- STDERR.print("Date [<RETURN> for Systemdate] (YYYYMMDD) : ")
- unless (si = STDIN.gets.chop).empty?
- dd = Date.new(*parsedate(si))
- end
- end
- dd ||= Date.today
+bd = options[:birthday] || Date.parse(prompt("Your birthday (YYYYMMDD): "))
+dd = options[:date] || Date.today
+ausgabeart = options[:graph] ? "g" : "v"
+display_period = options[:days]
- if $OPT_v
- ausgabeart = "v"
- elsif $OPT_g
- ausgabeart = "g"
- else
- STDERR.print("Values for today or Graph (v/g) [default g] : ")
- ausgabeart = STDIN.gets.chop
- end
-end
if ausgabeart == "v"
- printHeader(bd.year, bd.month, bd.day, dd - bd, name_of_week(bd))
+ printHeader(bd.year, bd.month, bd.day, dd - bd, bd.strftime("%a"))
print "\n"
phys, emot, geist = getPosition(dd - bd)
@@ -121,21 +99,7 @@ if ausgabeart == "v"
printf "Mental: %d%%\n", geist
print "\n"
else
- if $OPT_days
- display_period = $OPT_days.to_i
- elsif $OPT_D
- display_period = 9
- else
- STDERR.printf("Graph for how many days [default 10] : ")
- display_period = STDIN.gets.chop
- if display_period.empty?
- display_period = 9
- else
- display_period = display_period.to_i - 1
- end
- end
-
- printHeader(bd.year, bd.month, bd.day, dd - bd, name_of_week(bd))
+ printHeader(bd.year, bd.month, bd.day, dd - bd, bd.strftime("%a"))
print " P=physical, E=emotional, M=mental\n"
print " -------------------------+-------------------------\n"
print " Bad Condition | Good Condition\n"
diff --git a/sample/cal.rb b/sample/cal.rb
index fa20352f71..387657490f 100644
--- a/sample/cal.rb
+++ b/sample/cal.rb
@@ -1,7 +1,7 @@
#! /usr/bin/env ruby
-# cal.rb: Written by Tadayoshi Funaba 1998-2004
-# $Id: cal.rb,v 2.7 2004-01-10 23:52:51+09 tadf Exp $
+# cal.rb: Written by Tadayoshi Funaba 1998-2004,2006,2008
+# $Id: cal.rb,v 2.11 2008-01-06 08:42:17+09 tadf Exp $
require 'date'
@@ -9,25 +9,25 @@ class Cal
START =
{
- 'cn' => true, # China
- 'de' => 2342032, # Germany (protestant states)
- 'dk' => 2342032, # Denmark
- 'es' => 2299161, # Spain
- 'fi' => 2361390, # Finland
- 'fr' => 2299227, # France
- 'gb' => 2361222, # United Kingdom
- 'gr' => 2423868, # Greece
- 'hu' => 2301004, # Hungary
- 'it' => 2299161, # Italy
- 'jp' => true, # Japan
- 'no' => 2342032, # Norway
- 'pl' => 2299161, # Poland
- 'pt' => 2299161, # Portugal
- 'ru' => 2421639, # Russia
- 'se' => 2361390, # Sweden
- 'us' => 2361222, # United States
- 'os' => false, # (old style)
- 'ns' => true # (new style)
+ 'cn' => Date::GREGORIAN, # China
+ 'de' => 2342032, # Germany (protestant states)
+ 'dk' => 2342032, # Denmark
+ 'es' => 2299161, # Spain
+ 'fi' => 2361390, # Finland
+ 'fr' => 2299227, # France
+ 'gb' => 2361222, # United Kingdom
+ 'gr' => 2423868, # Greece
+ 'hu' => 2301004, # Hungary
+ 'it' => 2299161, # Italy
+ 'jp' => Date::GREGORIAN, # Japan
+ 'no' => 2342032, # Norway
+ 'pl' => 2299161, # Poland
+ 'pt' => 2299161, # Portugal
+ 'ru' => 2421639, # Russia
+ 'se' => 2361390, # Sweden
+ 'us' => 2361222, # United States
+ 'os' => Date::JULIAN, # (old style)
+ 'ns' => Date::GREGORIAN # (new style)
}
DEFAULT_START = 'gb'
@@ -53,7 +53,7 @@ class Cal
end
def pict(y, m)
- d = (1..31).detect{|d| Date.valid_date?(y, m, d, @start)}
+ d = (1..31).detect{|x| Date.valid_date?(y, m, x, @start)}
fi = Date.new(y, m, d, @start)
fi -= (fi.jd - @k + 1) % 7
@@ -72,7 +72,7 @@ class Cal
ca = %w(January February March April May June July
August September October November December)[m - 1]
- ca = ca + ' ' + y.to_s if not @opt_y
+ ca = ca + ' ' + y.to_s if !@opt_y
ca = ca.center(@mw)
ta.unshift(ca)
@@ -121,34 +121,46 @@ end
if __FILE__ == $0
- require 'getopts'
+ require 'getoptlong'
def usage
warn 'usage: cal [-c iso3166] [-jmty] [[month] year]'
exit 1
end
- usage unless getopts('jmty', "c:#{Cal::DEFAULT_START}")
+ cal = Cal.new
+
+ begin
+ GetoptLong.new(['-c', GetoptLong::REQUIRED_ARGUMENT],
+ ['-j', GetoptLong::NO_ARGUMENT],
+ ['-m', GetoptLong::NO_ARGUMENT],
+ ['-t', GetoptLong::NO_ARGUMENT],
+ ['-y', GetoptLong::NO_ARGUMENT]).
+ each do |opt, arg|
+ case opt
+ when '-c'; cal.opt_c(arg) || raise
+ when '-j'; cal.opt_j(true)
+ when '-m'; cal.opt_m(true)
+ when '-t'; cal.opt_t(true)
+ when '-y'; cal.opt_y(true)
+ end
+ end
+ rescue
+ usage
+ end
y, m = ARGV.values_at(1, 0).compact.collect{|x| x.to_i}
- $OPT_y ||= (y and not m)
+ cal.opt_y(true) if y && !m
to = Date.today
y ||= to.year
m ||= to.mon
- usage unless m >= 1 and m <= 12
+ usage unless m >= 1 && m <= 12
usage unless y >= -4712
- usage if Cal::START[$OPT_c].nil?
-
- cal = Cal.new
-
- cal.opt_j($OPT_j)
- cal.opt_m($OPT_m)
- cal.opt_t($OPT_t)
- cal.opt_y($OPT_y)
- cal.opt_c($OPT_c)
print cal.print(y, m)
end
+
+# See Bird & Wadler's Introduction to functional programming 4.5.
diff --git a/sample/cbreak.rb b/sample/cbreak.rb
index cbb15d2f41..76b534a76a 100644
--- a/sample/cbreak.rb
+++ b/sample/cbreak.rb
@@ -6,11 +6,11 @@ TIOCGETP = 0x40067408
TIOCSETP = 0x80067409
def cbreak ()
- set_cbreak(TRUE)
+ set_cbreak(true)
end
def cooked ()
- set_cbreak(FALSE)
+ set_cbreak(false)
end
def set_cbreak (on)
diff --git a/sample/coverage.rb b/sample/coverage.rb
new file mode 100644
index 0000000000..5e15f99716
--- /dev/null
+++ b/sample/coverage.rb
@@ -0,0 +1,62 @@
+require "coverage.so"
+
+Coverage.start
+
+ext = ENV["COVERUBY_EXT"] || ".cov"
+accum = ENV["COVERUBY_ACCUM"]
+accum = !accum || accum == "" || !(%w(f n 0).include?(accum[0]))
+pwd = Dir.pwd
+
+at_exit do
+ exit_exc = $!
+ Dir.chdir(pwd) do
+ Coverage.result.each do |sfile, covs|
+ cfile = sfile + ext
+
+ writable = proc do |f|
+ File.writable?(f) || File.writable?(File.dirname(f))
+ end
+ unless writable[cfile]
+ cfile = cfile.gsub(File.PATH_SEPARATOR, "#")
+ next unless writable[cfile]
+ end
+
+ readlines = proc do |f|
+ File.read(f).force_encoding("ASCII-8BIT").lines.to_a
+ end
+
+ sources = (readlines[sfile] rescue [])
+
+ pcovs = []
+ if accum
+ pcovs = (readlines[cfile] rescue []).map.with_index do |line, idx|
+ if line[/^\s*(?:(#####)|(\d+)|-):\s*\d+:(.*)$/n]
+ cov, line = $1 ? 0 : ($2 ? $2.to_i : nil), $3
+ if !sources[idx] || sources[idx].chomp != line.chomp
+ warn("source file changed, ignoring: `#{ cfile }'")
+ break []
+ end
+ cov
+ else
+ p line
+ warn("coverage file corrupted, ignoring: #{ cfile }")
+ break []
+ end
+ end
+ unless pcovs.empty? || pcovs.size == covs.size
+ warn("coverage file changed, ignoring: `#{ cfile }'")
+ pcovs = []
+ end
+ end
+
+ open(cfile, "w") do |out|
+ covs.zip(sources, pcovs).each_with_index do |(cov, line, pcov), idx|
+ cov += pcov || 0 if cov
+ cov = (cov ? (cov == 0 ? "#####" : cov.to_s) : "-").rjust(9)
+ out.puts("%s:% 5d:%s" % [cov, idx + 1, line])
+ end
+ end
+ end
+ end
+ raise exit_exc if exit_exc
+end
diff --git a/sample/dbmtest.rb b/sample/dbmtest.rb
deleted file mode 100644
index c77cc2065b..0000000000
--- a/sample/dbmtest.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# ruby dbm acess
-require "dbm"
-
-d = DBM.open("test")
-keys = d.keys
-if keys.length > 0 then
- for k in keys; print k, "\n"; end
- for v in d.values; print v, "\n"; end
-else
- d['foobar'] = 'FB'
- d['baz'] = 'BZ'
- d['quux'] = 'QX'
-end
-
diff --git a/sample/drb/darrayc.rb b/sample/drb/darrayc.rb
index 6f5ff6bb5d..b181d22699 100644
--- a/sample/drb/darrayc.rb
+++ b/sample/drb/darrayc.rb
@@ -45,15 +45,3 @@ ro.each do |x|
puts count
redo if count == 3
end
-
-puts "# each, retry"
-retried = false
-ro.each do |x|
- puts x
- if x == 4 && !retried
- puts 'retry'
- retried = true
- retry
- end
-end
-
diff --git a/sample/drb/dhasenc.rb b/sample/drb/dhasenc.rb
index 8114e9228d..2774feba5a 100644
--- a/sample/drb/dhasenc.rb
+++ b/sample/drb/dhasenc.rb
@@ -1,3 +1,4 @@
+# -*- encoding: euc-jp -*-
=begin
distributed Ruby --- dRuby Sample Client -- chasen client
Copyright (c) 1999-2001 Masatoshi SEKI
diff --git a/sample/dualstack-httpd.rb b/sample/dualstack-httpd.rb
index 893b29feba..11c5201d74 100644
--- a/sample/dualstack-httpd.rb
+++ b/sample/dualstack-httpd.rb
@@ -12,7 +12,7 @@ names = []
threads = []
res.each do |i|
- s = TCPserver.new(i[3], i[1])
+ s = TCPServer.new(i[3], i[1])
n = Socket.getnameinfo(s.getsockname, Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV).join(" port ")
sockpool.push s
names.push n
@@ -26,7 +26,7 @@ end
ls = mysock # copy to dynamic variable
t = Thread.current
STDERR.print "socket #{myname} listener started, pid #{$$} thread #{t}\n"
- while TRUE
+ while true
as = ls.accept
Thread.start do
STDERR.print "socket #{myname} accepted, thread ", Thread.current, "\n"
diff --git a/sample/eval.rb b/sample/eval.rb
index 90b839e873..ed4b7c3de5 100644
--- a/sample/eval.rb
+++ b/sample/eval.rb
@@ -1,6 +1,6 @@
line = ''
indent = 0
-$stdout.sync = TRUE
+$stdout.sync = true
print "ruby> "
loop do
l = gets
diff --git a/sample/exyacc.rb b/sample/exyacc.rb
index 5818825e25..c96ebfd676 100644
--- a/sample/exyacc.rb
+++ b/sample/exyacc.rb
@@ -2,21 +2,19 @@
# usage: exyacc.rb [yaccfiles]
# this is coverted from exyacc.pl in the camel book
-$/ = nil
-
-while gets()
- sbeg = $_.index("\n%%") + 1
- send = $_.rindex("\n%%") + 1
- $_ = $_[sbeg, send-sbeg]
- sub!(/.*\n/, "")
- gsub!(/'\{'/, "'\001'")
- gsub!(/'\}'/, "'\002'")
- gsub!(%r{\*/}, "\003\003")
- gsub!(%r{/\*[^\003]*\003\003}, '')
- while gsub!(/\{[^{}]*\}/, ''); end
- gsub!(/'\001'/, "'{'")
- gsub!(/'\002'/, "'}'")
- while gsub!(/^[ \t]*\n(\s)/, '\1'); end
- gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2')
- print $_
+ARGF.each(nil) do |source|
+ sbeg = source.index("\n%%") + 1
+ send = source.rindex("\n%%") + 1
+ grammer = source[sbeg, send-sbeg]
+ grammer.sub!(/.*\n/, "")
+ grammer.gsub!(/'\{'/, "'\001'")
+ grammer.gsub!(/'\}'/, "'\002'")
+ grammer.gsub!(%r{\*/}, "\003\003")
+ grammer.gsub!(%r{/\*[^\003]*\003\003}, '')
+ while grammer.gsub!(/\{[^{}]*\}/, ''); end
+ grammer.gsub!(/'\001'/, "'{'")
+ grammer.gsub!(/'\002'/, "'}'")
+ while grammer.gsub!(/^[ \t]*\n(\s)/, '\1'); end
+ grammer.gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2')
+ print grammer
end
diff --git a/sample/from.rb b/sample/from.rb
index 59cc387792..aa93e6726a 100644
--- a/sample/from.rb
+++ b/sample/from.rb
@@ -1,98 +1,113 @@
#! /usr/local/bin/ruby
-require "parsedate"
+require "time"
require "kconv"
-require "mailread"
-
-include ParseDate
-include Kconv
class String
-
- def kconv(code = Kconv::EUC)
- Kconv.kconv(self, code, Kconv::AUTO)
- end
-
def kjust(len)
- len += 1
- me = self[0, len].ljust(len)
- if me =~ /.$/ and $&.size == 2
- me[-2..-1] = ' '
- me[-2, 2] = ' '
+ res = ''
+ rlen = 0
+ self.each_char do |char|
+ delta = char.bytesize > 1 ? 2 : 1
+ break if rlen + delta > len
+ rlen += delta
+ res += char
end
- me.chop!
+ res += ' ' * (len - rlen) if rlen < len
+ res
end
-
end
-if ARGV[0] == '-w'
- wait = TRUE
- ARGV.shift
+def fromout(date, from, subj)
+ return 0 if !date
+ y, m, d = Time.parse(date).to_a.reverse[4, 3] if date
+ y ||= 0; m ||= 0; d ||= 0
+ from ||= "sombody@somewhere"
+ from.delete!("\r\n")
+ from = from.kconv(Encoding.default_external).kjust(28)
+ subj ||= "(nil)"
+ subj.delete!("\r\n")
+ subj = subj.kconv(Encoding.default_external).kjust(40)
+ printf "%02d/%02d/%02d [%s] %s\n", y%100, m, d, from, subj
+ return 1
end
-if ARGV.length == 0
- file = ENV['MAIL']
- user = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME']
-else
- file = user = ARGV[0]
- ARGV.clear
-end
+def get_mailfile(user)
+ file = user
+ unless user
+ file = ENV['MAIL']
+ user = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME']
+ end
-if file == nil or !File.exist? file
- [ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m|
- if File.exist? f = "#{m}/mail/#{user}"
- file = f
- break
+ if file == nil or !File.exist?(file)
+ [ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m|
+ path = "#{m}/mail/#{user}"
+ if File.exist?(path)
+ file = path
+ break
+ end
end
end
+ file
end
-$outcount = 0;
-def fromout(date, from, subj)
- return if !date
- y, m, d = parsedate(date) if date
- y ||= 0; m ||= 0; d ||= 0
- if from
- from.gsub! /\n/, ""
- else
- from = "sombody@somewhere"
- end
- if subj
- subj.gsub! /\n/, ""
- else
- subj = "(nil)"
+def from_main
+ if ARGV[0] == '-w'
+ wait = true
+ ARGV.shift
end
- if ENV['LANG'] =~ /sjis/i
- lang = Kconv::SJIS
- else
- lang = Kconv::EUC
- end
- from = from.kconv(lang).kjust(28)
- subj = subj.kconv(lang).kjust(40)
- printf "%02d/%02d/%02d [%s] %s\n",y%100,m,d,from,subj
- $outcount += 1
-end
+ file = get_mailfile(ARGV[0])
+
+ outcount = 0
+ if File.exist?(file)
+ atime = File.atime(file)
+ mtime = File.mtime(file)
+ open(file, "r") do |f|
+ until f.eof?
+ header = {}
+ f.each_line do |line|
+ next if /^From / =~ line # skip From-line
+ break if /^$/ =~ line # end of header
-if File.exist?(file)
- atime = File.atime(file)
- mtime = File.mtime(file)
- f = open(file, "r")
- begin
- until f.eof?
- mail = Mail.new(f)
- fromout mail.header['Date'],mail.header['From'],mail.header['Subject']
+ if /^(?<attr>\S+?):\s*(?<value>.*)/ =~ line
+ attr.capitalize!
+ header[attr] = value
+ elsif attr
+ header[attr] += "\n" + line.lstrip
+ end
+ end
+
+ f.each_line do |line|
+ break if /^From / =~ line
+ end
+ outcount += fromout(header['Date'], header['From'], header['Subject'])
+ end
end
- ensure
- f.close
File.utime(atime, mtime, file)
end
+
+ if outcount == 0
+ print "You have no mail.\n"
+ sleep 2 if wait
+ elsif wait
+ system "stty cbreak -echo"
+ $stdin.getc
+ system "stty cooked echo"
+ end
end
-if $outcount == 0
- print "You have no mail.\n"
- sleep 2 if wait
-elsif wait
- system "stty cbreak -echo"
- getc()
- system "stty cooked echo"
+if __FILE__ == $0
+ from_main
end
+
+__END__
+
+=begin
+
+= from.rb
+
+== USAGE
+
+ruby from.rb [-w] [username_or_filename]
+
+=end
diff --git a/sample/getopts.test b/sample/getopts.test
deleted file mode 100644
index 2866bccea8..0000000000
--- a/sample/getopts.test
+++ /dev/null
@@ -1,36 +0,0 @@
-#! /usr/local/bin/ruby
-
-load("parsearg.rb")
-
-def usage()
- printf "Usage:\n"
- printf "%s -d [-x x] [-y y] [--geometry geom] [--version] [string ...]\n", $0
-end
-
-$USAGE = 'usage'
-parseArgs(0, "d&(x|y)", "dfg", "x:", "y:", "geometry:800x600", "version")
-if ($OPT_d)
- if $OPT_version
- printf "version 1.0\n"
- end
- if ($OPT_x)
- printf("x = %d\n", $OPT_x.to_i)
- end
- if ($OPT_y)
- printf("y = %d\n", $OPT_y.to_i)
- end
- if ($OPT_geometry)
- printf("geometry = %s\n", $OPT_geometry)
- end
- if $OPT_f
- printf "f = TRUE\n"
- end
- if $OPT_g
- printf "g = TRUE\n"
- end
-end
-
-while (ARGV.length != 0)
- print "other = ", ARGV[0], "\n"
- ARGV.shift
-end
diff --git a/sample/goodfriday.rb b/sample/goodfriday.rb
deleted file mode 100644
index a95cfe819f..0000000000
--- a/sample/goodfriday.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-#! /usr/bin/env ruby
-
-# goodfriday.rb: Written by Tadayoshi Funaba 1998, 2000, 2002
-# $Id: goodfriday.rb,v 1.1 1998-03-08 18:44:44+09 tadf Exp $
-
-require 'date'
-
-def easter(y)
- g = (y % 19) + 1
- c = (y / 100) + 1
- x = (3 * c / 4) - 12
- z = ((8 * c + 5) / 25) - 5
- d = (5 * y / 4) - x - 10
- e = (11 * g + 20 + z - x) % 30
- e += 1 if e == 25 and g > 11 or e == 24
- n = 44 - e
- n += 30 if n < 21
- n = n + 7 - ((d + n) % 7)
- if n <= 31 then [y, 3, n] else [y, 4, n - 31] end
-end
-
-es = Date.new(*easter(Time.now.year))
-[[-9*7, 'Septuagesima Sunday'],
- [-8*7, 'Sexagesima Sunday'],
- [-7*7, 'Quinquagesima Sunday (Shrove Sunday)'],
- [-48, 'Shrove Monday'],
- [-47, 'Shrove Tuesday'],
- [-46, 'Ash Wednesday'],
- [-6*7, 'Quadragesima Sunday'],
- [-3*7, 'Mothering Sunday'],
- [-2*7, 'Passion Sunday'],
- [-7, 'Palm Sunday'],
- [-3, 'Maunday Thursday'],
- [-2, 'Good Friday'],
- [-1, 'Easter Eve'],
- [0, 'Easter Day'],
- [1, 'Easter Monday'],
- [7, 'Low Sunday'],
- [5*7, 'Rogation Sunday'],
- [39, 'Ascension Day (Holy Thursday)'],
- [42, 'Sunday after Ascension Day'],
- [7*7, 'Pentecost (Whitsunday)'],
- [50, 'Whitmonday'],
- [8*7, 'Trinity Sunday'],
- [60, 'Corpus Christi (Thursday after Trinity)']].
-each do |xs|
- puts((es + xs.shift).to_s + ' ' + xs.shift)
-end
diff --git a/sample/mine.rb b/sample/mine.rb
index 8fc27e0c6d..4ef006685e 100644
--- a/sample/mine.rb
+++ b/sample/mine.rb
@@ -1,4 +1,5 @@
#! /usr/bin/ruby -Ke
+# -*- encoding: euc-jp -*-
class Board
def clr
diff --git a/sample/mkproto.rb b/sample/mkproto.rb
index 754ca2dff2..6e7fc0f788 100644
--- a/sample/mkproto.rb
+++ b/sample/mkproto.rb
@@ -1,20 +1,20 @@
$/ = nil
while line = gets()
- if /^((void|VALUE|int|char *\*|ID|struct [\w_]+ *\*|st_table *\*) *)?\n([\w\d_]+)\(.*\)\n\s*((.+;\n)*)\{/ =~ line
+ if /^((void|VALUE|int|char *\*|ID|struct \w+ *\*|st_table *\*) *)?\n(\w+)\(.*\)\n\s*((.+;\n)*)\{/ =~ line
line = $'
printf "%s %s(", $2, $3
args = []
for arg in $4.split(/;\n\s*/)
arg.gsub!(/ +/, ' ')
if arg =~ /,/
- if arg =~ /(([^*]+) *\** *[\w\d_]+),/
+ if arg =~ /(([^*]+) *\** *\w+),/
type = $2.strip
args.push $1.strip
arg = $'
else
type = ""
end
- while arg.sub!(/(\** *[\w\d_]+)(,|$)/, "") && $~
+ while arg.sub!(/(\** *\w+)(,|$)/, "") && $~
args.push type + " " + $1.strip
end
else
diff --git a/sample/mrshtest.rb b/sample/mrshtest.rb
deleted file mode 100644
index 8d2dc9936b..0000000000
--- a/sample/mrshtest.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-include Marshal
-a = 25.6;
-pt = Struct.new('Point', :x,:y);
-x = pt.new(10, 10)
-y = pt.new(20, 20)
-rt = Struct.new('Rectangle', :origin,:corner);
-z = rt.new(x, y)
-c = Object.new
-s = [a, x, z, c, c, "fff"];
-p s
-d = dump(s);
-p d
-p load(d)
diff --git a/sample/occur.rb b/sample/occur.rb
index 8bb09e15ad..4ec6ae479b 100644
--- a/sample/occur.rb
+++ b/sample/occur.rb
@@ -1,8 +1,8 @@
# word occurrence listing
# usege: ruby occur.rb file..
freq = Hash.new(0)
-while gets()
- for word in split(/\W+/)
+while line = gets()
+ for word in line.split(/\W+/)
freq[word] += 1
end
end
diff --git a/sample/occur2.rb b/sample/occur2.rb
index 53885c0ba7..ca87d0ddef 100644
--- a/sample/occur2.rb
+++ b/sample/occur2.rb
@@ -1,13 +1,10 @@
# word occurrence listing
# usege: ruby occur2.rb file..
freq = {}
-while gets()
- for word in split(/\W+/)
- begin
- freq[word] += 1
- rescue NameError
- freq[word] = 1
- end
+ARGF.each_line do |line|
+ for word in line.split(/\W+/)
+ freq[word] ||= 0
+ freq[word] += 1
end
end
diff --git a/sample/openssl/c_rehash.rb b/sample/openssl/c_rehash.rb
index 386eef5f24..afbb654517 100644
--- a/sample/openssl/c_rehash.rb
+++ b/sample/openssl/c_rehash.rb
@@ -1,7 +1,7 @@
#!/usr/bin/env ruby
require 'openssl'
-require 'md5'
+require 'digest/md5'
class CHashDir
include Enumerable
@@ -161,7 +161,7 @@ private
end
def fingerprint(der)
- MD5.hexdigest(der).upcase
+ Digest::MD5.hexdigest(der).upcase
end
end
diff --git a/sample/openssl/cert_store_view.rb b/sample/openssl/cert_store_view.rb
deleted file mode 100644
index 26c4d527f7..0000000000
--- a/sample/openssl/cert_store_view.rb
+++ /dev/null
@@ -1,911 +0,0 @@
-#!/usr/bin/env ruby
-
-require 'fox'
-require 'openssl'
-require 'time'
-require 'certstore'
-require 'getopts'
-
-include Fox
-
-module CertDumpSupport
- def cert_label(cert)
- subject_alt_name =
- cert.extensions.find { |ext| ext.oid == 'subjectAltName' }
- if subject_alt_name
- subject_alt_name.value.split(/\s*,\s/).each do |alt_name_pair|
- alt_tag, alt_name = alt_name_pair.split(/:/)
- return alt_name
- end
- end
- name_label(cert.subject)
- end
-
- def name_label(name)
- ary = name.to_a
- if (cn = ary.find { |rdn| rdn[0] == 'CN' })
- return cn[1]
- end
- if ary.last[0] == 'OU'
- return ary.last[1]
- end
- name.to_s
- end
-
- def name_text(name)
- name.to_a.collect { |tag, value|
- "#{tag} = #{value}"
- }.reverse.join("\n")
- end
-
- def bn_label(bn)
- ("0" << sprintf("%X", bn)).scan(/../).join(" ")
- end
-end
-
-class CertDump
- include CertDumpSupport
-
- def initialize(cert)
- @cert = cert
- end
-
- def get_dump(tag)
- case tag
- when 'Version'
- version
- when 'Serial'
- serial
- when 'Signature Algorithm'
- signature_algorithm
- when 'Issuer'
- issuer
- when 'Validity'
- validity
- when 'Not before'
- not_before
- when 'Not after'
- not_after
- when 'Subject'
- subject
- when 'Public key'
- public_key
- else
- ext(tag)
- end
- end
-
- def get_dump_line(tag)
- case tag
- when 'Version'
- version_line
- when 'Serial'
- serial_line
- when 'Signature Algorithm'
- signature_algorithm_line
- when 'Subject'
- subject_line
- when 'Issuer'
- issuer_line
- when 'Validity'
- validity_line
- when 'Not before'
- not_before_line
- when 'Not after'
- not_after_line
- when 'Public key'
- public_key_line
- else
- ext_line(tag)
- end
- end
-
-private
-
- def version
- "Version: #{@cert.version + 1}"
- end
-
- def version_line
- version
- end
-
- def serial
- bn_label(@cert.serial)
- end
-
- def serial_line
- serial
- end
-
- def signature_algorithm
- @cert.signature_algorithm
- end
-
- def signature_algorithm_line
- signature_algorithm
- end
-
- def subject
- name_text(@cert.subject)
- end
-
- def subject_line
- @cert.subject.to_s
- end
-
- def issuer
- name_text(@cert.issuer)
- end
-
- def issuer_line
- @cert.issuer.to_s
- end
-
- def validity
- <<EOS
-Not before: #{not_before}
-Not after: #{not_after}
-EOS
- end
-
- def validity_line
- "from #{@cert.not_before.iso8601} to #{@cert.not_after.iso8601}"
- end
-
- def not_before
- @cert.not_before.to_s
- end
-
- def not_before_line
- not_before
- end
-
- def not_after
- @cert.not_after.to_s
- end
-
- def not_after_line
- not_after
- end
-
- def public_key
- @cert.public_key.to_text
- end
-
- def public_key_line
- "#{@cert.public_key.class} -- " << public_key.scan(/\A[^\n]*/)[0] << '...'
- end
-
- def ext(tag)
- @cert.extensions.each do |ext|
- if ext.oid == tag
- return ext_detail(tag, ext.value)
- end
- end
- "(unknown)"
- end
-
- def ext_line(tag)
- ext(tag).tr("\r\n", '')
- end
-
- def ext_detail(tag, value)
- value
- end
-end
-
-class CrlDump
- include CertDumpSupport
-
- def initialize(crl)
- @crl = crl
- end
-
- def get_dump(tag)
- case tag
- when 'Version'
- version
- when 'Signature Algorithm'
- signature_algorithm
- when 'Issuer'
- issuer
- when 'Last update'
- last_update
- when 'Next update'
- next_update
- else
- ext(tag)
- end
- end
-
- def get_dump_line(tag)
- case tag
- when 'Version'
- version_line
- when 'Signature Algorithm'
- signature_algorithm_line
- when 'Issuer'
- issuer_line
- when 'Last update'
- last_update_line
- when 'Next update'
- next_update_line
- else
- ext_line(tag)
- end
- end
-
-private
-
- def version
- "Version: #{@crl.version + 1}"
- end
-
- def version_line
- version
- end
-
- def signature_algorithm
- @crl.signature_algorithm
- end
-
- def signature_algorithm_line
- signature_algorithm
- end
-
- def issuer
- name_text(@crl.issuer)
- end
-
- def issuer_line
- @crl.issuer.to_s
- end
-
- def last_update
- @crl.last_update.to_s
- end
-
- def last_update_line
- last_update
- end
-
- def next_update
- @crl.next_update.to_s
- end
-
- def next_update_line
- next_update
- end
-
- def ext(tag)
- @crl.extensions.each do |ext|
- if ext.oid == tag
- return ext_detail(tag, ext.value)
- end
- end
- "(unknown)"
- end
-
- def ext_line(tag)
- ext(tag).tr("\r\n", '')
- end
-
- def ext_detail(tag, value)
- value
- end
-end
-
-class RevokedDump
- include CertDumpSupport
-
- def initialize(revoked)
- @revoked = revoked
- end
-
- def get_dump(tag)
- case tag
- when 'Serial'
- serial
- when 'Time'
- time
- else
- ext(tag)
- end
- end
-
- def get_dump_line(tag)
- case tag
- when 'Serial'
- serial_line
- when 'Time'
- time_line
- else
- ext_line(tag)
- end
- end
-
-private
-
- def serial
- bn_label(@revoked.serial)
- end
-
- def serial_line
- serial
- end
-
- def time
- @revoked.time.to_s
- end
-
- def time_line
- time
- end
-
- def ext(tag)
- @revoked.extensions.each do |ext|
- if ext.oid == tag
- return ext_detail(tag, ext.value)
- end
- end
- "(unknown)"
- end
-
- def ext_line(tag)
- ext(tag).tr("\r\n", '')
- end
-
- def ext_detail(tag, value)
- value
- end
-end
-
-class RequestDump
- include CertDumpSupport
-
- def initialize(req)
- @req = req
- end
-
- def get_dump(tag)
- case tag
- when 'Version'
- version
- when 'Signature Algorithm'
- signature_algorithm
- when 'Subject'
- subject
- when 'Public key'
- public_key
- else
- attributes(tag)
- end
- end
-
- def get_dump_line(tag)
- case tag
- when 'Version'
- version_line
- when 'Signature Algorithm'
- signature_algorithm_line
- when 'Subject'
- subject_line
- when 'Public key'
- public_key_line
- else
- attributes_line(tag)
- end
- end
-
-private
-
- def version
- "Version: #{@req.version + 1}"
- end
-
- def version_line
- version
- end
-
- def signature_algorithm
- @req.signature_algorithm
- end
-
- def signature_algorithm_line
- signature_algorithm
- end
-
- def subject
- name_text(@req.subject)
- end
-
- def subject_line
- @req.subject.to_s
- end
-
- def public_key
- @req.public_key.to_text
- end
-
- def public_key_line
- "#{@req.public_key.class} -- " << public_key.scan(/\A[^\n]*/)[0] << '...'
- end
-
- def attributes(tag)
- "(unknown)"
- end
-
- def attributes_line(tag)
- attributes(tag).tr("\r\n", '')
- end
-end
-
-class CertStoreView < FXMainWindow
- class CertTree
- include CertDumpSupport
-
- def initialize(observer, tree)
- @observer = observer
- @tree = tree
- @tree.connect(SEL_COMMAND) do |sender, sel, item|
- if item.data
- @observer.getApp().beginWaitCursor do
- @observer.show_item(item.data)
- end
- else
- @observer.show_item(nil)
- end
- end
- end
-
- def show(cert_store)
- @tree.clearItems
- @self_signed_ca_node = add_item_last(nil, "Trusted root CA")
- @other_ca_node = add_item_last(nil, "Intermediate CA")
- @ee_node = add_item_last(nil, "Personal")
- @crl_node = add_item_last(nil, "CRL")
- @request_node = add_item_last(nil, "Request")
- @verify_path_node = add_item_last(nil, "Certification path")
- show_certs(cert_store)
- end
-
- def show_certs(cert_store)
- remove_items(@self_signed_ca_node)
- remove_items(@other_ca_node)
- remove_items(@ee_node)
- remove_items(@crl_node)
- remove_items(@request_node)
- import_certs(cert_store)
- end
-
- def show_request(req)
- node = add_item_last(@request_node, name_label(req.subject), req)
- @tree.selectItem(node)
- @observer.show_item(req)
- end
-
- def show_verify_path(verify_path)
- add_verify_path(verify_path)
- end
-
- private
-
- def open_node(node)
- node.expanded = node.opened = true
- end
-
- def close_node(node)
- node.expanded = node.opened = false
- end
-
- def import_certs(cert_store)
- cert_store.self_signed_ca.each do |cert|
- add_item_last(@self_signed_ca_node, cert_label(cert), cert)
- end
- cert_store.other_ca.each do |cert|
- add_item_last(@other_ca_node, cert_label(cert), cert)
- end
- cert_store.ee.each do |cert|
- add_item_last(@ee_node, cert_label(cert), cert)
- end
- cert_store.crl.each do |crl|
- node = add_item_last(@crl_node, name_label(crl.issuer), crl)
- close_node(node)
- crl.revoked.each do |revoked|
- add_item_last(node, bn_label(revoked.serial), revoked)
- end
- end
- cert_store.request.each do |req|
- add_item_last(@requestnode, name_label(req.subject), req)
- end
- end
-
- def add_verify_path(verify_path)
- node = @verify_path_node
- last_cert = nil
- verify_path.reverse_each do |ok, cert, crl_check, error_string|
- warn = []
- if @observer.cert_store.is_ca?(cert)
- warn << 'NO ARL' unless crl_check
- else
- warn << 'NO CRL' unless crl_check
- end
- warn_str = '(' << warn.join(", ") << ')'
- warn_mark = warn.empty? ? '' : '!'
- label = if ok
- "OK#{warn_mark}..." + cert_label(cert)
- else
- "NG(#{error_string})..." + cert_label(cert)
- end
- label << warn_str unless warn.empty?
- node = add_item_last(node, label, cert)
- node.expanded = true
- last_cert = cert
- end
- if last_cert
- @tree.selectItem(node)
- @observer.show_item(last_cert)
- end
- end
-
- def add_item_last(parent, label, obj = nil)
- node = @tree.addItemLast(parent, FXTreeItem.new(label))
- node.data = obj if obj
- open_node(node)
- node
- end
-
- def remove_items(node)
- while node.getNumChildren > 0
- @tree.removeItem(node.getFirst)
- end
- end
- end
-
- class CertInfo
- def initialize(observer, table)
- @observer = observer
- @table = table
- @table.leadingRows = 0
- @table.leadingCols = 0
- @table.trailingRows = 0
- @table.trailingCols = 0
- @table.showVertGrid(false)
- @table.showHorzGrid(false)
- @table.setTableSize(1, 2)
- @table.setColumnWidth(0, 125)
- @table.setColumnWidth(1, 350)
- end
-
- def show(item)
- @observer.show_detail(nil, nil)
- if item.nil?
- set_column_size(1)
- return
- end
- case item
- when OpenSSL::X509::Certificate
- show_cert(item)
- when OpenSSL::X509::CRL
- show_crl(item)
- when OpenSSL::X509::Revoked
- show_revoked(item)
- when OpenSSL::X509::Request
- show_request(item)
- else
- raise NotImplementedError.new("Unknown item type #{item.class}.")
- end
- end
-
- private
-
- def show_cert(cert)
- wrap = CertDump.new(cert)
- items = []
- items << ['Version', wrap.get_dump_line('Version')]
- items << ['Signature Algorithm', wrap.get_dump_line('Signature Algorithm')]
- items << ['Issuer', wrap.get_dump_line('Issuer')]
- items << ['Serial', wrap.get_dump_line('Serial')]
- #items << ['Not before', wrap.get_dump_line('Not before')]
- #items << ['Not after', wrap.get_dump_line('Not after')]
- items << ['Subject', wrap.get_dump_line('Subject')]
- items << ['Public key', wrap.get_dump_line('Public key')]
- items << ['Validity', wrap.get_dump_line('Validity')]
- (cert.extensions.sort { |a, b| a.oid <=> b.oid }).each do |ext|
- items << [ext.oid, wrap.get_dump_line(ext.oid)]
- end
- show_items(cert, items)
- end
-
- def show_crl(crl)
- wrap = CrlDump.new(crl)
- items = []
- items << ['Version', wrap.get_dump_line('Version')]
- items << ['Signature Algorithm', wrap.get_dump_line('Signature Algorithm')]
- items << ['Issuer', wrap.get_dump_line('Issuer')]
- items << ['Last update', wrap.get_dump_line('Last update')]
- items << ['Next update', wrap.get_dump_line('Next update')]
- crl.extensions.each do |ext|
- items << [ext.oid, wrap.get_dump_line(ext.oid)]
- end
- show_items(crl, items)
- end
-
- def show_revoked(revoked)
- wrap = RevokedDump.new(revoked)
- items = []
- items << ['Serial', wrap.get_dump_line('Serial')]
- items << ['Time', wrap.get_dump_line('Time')]
- revoked.extensions.each do |ext|
- items << [ext.oid, wrap.get_dump_line(ext.oid)]
- end
- show_items(revoked, items)
- end
-
- def show_request(req)
- wrap = RequestDump.new(req)
- items = []
- items << ['Version', wrap.get_dump_line('Version')]
- items << ['Signature Algorithm', wrap.get_dump_line('Signature Algorithm')]
- items << ['Subject', wrap.get_dump_line('Subject')]
- items << ['Public key', wrap.get_dump_line('Public key')]
- req.attributes.each do |attr|
- items << [attr.attr, wrap.get_dump_line(attr.oid)]
- end
- show_items(req, items)
- end
-
- def show_items(obj, items)
- set_column_size(items.size)
- items.each_with_index do |ele, idx|
- tag, value = ele
- @table.setItemText(idx, 0, tag)
- @table.getItem(idx, 0).data = tag
- @table.setItemText(idx, 1, value.to_s)
- @table.getItem(idx, 1).data = tag
- end
- @table.connect(SEL_COMMAND) do |sender, sel, loc|
- item = @table.getItem(loc.row, loc.col)
- @observer.show_detail(obj, item.data)
- end
- justify_table
- end
-
- def set_column_size(size)
- col0_width = @table.getColumnWidth(0)
- col1_width = @table.getColumnWidth(1)
- @table.setTableSize(size, 2)
- @table.setColumnWidth(0, col0_width)
- @table.setColumnWidth(1, col1_width)
- end
-
- def justify_table
- for col in 0..@table.numCols-1
- for row in 0..@table.numRows-1
- @table.getItem(row, col).justify = FXTableItem::LEFT
- end
- end
- end
- end
-
- class CertDetail
- def initialize(observer, detail)
- @observer = observer
- @detail = detail
- end
-
- def show(item, tag)
- if item.nil?
- @detail.text = ''
- return
- end
- case item
- when OpenSSL::X509::Certificate
- show_cert(item, tag)
- when OpenSSL::X509::CRL
- show_crl(item, tag)
- when OpenSSL::X509::Revoked
- show_revoked(item, tag)
- when OpenSSL::X509::Request
- show_request(item, tag)
- else
- raise NotImplementedError.new("Unknown item type #{item.class}.")
- end
- end
-
- private
-
- def show_cert(cert, tag)
- wrap = CertDump.new(cert)
- @detail.text = wrap.get_dump(tag)
- end
-
- def show_crl(crl, tag)
- wrap = CrlDump.new(crl)
- @detail.text = wrap.get_dump(tag)
- end
-
- def show_revoked(revoked, tag)
- wrap = RevokedDump.new(revoked)
- @detail.text = wrap.get_dump(tag)
- end
-
- def show_request(request, tag)
- wrap = RequestDump.new(request)
- @detail.text = wrap.get_dump(tag)
- end
- end
-
- attr_reader :cert_store
-
- def initialize(app, cert_store)
- @cert_store = cert_store
- @verify_filter = 0
- @verify_filename = nil
- full_width = 800
- full_height = 500
- horz_pos = 300
-
- super(app, "Certificate store", nil, nil, DECOR_ALL, 0, 0, full_width,
- full_height)
-
- FXTooltip.new(self.getApp())
-
- menubar = FXMenubar.new(self, LAYOUT_SIDE_TOP|LAYOUT_FILL_X)
- file_menu = FXMenuPane.new(self)
- FXMenuTitle.new(menubar, "&File", nil, file_menu)
- file_open_menu = FXMenuPane.new(self)
- FXMenuCommand.new(file_open_menu, "&Directory\tCtl-O").connect(SEL_COMMAND,
- method(:on_cmd_file_open_dir))
- FXMenuCascade.new(file_menu, "&Open\tCtl-O", nil, file_open_menu)
- FXMenuCommand.new(file_menu, "&Quit\tCtl-Q", nil, getApp(), FXApp::ID_QUIT)
-
- tool_menu = FXMenuPane.new(self)
- FXMenuTitle.new(menubar, "&Tool", nil, tool_menu)
- FXMenuCommand.new(tool_menu, "&Verify\tCtl-N").connect(SEL_COMMAND,
- method(:on_cmd_tool_verify))
- FXMenuCommand.new(tool_menu, "&Show Request\tCtl-R").connect(SEL_COMMAND,
- method(:on_cmd_tool_request))
-
- base_frame = FXHorizontalFrame.new(self, LAYOUT_FILL_X | LAYOUT_FILL_Y)
- splitter_horz = FXSplitter.new(base_frame, LAYOUT_SIDE_TOP | LAYOUT_FILL_X |
- LAYOUT_FILL_Y | SPLITTER_TRACKING | SPLITTER_HORIZONTAL)
-
- # Cert tree
- cert_tree_frame = FXHorizontalFrame.new(splitter_horz, LAYOUT_FILL_X |
- LAYOUT_FILL_Y | FRAME_SUNKEN | FRAME_THICK)
- cert_tree_frame.setWidth(horz_pos)
- cert_tree = FXTreeList.new(cert_tree_frame, 0, nil, 0,
- TREELIST_BROWSESELECT | TREELIST_SHOWS_LINES | TREELIST_SHOWS_BOXES |
- TREELIST_ROOT_BOXES | LAYOUT_FILL_X | LAYOUT_FILL_Y)
- @cert_tree = CertTree.new(self, cert_tree)
-
- # Cert info
- splitter_vert = FXSplitter.new(splitter_horz, LAYOUT_SIDE_TOP |
- LAYOUT_FILL_X | LAYOUT_FILL_Y | SPLITTER_TRACKING | SPLITTER_VERTICAL |
- SPLITTER_REVERSED)
- cert_list_base = FXVerticalFrame.new(splitter_vert, LAYOUT_FILL_X |
- LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0)
- cert_list_frame = FXHorizontalFrame.new(cert_list_base, FRAME_SUNKEN |
- FRAME_THICK | LAYOUT_FILL_X | LAYOUT_FILL_Y)
- cert_info = FXTable.new(cert_list_frame, 2, 10, nil, 0, FRAME_SUNKEN |
- TABLE_COL_SIZABLE | LAYOUT_FILL_X | LAYOUT_FILL_Y, 0, 0, 0, 0, 2, 2, 2, 2)
- @cert_info = CertInfo.new(self, cert_info)
-
- cert_detail_base = FXVerticalFrame.new(splitter_vert, LAYOUT_FILL_X |
- LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0)
- cert_detail_frame = FXHorizontalFrame.new(cert_detail_base, FRAME_SUNKEN |
- FRAME_THICK | LAYOUT_FILL_X | LAYOUT_FILL_Y)
- cert_detail = FXText.new(cert_detail_frame, nil, 0, TEXT_READONLY |
- LAYOUT_FILL_X | LAYOUT_FILL_Y)
- @cert_detail = CertDetail.new(self, cert_detail)
-
- show_init
- end
-
- def create
- super
- show(PLACEMENT_SCREEN)
- end
-
- def show_init
- @cert_tree.show(@cert_store)
- show_item(nil)
- end
-
- def show_certs
- @cert_tree.show_certs(@cert_store)
- end
-
- def show_request(req)
- @cert_tree.show_request(req)
- end
-
- def show_verify_path(verify_path)
- @cert_tree.show_verify_path(verify_path)
- end
-
- def show_item(item)
- @cert_info.show(item) if @cert_info
- end
-
- def show_detail(item, tag)
- @cert_detail.show(item, tag) if @cert_detail
- end
-
- def verify(certfile)
- path = verify_certfile(certfile)
- show_certs # CRL could be change.
- show_verify_path(path)
- end
-
-private
-
- def on_cmd_file_open_dir(sender, sel, ptr)
- dir = FXFileDialog.getOpenDirectory(self, "Open certificate directory", ".")
- unless dir.empty?
- begin
- @cert_store = CertStore.new(dir)
- rescue
- show_error($!)
- end
- show_init
- end
- 1
- end
-
- def on_cmd_tool_verify(sender, sel, ptr)
- dialog = FXFileDialog.new(self, "Verify certificate")
- dialog.filename = ''
- dialog.patternList = ["All Files (*)", "PEM formatted certificate (*.pem)"]
- dialog.currentPattern = @verify_filter
- if dialog.execute != 0
- @verify_filename = dialog.filename
- verify(@verify_filename)
- end
- @verify_filter = dialog.currentPattern
- 1
- end
-
- def on_cmd_tool_request(sender, sel, ptr)
- dialog = FXFileDialog.new(self, "Show request")
- dialog.filename = ''
- dialog.patternList = ["All Files (*)", "PEM formatted certificate (*.pem)"]
- if dialog.execute != 0
- req = @cert_store.generate_cert(dialog.filename)
- show_request(req)
- end
- 1
- end
-
- def verify_certfile(filename)
- begin
- cert = @cert_store.generate_cert(filename)
- result = @cert_store.verify(cert)
- @cert_store.scan_certs
- result
- rescue
- show_error($!)
- []
- end
- end
-
- def show_error(e)
- msg = e.inspect + "\n" + e.backtrace.join("\n")
- FXMessageBox.error(self, MBOX_OK, "Error", msg)
- end
-end
-
-getopts nil, "cert:"
-
-certs_dir = ARGV.shift or raise "#{$0} cert_dir"
-certfile = $OPT_cert
-app = FXApp.new("CertStore", "FoxTest")
-cert_store = CertStore.new(certs_dir)
-w = CertStoreView.new(app, cert_store)
-app.create
-if certfile
- w.verify(certfile)
-end
-app.run
diff --git a/sample/openssl/cipher.rb b/sample/openssl/cipher.rb
index 6e8cdb9427..58b10d6046 100644
--- a/sample/openssl/cipher.rb
+++ b/sample/openssl/cipher.rb
@@ -1,33 +1,54 @@
#!/usr/bin/env ruby
require 'openssl'
-text = "abcdefghijklmnopqrstuvwxyz"
-pass = "secret password"
-salt = "8 octets" # or nil
-alg = "DES-EDE3-CBC"
-#alg = "AES-128-CBC"
+def crypt_by_password(alg, pass, salt, text)
+ puts "--Setup--"
+ puts %(cipher alg: "#{alg}")
+ puts %(plain text: "#{text}")
+ puts %(password: "#{pass}")
+ puts %(salt: "#{salt}")
+ puts
-puts "--Setup--"
-puts %(clear text: "#{text}")
-puts %(password: "#{pass}")
-puts %(salt: "#{salt}")
-puts %(cipher alg: "#{alg}")
-puts
+ puts "--Encrypting--"
+ enc = OpenSSL::Cipher::Cipher.new(alg)
+ enc.encrypt
+ enc.pkcs5_keyivgen(pass, salt)
+ cipher = enc.update(text)
+ cipher << enc.final
+ puts %(encrypted text: #{cipher.inspect})
+ puts
-puts "--Encrypting--"
-des = OpenSSL::Cipher::Cipher.new(alg)
-des.pkcs5_keyivgen(pass, salt)
-des.encrypt
-cipher = des.update(text)
-cipher << des.final
-puts %(encrypted text: #{cipher.inspect})
-puts
+ puts "--Decrypting--"
+ dec = OpenSSL::Cipher::Cipher.new(alg)
+ dec.decrypt
+ dec.pkcs5_keyivgen(pass, salt)
+ plain = dec.update(cipher)
+ plain << dec.final
+ puts %(decrypted text: "#{plain}")
+ puts
+end
+
+def ciphers
+ ciphers = OpenSSL::Cipher.ciphers.sort
+ ciphers.each{|i|
+ if i.upcase != i && ciphers.include?(i.upcase)
+ ciphers.delete(i)
+ end
+ }
+ return ciphers
+end
-puts "--Decrypting--"
-des = OpenSSL::Cipher::Cipher.new(alg)
-des.pkcs5_keyivgen(pass, salt)
-des.decrypt
-out = des.update(cipher)
-out << des.final
-puts %(decrypted text: "#{out}")
+puts "Supported ciphers in #{OpenSSL::OPENSSL_VERSION}:"
+ciphers.each_with_index{|name, i|
+ printf("%-15s", name)
+ puts if (i + 1) % 5 == 0
+}
puts
+puts
+
+alg = ARGV.shift || ciphers.first
+pass = "secret password"
+salt = "8 octets" # or nil
+text = "abcdefghijklmnopqrstuvwxyz"
+
+crypt_by_password(alg, pass, salt, text)
diff --git a/sample/openssl/echo_cli.rb b/sample/openssl/echo_cli.rb
index 29b356a7ad..069a21ec94 100644
--- a/sample/openssl/echo_cli.rb
+++ b/sample/openssl/echo_cli.rb
@@ -2,15 +2,15 @@
require 'socket'
require 'openssl'
-require 'getopts'
+require 'optparse'
-getopts nil, "p:2000", "c:", "k:", "C:"
+options = ARGV.getopts("p:c:k:C:")
host = ARGV[0] || "localhost"
-port = $OPT_p
-cert_file = $OPT_c
-key_file = $OPT_k
-ca_path = $OPT_C
+port = options["p"] || "2000"
+cert_file = options["c"]
+key_file = options["k"]
+ca_path = options["C"]
ctx = OpenSSL::SSL::SSLContext.new()
if cert_file && key_file
@@ -27,11 +27,18 @@ end
s = TCPSocket.new(host, port)
ssl = OpenSSL::SSL::SSLSocket.new(s, ctx)
ssl.connect # start SSL session
+p ssl.peer_cert
+errors = Hash.new
+OpenSSL::X509.constants.grep(/^V_(ERR_|OK)/).each do |name|
+ errors[OpenSSL::X509.const_get(name)] = name
+end
+p errors[ssl.verify_result]
+
ssl.sync_close = true # if true the underlying socket will be
# closed in SSLSocket#close. (default: false)
while line = $stdin.gets
ssl.write line
- print ssl.gets
+ puts ssl.gets.inspect
end
ssl.close
diff --git a/sample/openssl/echo_svr.rb b/sample/openssl/echo_svr.rb
index be8e10fa26..719de6be84 100644
--- a/sample/openssl/echo_svr.rb
+++ b/sample/openssl/echo_svr.rb
@@ -2,14 +2,14 @@
require 'socket'
require 'openssl'
-require 'getopts'
+require 'optparse'
-getopts nil, "p:2000", "c:", "k:", "C:"
+options = ARGV.getopts("p:c:k:C:")
-port = $OPT_p
-cert_file = $OPT_c
-key_file = $OPT_k
-ca_path = $OPT_C
+port = options["p"] || "2000"
+cert_file = options["c"]
+key_file = options["k"]
+ca_path = options["C"]
if cert_file && key_file
cert = OpenSSL::X509::Certificate.new(File::read(cert_file))
@@ -55,8 +55,11 @@ tcps = TCPServer.new(port)
ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
loop do
ns = ssls.accept
+ puts "connected from #{ns.peeraddr}"
while line = ns.gets
+ puts line.inspect
ns.write line
end
+ puts "connection closed"
ns.close
end
diff --git a/sample/openssl/gen_csr.rb b/sample/openssl/gen_csr.rb
index 5858acd9f2..4228707fdb 100644
--- a/sample/openssl/gen_csr.rb
+++ b/sample/openssl/gen_csr.rb
@@ -1,6 +1,6 @@
#!/usr/bin/env ruby
-require 'getopts'
+require 'optparse'
require 'openssl'
include OpenSSL
@@ -14,14 +14,13 @@ EOS
exit
end
-getopts nil, "key:", "csrout:", "keyout:"
-keypair_file = $OPT_key
-csrout = $OPT_csrout || "csr.pem"
-keyout = $OPT_keyout || "keypair.pem"
+options = ARGV.getopts(nil, "key:", "csrout:", "keyout:")
+keypair_file = options["key"]
+csrout = options["csrout"] || "csr.pem"
+keyout = options["keyout"] || "keypair.pem"
$stdout.sync = true
name_str = ARGV.shift or usage()
-p name_str
name = X509::Name.parse(name_str)
keypair = nil
@@ -48,3 +47,5 @@ puts "Writing #{csrout}..."
File.open(csrout, "w") do |f|
f << req.to_pem
end
+puts req.to_text
+puts req.to_pem
diff --git a/sample/openssl/smime_read.rb b/sample/openssl/smime_read.rb
index 0f08f54f7e..17394f9b8d 100644
--- a/sample/openssl/smime_read.rb
+++ b/sample/openssl/smime_read.rb
@@ -1,12 +1,12 @@
-require 'getopts'
+require 'optparse'
require 'openssl'
include OpenSSL
-getopts nil, "c:", "k:", "C:"
+options = ARGV.getopts("c:k:C:")
-cert_file = $OPT_c
-key_file = $OPT_k
-ca_path = $OPT_C
+cert_file = options["c"]
+key_file = options["k"]
+ca_path = options["C"]
data = $stdin.read
diff --git a/sample/openssl/smime_write.rb b/sample/openssl/smime_write.rb
index ce32cd8146..535b3d6685 100644
--- a/sample/openssl/smime_write.rb
+++ b/sample/openssl/smime_write.rb
@@ -1,12 +1,12 @@
require 'openssl'
-require 'getopts'
+require 'optparse'
include OpenSSL
-getopts nil, "c:", "k:", "r:"
+options = ARGV.getopts("c:k:r:")
-cert_file = $OPT_c
-key_file = $OPT_k
-rcpt_file = $OPT_r
+cert_file = options["c"]
+key_file = options["k"]
+rcpt_file = options["r"]
cert = X509::Certificate.new(File::read(cert_file))
key = PKey::RSA.new(File::read(key_file))
diff --git a/sample/openssl/wget.rb b/sample/openssl/wget.rb
index 0362ab980d..ee637204db 100644
--- a/sample/openssl/wget.rb
+++ b/sample/openssl/wget.rb
@@ -1,11 +1,11 @@
#!/usr/bin/env ruby
require 'net/https'
-require 'getopts'
+require 'optparse'
-getopts nil, 'C:'
+options = ARGV.getopts('C:')
-ca_path = $OPT_C
+cert_store = options["C"]
uri = URI.parse(ARGV[0])
if proxy = ENV['HTTP_PROXY']
@@ -18,11 +18,12 @@ h = Net::HTTP.new(uri.host, uri.port, prx_host, prx_port)
h.set_debug_output($stderr) if $DEBUG
if uri.scheme == "https"
h.use_ssl = true
- if ca_path
- h.verify_mode = OpenSSL::SSL::VERIFY_PEER
- h.ca_path = ca_path
- else
- $stderr.puts "!!! WARNING: PEER CERTIFICATE WON'T BE VERIFIED !!!"
+ if cert_store
+ if File.directory?(cert_store)
+ h.ca_path = cert_store
+ else
+ h.ca_file = cert_store
+ end
end
end
diff --git a/sample/optparse/opttest.rb b/sample/optparse/opttest.rb
index 61b157bce5..9247af494f 100644
--- a/sample/optparse/opttest.rb
+++ b/sample/optparse/opttest.rb
@@ -13,7 +13,7 @@ ARGV.options do
|opts|
opts.banner << " argv..."
- # separater
+ # separator
opts.on_tail
opts.on_tail("common options:")
@@ -23,49 +23,49 @@ ARGV.options do
# mandatory argument
opts.on("-r", "--require=LIBRARY", String,
"require the LIBRARY, before",
- "executing your script") {|@library|}
+ "executing your script") {|lib|@library=lib}
# optional argument
opts.on("-i", "--inplace=[EXTENSION]",
"edit ARGV files in place", # multiline description
- "(make backup if EXTENSION supplied)") {|@inplace| @inplace ||= ''}
+ "(make backup if EXTENSION supplied)") {|inplace| @inplace = inplace || ''}
- opts.on("-N=[NUM]", Integer) {|@number|}
+ opts.on("-N=[NUM]", Integer) {|num|@number=num}
# additional class
- opts.on("-t", "--[no-]time[=TIME]", Time, "it's the time") {|@time|}
+ opts.on("-t", "--[no-]time[=TIME]", Time, "it's the time") {|time|@time=time}
# limit argument syntax
opts.on("-[0-7]", "-F", "--irs=[OCTAL]", OptionParser::OctalInteger,
- "specify record separator", "(\\0, if no argument)") {|@irs|}
+ "specify record separator", "(\\0, if no argument)") {|irs|@irs=irs}
# boolean switch(default true)
@exec = true
- opts.on("-n", "--no-exec[=FLAG]", TrueClass, "not really execute") {|@exec|}
+ opts.on("-n", "--no-exec[=FLAG]", TrueClass, "not really execute") {|exec|@exec=exec}
# array
- opts.on("-a", "--list[=LIST,LIST]", Array, "list") {|@list|}
+ opts.on("-a", "--list[=LIST,LIST]", Array, "list") {|list|@list=list}
# fixed size array
- opts.on("--pair[=car,cdr]", Array, "pair") {|@x, @y|}
+ opts.on("--pair[=car,cdr]", Array, "pair") {|x,y|@x=x; @y=y}
# keyword completion
opts.on("--code=CODE", CODES, CODE_ALIASES, "select coding system",
- "("+CODES.join(",")+",", " "+CODE_ALIASES.keys.join(",")+")") {|@code|}
+ "("+CODES.join(",")+",", " "+CODE_ALIASES.keys.join(",")+")") {|c|@code=c}
# optional argument with keyword completion
- opts.on("--type[=TYPE]", [:text, :binary], "select type(text, binary)") {|@type|}
+ opts.on("--type[=TYPE]", [:text, :binary], "select type(text, binary)") {|t|@type=t}
# boolean switch with optional argument(default false)
- opts.on("-v", "--[no-]verbose=[FLAG]", "run verbosely") {|@verbose|}
+ opts.on("-v", "--[no-]verbose=[FLAG]", "run verbosely") {|v|@verbose=v}
# easy way, set local variable
- opts.on("-q", "--quit", "quit when ARGV is empty") {|@quit|}
+ opts.on("-q", "--quit", "quit when ARGV is empty") {|q|@quit=q}
# adding on the fly
opts.on("--add=SWITCH=[ARG]", "add option on the fly", /\A(\w+)(?:=.+)?\Z/) do
|opt, var|
- opts.on("--#{opt}", "added in runtime", &eval("proc {|@#{var}|}"))
+ opts.on("--#{opt}", "added in runtime", &eval("proc {|x|@#{var}=x}"))
end
opts.on_head("specific options:")
@@ -79,7 +79,7 @@ ARGV.options do
end
pp self
-(print ARGV.options; exit) if @quit
+begin print ARGV.options; exit end if @quit
ARGV.options = nil # no more parse
puts "ARGV = #{ARGV.join(' ')}" if !ARGV.empty?
#opts.variable.each {|sym| puts "#{sym} = #{opts.send(sym).inspect}"}
diff --git a/sample/philos.rb b/sample/philos.rb
index 119e7c36b9..5c8f43c819 100644
--- a/sample/philos.rb
+++ b/sample/philos.rb
@@ -25,7 +25,7 @@ def eat(n)
end
def philosopher(n)
- while TRUE
+ while true
think n
$forks[n].lock
if not $forks[(n+1)%N].try_lock
diff --git a/sample/pty/expect_sample.rb b/sample/pty/expect_sample.rb
new file mode 100644
index 0000000000..d3b072b83c
--- /dev/null
+++ b/sample/pty/expect_sample.rb
@@ -0,0 +1,48 @@
+#
+# sample program of expect.rb
+#
+# by A. Ito
+#
+# This program reports the latest version of ruby interpreter
+# by connecting to ftp server at ruby-lang.org.
+#
+require 'pty'
+require 'expect'
+
+fnames = []
+PTY.spawn("ftp ftp.ruby-lang.org") do |r_f,w_f,pid|
+ w_f.sync = true
+
+ $expect_verbose = false
+
+ if !ENV['USER'].nil?
+ username = ENV['USER']
+ elsif !ENV['LOGNAME'].nil?
+ username = ENV['LOGNAME']
+ else
+ username = 'guest'
+ end
+
+ r_f.expect(/^(Name).*: |(word):|> /) do
+ w_f.puts($1 ? "ftp" : $2 ? "#{username}@" : "cd pub/ruby")
+ end
+ r_f.expect("> ") do
+ w_f.print "dir\n"
+ end
+
+ r_f.expect(/[^\-]> /) do |output|
+ for x in output[0].split("\n")
+ if x =~ /(ruby.*?\.tar\.gz)/ then
+ fnames.push $1
+ end
+ end
+ end
+ begin
+ w_f.print "quit\n"
+ rescue
+ end
+end
+
+print "The latest ruby interpreter is "
+print fnames.sort.pop
+print "\n"
diff --git a/sample/pty/script.rb b/sample/pty/script.rb
new file mode 100644
index 0000000000..903a6f75bd
--- /dev/null
+++ b/sample/pty/script.rb
@@ -0,0 +1,37 @@
+require 'pty'
+
+if ARGV.size == 0 then
+ ofile = "typescript"
+else
+ ofile = ARGV[0]
+end
+
+logfile = File.open(ofile,"a")
+
+system "stty -echo raw lnext ^_"
+
+PTY.spawn("/bin/csh") do |r_pty,w_pty,pid|
+
+ Thread.new do
+ while true
+ w_pty.print STDIN.getc.chr
+ w_pty.flush
+ end
+ end
+
+ begin
+ while true
+ c = r_pty.sysread(512)
+ break if c.nil?
+ print c
+ STDOUT.flush
+ logfile.print c
+ end
+ rescue
+ # print $@,':',$!,"\n"
+ logfile.close
+ end
+end
+
+system "stty echo -raw lnext ^v"
+
diff --git a/sample/pty/shl.rb b/sample/pty/shl.rb
new file mode 100644
index 0000000000..cdaf8d7398
--- /dev/null
+++ b/sample/pty/shl.rb
@@ -0,0 +1,92 @@
+#
+# old-fashioned 'shl' like program
+# by A. Ito
+#
+# commands:
+# c creates new shell
+# C-z suspends shell
+# p lists all shell
+# 0,1,... choose shell
+# q quit
+
+require 'pty'
+
+$shells = []
+$n_shells = 0
+
+$r_pty = nil
+$w_pty = nil
+
+def writer
+ system "stty -echo raw"
+ begin
+ while true
+ c = STDIN.getc
+ if c == 26 then # C-z
+ $reader.raise(nil)
+ return 'Suspend'
+ end
+ $w_pty.print c.chr
+ $w_pty.flush
+ end
+ rescue
+ $reader.raise(nil)
+ return 'Exit'
+ ensure
+ system "stty echo -raw"
+ end
+end
+
+$reader = Thread.new {
+ while true
+ begin
+ next if $r_pty.nil?
+ c = $r_pty.getc
+ if c.nil? then
+ Thread.stop
+ end
+ print c.chr
+ STDOUT.flush
+ rescue
+ Thread.stop
+ end
+ end
+}
+
+# $reader.raise(nil)
+
+
+while true
+ print ">> "
+ STDOUT.flush
+ case gets
+ when /^c/i
+ $shells[$n_shells] = PTY.spawn("/bin/csh")
+ $r_pty,$w_pty = $shells[$n_shells]
+ $n_shells += 1
+ $reader.run
+ if writer == 'Exit'
+ $n_shells -= 1
+ $shells[$n_shells] = nil
+ end
+ when /^p/i
+ for i in 0..$n_shells
+ unless $shells[i].nil?
+ print i,"\n"
+ end
+ end
+ when /^([0-9]+)/
+ n = $1.to_i
+ if $shells[n].nil?
+ print "\##{i} doesn't exist\n"
+ else
+ $r_pty,$w_pty = $shells[n]
+ $reader.run
+ if writer == 'Exit' then
+ $shells[n] = nil
+ end
+ end
+ when /^q/i
+ exit
+ end
+end
diff --git a/sample/rdoc/markup/rdoc2latex.rb b/sample/rdoc/markup/rdoc2latex.rb
new file mode 100644
index 0000000000..aa8079eb90
--- /dev/null
+++ b/sample/rdoc/markup/rdoc2latex.rb
@@ -0,0 +1,15 @@
+#!/usr/local/bin/ruby
+# Illustration of a script to convert an RDoc-style file to a LaTeX document
+
+require 'rdoc/markup'
+require 'rdoc/markup/to_latex'
+
+p = RDoc::Markup.new
+h = RDoc::Markup::ToLaTeX.new
+
+#puts "\\documentclass{report}"
+#puts "\\usepackage{tabularx}"
+#puts "\\usepackage{parskip}"
+#puts "\\begin{document}"
+puts p.convert(ARGF.read, h)
+#puts "\\end{document}"
diff --git a/sample/rdoc/markup/sample.rb b/sample/rdoc/markup/sample.rb
new file mode 100644
index 0000000000..db5d88d150
--- /dev/null
+++ b/sample/rdoc/markup/sample.rb
@@ -0,0 +1,40 @@
+# This program illustrates the basic use of the SimpleMarkup
+# class. It extracts the first comment block from the
+# simple_markup.rb file and converts it into HTML on
+# standard output. Run it using
+#
+# % ruby sample.rb
+#
+# You should be in the sample/rdoc/markup/ directory when you do this,
+# as it hardwires the path to the files it needs to require.
+# This isn't necessary in the code you write once you've
+# installed the package.
+#
+# For a better way of formatting code comment blocks (and more)
+# see the rdoc package.
+#
+
+require 'rdoc/markup/simple_markup'
+require 'rdoc/markup/simple_markup/to_html'
+
+# Extract the comment block from the source file
+
+input_string = ""
+
+File.foreach("../../../lib/rdoc/markup/simple_markup.rb") do |line|
+ break unless line.gsub!(/^\# ?/, '')
+ input_string << line
+end
+
+# Create a markup object
+markup = SM::SimpleMarkup.new
+
+# Attach it to an HTML formatter
+h = SM::ToHtml.new
+
+# And convert out comment block to html. Wrap it a body
+# tag pair to let browsers view it
+
+puts "<html><body>"
+puts markup.convert(input_string, h)
+puts "</body></html>"
diff --git a/sample/regx.rb b/sample/regx.rb
deleted file mode 100644
index aaf4b5f1ee..0000000000
--- a/sample/regx.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-st = "\033[7m"
-en = "\033[m"
-#st = "<<"
-#en = ">>"
-
-while TRUE
- print "str> "
- STDOUT.flush
- input = gets
- break if not input
- if input != ""
- str = input
- str.chop!
- end
- print "pat> "
- STDOUT.flush
- re = gets
- break if not re
- re.chop!
- str.gsub! re, "#{st}\\&#{en}"
- print str, "\n"
-end
-print "\n"
diff --git a/sample/ripper/ruby2html.rb b/sample/ripper/ruby2html.rb
new file mode 100644
index 0000000000..8f64f5a713
--- /dev/null
+++ b/sample/ripper/ruby2html.rb
@@ -0,0 +1,112 @@
+#!/usr/bin/env ruby
+# $originalId: ruby2html.rb,v 1.2 2005/09/23 22:53:47 aamine Exp $
+
+TEMPLATE_LINE = __LINE__ + 2
+TEMPLATE = <<-EndTemplate
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=<%= encoding %>">
+<% if css %>
+ <link rel="stylesheet" type="text/css" href="<%= css %>">
+<% end %>
+ <title><%= File.basename(f.path) %></title>
+</head>
+<body>
+<pre>
+<%
+ if print_line_number
+ Ruby2HTML.compile(f).each_with_index do |line, idx|
+%><%= sprintf('%4d %s', idx+1, line) %><%
+ end
+ else
+%><%= Ruby2HTML.compile(f) %><%
+ end
+%>
+</pre>
+</body>
+</html>
+EndTemplate
+
+require 'ripper'
+require 'stringio'
+require 'cgi'
+require 'erb'
+require 'optparse'
+
+def main
+ encoding = 'us-ascii'
+ css = nil
+ print_line_number = false
+ parser = OptionParser.new
+ parser.banner = "Usage: #{File.basename($0)} [-l] [<file>...]"
+ parser.on('--encoding=NAME', 'Character encoding [us-ascii].') {|name|
+ encoding = name
+ }
+ parser.on('--css=URL', 'Set a link to CSS.') {|url|
+ css = url
+ }
+ parser.on('-l', '--line-number', 'Show line number.') {
+ print_line_number = true
+ }
+ parser.on('--help', 'Prints this message and quit.') {
+ puts parser.help
+ exit 0
+ }
+ begin
+ parser.parse!
+ rescue OptionParser::ParseError => err
+ $stderr.puts err
+ $stderr.puts parser.help
+ exit 1
+ end
+ puts ruby2html(ARGF, encoding, css, print_line_number)
+end
+
+class ERB
+ attr_accessor :lineno
+
+ remove_method :result
+ def result(b)
+ eval(@src, b, (@filename || '(erb)'), (@lineno || 1))
+ end
+end
+
+def ruby2html(f, encoding, css, print_line_number)
+ erb = ERB.new(TEMPLATE, nil, '>')
+ erb.filename = __FILE__
+ erb.lineno = TEMPLATE_LINE
+ erb.result(binding())
+end
+
+class Ruby2HTML < Ripper::Filter
+ def Ruby2HTML.compile(f)
+ buf = StringIO.new
+ Ruby2HTML.new(f).parse(buf)
+ buf.string
+ end
+
+ def on_default(event, tok, f)
+ f << CGI.escapeHTML(tok)
+ end
+
+ def on_kw(tok, f)
+ f << %Q[<span class="resword">#{CGI.escapeHTML(tok)}</span>]
+ end
+
+ def on_comment(tok, f)
+ f << %Q[<span class="comment">#{CGI.escapeHTML(tok.rstrip)}</span>\n]
+ end
+
+ def on_tstring_beg(tok, f)
+ f << %Q[<span class="string">#{CGI.escapeHTML(tok)}]
+ end
+
+ def on_tstring_end(tok, f)
+ f << %Q[#{CGI.escapeHTML(tok)}</span>]
+ end
+end
+
+if $0 == __FILE__
+ main
+end
diff --git a/sample/ripper/strip-comment.rb b/sample/ripper/strip-comment.rb
new file mode 100644
index 0000000000..bd26b6a377
--- /dev/null
+++ b/sample/ripper/strip-comment.rb
@@ -0,0 +1,19 @@
+# $Id$
+
+require 'ripper/filter'
+
+class CommentStripper < Ripper::Filter
+ def CommentStripper.strip(src)
+ new(src).parse(nil)
+ end
+
+ def on_default(event, token, data)
+ print token
+ end
+
+ def on_comment(token, data)
+ puts
+ end
+end
+
+CommentStripper.strip(ARGF)
diff --git a/sample/rss/blend.rb b/sample/rss/blend.rb
index 2fbd6efed6..351f6f373f 100755
--- a/sample/rss/blend.rb
+++ b/sample/rss/blend.rb
@@ -64,6 +64,12 @@ rss = RSS::Maker.make("1.0") do |maker|
item.setup_maker(maker.items)
end
end
+
+ maker.items.each do |item|
+ item.title ||= "UNKNOWN"
+ item.link ||= "UNKNOWN"
+ end
+
maker.items.do_sort = true
maker.items.max_size = 15
end
diff --git a/sample/rss/convert.rb b/sample/rss/convert.rb
index 394b13e8eb..e6bff4c623 100755
--- a/sample/rss/convert.rb
+++ b/sample/rss/convert.rb
@@ -23,7 +23,7 @@ ARGV.each do |fname|
when '-v'
verbose = true
next
- when /^-t(0\.91|1\.0|2\.0)$/
+ when /^-t(0\.91|1\.0|2\.0|atom)$/
to_version = $1
next
end
diff --git a/sample/rss/list_description.rb b/sample/rss/list_description.rb
index bb1f9636e2..990974d8f5 100644..100755
--- a/sample/rss/list_description.rb
+++ b/sample/rss/list_description.rb
@@ -4,7 +4,7 @@ require "nkf"
class String
# From tdiary.rb
def shorten( len = 120 )
- lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
+ lines = NKF::nkf( "-t -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
lines[0].concat( '...' ) if lines[0] and lines[1]
lines[0]
end
@@ -52,13 +52,22 @@ ARGV.each do |fname|
puts "#{fname} does not include RSS 1.0 or 0.9x/2.0"
else
begin
- rss.output_encoding = "euc-jp"
+ rss.output_encoding = "utf-8"
rescue RSS::UnknownConversionMethodError
error($!) if verbose
end
- rss.channel.title ||= "Unknown"
+
+ rss = rss.to_rss("1.0") do |maker|
+ maker.channel.about ||= maker.channel.link
+ maker.channel.description ||= "No description"
+ maker.items.each do |item|
+ item.title ||= "No title"
+ item.link ||= "UNKNOWN"
+ end
+ end
+ next if rss.nil?
+
rss.items.each do |item|
- item.title ||= "Unknown"
channels[rss.channel.title] ||= []
channels[rss.channel.title] << item if item.description
end
diff --git a/sample/rss/re_read.rb b/sample/rss/re_read.rb
index c19a5099bb..ee54a18a88 100755
--- a/sample/rss/re_read.rb
+++ b/sample/rss/re_read.rb
@@ -29,16 +29,16 @@ ARGV.each do |fname|
read = false
begin
rss = RSS::Parser.parse(source)
- puts "Re-read valid RSS: #{fname}"
+ puts "Re-read valid feed: #{fname}"
RSS::Parser.parse(rss.to_s)
read = true
rescue RSS::InvalidRSSError
error($!) if verbose
- ## do non validate parse for invalid RSS 1.0
+ ## do non validate parse for invalid feed
begin
rss = RSS::Parser.parse(source, false)
rescue RSS::Error
- ## invalid RSS.
+ ## invalid feed
error($!) if verbose
end
rescue RSS::Error
@@ -46,9 +46,9 @@ ARGV.each do |fname|
end
if rss.nil?
- puts "Invalid RSS: #{fname}"
+ puts "Invalid feed: #{fname}"
elsif !read
- puts "Re-read invalid RSS: #{fname}"
+ puts "Re-read invalid feed: #{fname}"
begin
RSS::Parser.parse(rss.to_s)
rescue RSS::Error
diff --git a/sample/rss/rss_recent.rb b/sample/rss/rss_recent.rb
index 7821df5c7b..14c861284e 100644..100755
--- a/sample/rss/rss_recent.rb
+++ b/sample/rss/rss_recent.rb
@@ -4,7 +4,7 @@ require "nkf"
class String
# From tdiary.rb
def shorten( len = 120 )
- lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
+ lines = NKF::nkf( "-t -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
lines[0].concat( '...' ) if lines[0] and lines[1]
lines[0]
end
@@ -51,20 +51,24 @@ ARGV.each do |fname|
puts "#{fname} does not include RSS 1.0 or 0.9x/2.0"
else
begin
- rss.output_encoding = "euc-jp"
+ rss.output_encoding = "utf-8"
rescue RSS::UnknownConversionMethodError
error($!) if verbose
end
- rss.items.each do |item|
- if item.respond_to?(:pubDate) and item.pubDate
- class << item
- alias_method(:dc_date, :pubDate)
- end
- end
- if item.respond_to?(:dc_date) and item.dc_date
- items << [rss.channel, item]
+
+ rss = rss.to_rss("1.0") do |maker|
+ maker.channel.about ||= maker.channel.link
+ maker.channel.description ||= "No description"
+ maker.items.each do |item|
+ item.title ||= "UNKNOWN"
+ item.link ||= "UNKNOWN"
end
end
+ next if rss.nil?
+
+ rss.items.each do |item|
+ items << [rss.channel, item] if item.dc_date
+ end
end
end
processing_time = Time.now - before_time
diff --git a/sample/svr.rb b/sample/svr.rb
index 11cfc5fbfe..f4f29eb8e7 100644
--- a/sample/svr.rb
+++ b/sample/svr.rb
@@ -6,7 +6,7 @@
require "socket"
-gs = TCPserver.open(0)
+gs = TCPServer.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))
diff --git a/sample/test.rb b/sample/test.rb
index e7f2d251b7..fc7a7f5db7 100644
--- a/sample/test.rb
+++ b/sample/test.rb
@@ -1,12 +1,12 @@
#! /usr/bin/env ruby
+# -*- coding: us-ascii -*-
-$KCODE = "none"
$testnum=0
$ntest=0
$failed = 0
def test_check(what)
- printf "%s\n", what
+ STDERR.print "\nsample/test.rb:#{what} "
$what = what
$testnum = 0
end
@@ -14,13 +14,17 @@ end
def test_ok(cond,n=1)
$testnum+=1
$ntest+=1
+ where = (st = caller(n)) ? st[0] : "caller error! (n=#{n}, trace=#{caller(0).join(', ')}"
if cond
- printf "ok %d\n", $testnum
+ STDERR.print "."
+ printf "ok %d (%s)\n", $testnum, where
else
- where = caller(n)[0]
+ STDERR.print "F"
printf "not ok %s %d -- %s\n", $what, $testnum, where
$failed+=1
end
+ STDOUT.flush
+ STDERR.flush
end
# make sure conditional operators work
@@ -54,30 +58,48 @@ a = [*[]]; test_ok(a == [])
a = [*[1]]; test_ok(a == [1])
a = [*[1,2]]; test_ok(a == [1,2])
-a = *nil; test_ok(a == nil)
-a = *1; test_ok(a == 1)
-a = *[]; test_ok(a == nil)
-a = *[1]; test_ok(a == 1)
-a = *[nil]; test_ok(a == nil)
-a = *[[]]; test_ok(a == [])
+a = *[]; test_ok(a == [])
+a = *[1]; test_ok(a == [1])
+a = *[nil]; test_ok(a == [nil])
+a = *[[]]; test_ok(a == [[]])
a = *[1,2]; test_ok(a == [1,2])
-a = *[*[]]; test_ok(a == nil)
-a = *[*[1]]; test_ok(a == 1)
+a = *[*[]]; test_ok(a == [])
+a = *[*[1]]; test_ok(a == [1])
a = *[*[1,2]]; test_ok(a == [1,2])
+a, = nil; test_ok(a == nil)
+a, = 1; test_ok(a == 1)
+a, = []; test_ok(a == nil)
+a, = [1]; test_ok(a == 1)
+a, = [nil]; test_ok(a == nil)
+a, = [[]]; test_ok(a == [])
+a, = 1,2; test_ok(a == 1)
+a, = [1,2]; test_ok(a == 1)
+a, = [*[]]; test_ok(a == nil)
+a, = [*[1]]; test_ok(a == 1)
+a, = *[1,2]; test_ok(a == 1)
+a, = [*[1,2]]; test_ok(a == 1)
+
+a, = *[]; test_ok(a == nil)
+a, = *[1]; test_ok(a == 1)
+a, = *[nil]; test_ok(a == nil)
+a, = *[[]]; test_ok(a == [])
+a, = *[1,2]; test_ok(a == 1)
+a, = *[*[]]; test_ok(a == nil)
+a, = *[*[1]]; test_ok(a == 1)
+a, = *[*[1,2]]; test_ok(a == 1)
+
*a = nil; test_ok(a == [nil])
*a = 1; test_ok(a == [1])
-*a = []; test_ok(a == [[]])
-*a = [1]; test_ok(a == [[1]])
-*a = [nil]; test_ok(a == [[nil]])
-*a = [[]]; test_ok(a == [[[]]])
-*a = [1,2]; test_ok(a == [[1,2]])
-*a = [*[]]; test_ok(a == [[]])
-*a = [*[1]]; test_ok(a == [[1]])
-*a = [*[1,2]]; test_ok(a == [[1,2]])
-
-*a = *nil; test_ok(a == [nil])
-*a = *1; test_ok(a == [1])
+*a = []; test_ok(a == [])
+*a = [1]; test_ok(a == [1])
+*a = [nil]; test_ok(a == [nil])
+*a = [[]]; test_ok(a == [[]])
+*a = [1,2]; test_ok(a == [1,2])
+*a = [*[]]; test_ok(a == [])
+*a = [*[1]]; test_ok(a == [1])
+*a = [*[1,2]]; test_ok(a == [1,2])
+
*a = *[]; test_ok(a == [])
*a = *[1]; test_ok(a == [1])
*a = *[nil]; test_ok(a == [nil])
@@ -98,8 +120,6 @@ a,b,*c = [*[]]; test_ok([a,b,c] == [nil,nil,[]])
a,b,*c = [*[1]]; test_ok([a,b,c] == [1,nil,[]])
a,b,*c = [*[1,2]]; test_ok([a,b,c] == [1,2,[]])
-a,b,*c = *nil; test_ok([a,b,c] == [nil,nil,[]])
-a,b,*c = *1; test_ok([a,b,c] == [1,nil,[]])
a,b,*c = *[]; test_ok([a,b,c] == [nil,nil,[]])
a,b,*c = *[1]; test_ok([a,b,c] == [1,nil,[]])
a,b,*c = *[nil]; test_ok([a,b,c] == [nil,nil,[]])
@@ -118,13 +138,32 @@ def f; yield [[]]; end; f {|a| test_ok(a == [[]])}
def f; yield [*[]]; end; f {|a| test_ok(a == [])}
def f; yield [*[1]]; end; f {|a| test_ok(a == [1])}
def f; yield [*[1,2]]; end; f {|a| test_ok(a == [1,2])}
-
-def f; yield *nil; end; f {|a| test_ok(a == nil)}
-def f; yield *1; end; f {|a| test_ok(a == 1)}
+def f; yield *[]; end; f {|a| test_ok(a == nil)}
def f; yield *[1]; end; f {|a| test_ok(a == 1)}
def f; yield *[nil]; end; f {|a| test_ok(a == nil)}
def f; yield *[[]]; end; f {|a| test_ok(a == [])}
+def f; yield *[*[]]; end; f {|a| test_ok(a == nil)}
def f; yield *[*[1]]; end; f {|a| test_ok(a == 1)}
+def f; yield *[*[1,2]]; end; f {|a| test_ok(a == 1)}
+
+def f; yield; end; f {|a,| test_ok(a == nil)}
+def f; yield nil; end; f {|a,| test_ok(a == nil)}
+def f; yield 1; end; f {|a,| test_ok(a == 1)}
+def f; yield []; end; f {|a,| test_ok(a == nil)}
+def f; yield [1]; end; f {|a,| test_ok(a == 1)}
+def f; yield [nil]; end; f {|a,| test_ok(a == nil)}
+def f; yield [[]]; end; f {|a,| test_ok(a == [])}
+def f; yield [*[]]; end; f {|a,| test_ok(a == nil)}
+def f; yield [*[1]]; end; f {|a,| test_ok(a == 1)}
+def f; yield [*[1,2]]; end; f {|a,| test_ok(a == 1)}
+
+def f; yield *[]; end; f {|a,| test_ok(a == nil)}
+def f; yield *[1]; end; f {|a,| test_ok(a == 1)}
+def f; yield *[nil]; end; f {|a,| test_ok(a == nil)}
+def f; yield *[[]]; end; f {|a,| test_ok(a == nil)}
+def f; yield *[*[]]; end; f {|a,| test_ok(a == nil)}
+def f; yield *[*[1]]; end; f {|a,| test_ok(a == 1)}
+def f; yield *[*[1,2]]; end; f {|a,| test_ok(a == 1)}
def f; yield; end; f {|*a| test_ok(a == [])}
def f; yield nil; end; f {|*a| test_ok(a == [nil])}
@@ -138,8 +177,6 @@ def f; yield [*[]]; end; f {|*a| test_ok(a == [[]])}
def f; yield [*[1]]; end; f {|*a| test_ok(a == [[1]])}
def f; yield [*[1,2]]; end; f {|*a| test_ok(a == [[1,2]])}
-def f; yield *nil; end; f {|*a| test_ok(a == [nil])}
-def f; yield *1; end; f {|*a| test_ok(a == [1])}
def f; yield *[]; end; f {|*a| test_ok(a == [])}
def f; yield *[1]; end; f {|*a| test_ok(a == [1])}
def f; yield *[nil]; end; f {|*a| test_ok(a == [nil])}
@@ -159,12 +196,10 @@ def f; yield [*[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])}
def f; yield [*[1]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])}
def f; yield [*[1,2]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,2,[]])}
-def f; yield *nil; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])}
-def f; yield *1; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])}
def f; yield *[]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])}
def f; yield *[1]; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])}
def f; yield *[nil]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])}
-def f; yield *[[]]; end; f {|a,b,*c| test_ok([a,b,c] == [[],nil,[]])}
+def f; yield *[[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])}
def f; yield *[*[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])}
def f; yield *[*[1]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])}
def f; yield *[*[1,2]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,2,[]])}
@@ -180,58 +215,40 @@ def r; return [*[]]; end; a = r(); test_ok(a == [])
def r; return [*[1]]; end; a = r(); test_ok(a == [1])
def r; return [*[1,2]]; end; a = r(); test_ok(a == [1,2])
-def r; return *nil; end; a = r(); test_ok(a == nil)
-def r; return *1; end; a = r(); test_ok(a == 1)
-def r; return *[]; end; a = r(); test_ok(a == nil)
-def r; return *[1]; end; a = r(); test_ok(a == 1)
-def r; return *[nil]; end; a = r(); test_ok(a == nil)
-def r; return *[[]]; end; a = r(); test_ok(a == [])
-def r; return *[*[]]; end; a = r(); test_ok(a == nil)
-def r; return *[*[1]]; end; a = r(); test_ok(a == 1)
+def r; return *[]; end; a = r(); test_ok(a == [])
+def r; return *[1]; end; a = r(); test_ok(a == [1])
+def r; return *[nil]; end; a = r(); test_ok(a == [nil])
+def r; return *[[]]; end; a = r(); test_ok(a == [[]])
+def r; return *[*[]]; end; a = r(); test_ok(a == [])
+def r; return *[*[1]]; end; a = r(); test_ok(a == [1])
def r; return *[*[1,2]]; end; a = r(); test_ok(a == [1,2])
-def r; return *nil; end; a = *r(); test_ok(a == nil)
-def r; return *1; end; a = *r(); test_ok(a == 1)
-def r; return *[]; end; a = *r(); test_ok(a == nil)
-def r; return *[1]; end; a = *r(); test_ok(a == 1)
-def r; return *[nil]; end; a = *r(); test_ok(a == nil)
-def r; return *[[]]; end; a = *r(); test_ok(a == nil)
-def r; return *[*[]]; end; a = *r(); test_ok(a == nil)
-def r; return *[*[1]]; end; a = *r(); test_ok(a == 1)
+def r; return *[[]]; end; a = *r(); test_ok(a == [[]])
def r; return *[*[1,2]]; end; a = *r(); test_ok(a == [1,2])
def r; return; end; *a = r(); test_ok(a == [nil])
def r; return nil; end; *a = r(); test_ok(a == [nil])
def r; return 1; end; *a = r(); test_ok(a == [1])
-def r; return []; end; *a = r(); test_ok(a == [[]])
-def r; return [1]; end; *a = r(); test_ok(a == [[1]])
-def r; return [nil]; end; *a = r(); test_ok(a == [[nil]])
-def r; return [[]]; end; *a = r(); test_ok(a == [[[]]])
-def r; return [1,2]; end; *a = r(); test_ok(a == [[1,2]])
-def r; return [*[]]; end; *a = r(); test_ok(a == [[]])
-def r; return [*[1]]; end; *a = r(); test_ok(a == [[1]])
-def r; return [*[1,2]]; end; *a = r(); test_ok(a == [[1,2]])
-
-def r; return *nil; end; *a = r(); test_ok(a == [nil])
-def r; return *1; end; *a = r(); test_ok(a == [1])
-def r; return *[]; end; *a = r(); test_ok(a == [nil])
+def r; return []; end; *a = r(); test_ok(a == [])
+def r; return [1]; end; *a = r(); test_ok(a == [1])
+def r; return [nil]; end; *a = r(); test_ok(a == [nil])
+def r; return [[]]; end; *a = r(); test_ok(a == [[]])
+def r; return [1,2]; end; *a = r(); test_ok(a == [1,2])
+def r; return [*[]]; end; *a = r(); test_ok(a == [])
+def r; return [*[1]]; end; *a = r(); test_ok(a == [1])
+def r; return [*[1,2]]; end; *a = r(); test_ok(a == [1,2])
+
+def r; return *[]; end; *a = r(); test_ok(a == [])
def r; return *[1]; end; *a = r(); test_ok(a == [1])
def r; return *[nil]; end; *a = r(); test_ok(a == [nil])
def r; return *[[]]; end; *a = r(); test_ok(a == [[]])
-def r; return *[1,2]; end; *a = r(); test_ok(a == [[1,2]])
-def r; return *[*[]]; end; *a = r(); test_ok(a == [nil])
+def r; return *[1,2]; end; *a = r(); test_ok(a == [1,2])
+def r; return *[*[]]; end; *a = r(); test_ok(a == [])
def r; return *[*[1]]; end; *a = r(); test_ok(a == [1])
-def r; return *[*[1,2]]; end; *a = r(); test_ok(a == [[1,2]])
-
-def r; return *nil; end; *a = *r(); test_ok(a == [nil])
-def r; return *1; end; *a = *r(); test_ok(a == [1])
-def r; return *[]; end; *a = *r(); test_ok(a == [nil])
-def r; return *[1]; end; *a = *r(); test_ok(a == [1])
-def r; return *[nil]; end; *a = *r(); test_ok(a == [nil])
-def r; return *[[]]; end; *a = *r(); test_ok(a == [])
+def r; return *[*[1,2]]; end; *a = r(); test_ok(a == [1,2])
+
+def r; return *[[]]; end; *a = *r(); test_ok(a == [[]])
def r; return *[1,2]; end; *a = *r(); test_ok(a == [1,2])
-def r; return *[*[]]; end; *a = *r(); test_ok(a == [nil])
-def r; return *[*[1]]; end; *a = *r(); test_ok(a == [1])
def r; return *[*[1,2]]; end; *a = *r(); test_ok(a == [1,2])
def r; return; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]])
@@ -246,12 +263,10 @@ def r; return [*[]]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]])
def r; return [*[1]]; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]])
def r; return [*[1,2]]; end; a,b,*c = r(); test_ok([a,b,c] == [1,2,[]])
-def r; return *nil; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]])
-def r; return *1; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]])
def r; return *[]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]])
def r; return *[1]; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]])
def r; return *[nil]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]])
-def r; return *[[]]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]])
+def r; return *[[]]; end; a,b,*c = r(); test_ok([a,b,c] == [[],nil,[]])
def r; return *[1,2]; end; a,b,*c = r(); test_ok([a,b,c] == [1,2,[]])
def r; return *[*[]]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]])
def r; return *[*[1]]; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]])
@@ -282,6 +297,64 @@ test_ok(f.call([[42]]) == [[[42]]])
test_ok(f.call([42,55]) == [[42,55]])
test_ok(f.call(42,55) == [42,55])
+f = lambda { |a, b=42, *c| [a,b,c] }
+test_ok(f.call(1 ) == [1,42,[ ]] )
+test_ok(f.call(1,43 ) == [1,43,[ ]] )
+test_ok(f.call(1,43,44) == [1,43,[44]] )
+
+f = lambda { |a, b=(a|16), *c, &block| [a,b,c,block&&block[]] }
+test_ok(f.call(8 ) == [8,24,[ ],nil] )
+test_ok(f.call(8,43 ) == [8,43,[ ],nil] )
+test_ok(f.call(8,43,44) == [8,43,[44],nil] )
+test_ok(f.call(8 ){45} == [8,24,[ ],45 ] )
+test_ok(f.call(8,43 ){45} == [8,43,[ ],45 ] )
+test_ok(f.call(8,43,44){45} == [8,43,[44],45 ] )
+
+f = lambda { |a, b=42, *c, d| [a,b,c,d] }
+test_ok(f.call(1 ,99) == [1,42,[ ],99] )
+test_ok(f.call(1,43 ,99) == [1,43,[ ],99] )
+test_ok(f.call(1,43,44,99) == [1,43,[44],99] )
+
+f = lambda { |a, b=(a|16), &block| [a,b,block&&block[]] }
+test_ok(f.call(8 ) == [8,24,nil] )
+test_ok(f.call(8,43) == [8,43,nil] )
+test_ok(f.call(8,43) == [8,43,nil] )
+test_ok(f.call(8 ){45} == [8,24,45 ] )
+test_ok(f.call(8,43){45} == [8,43,45 ] )
+test_ok(f.call(8,43){45} == [8,43,45 ] )
+
+f = lambda { |a, b=42, d| [a,b,d] }
+test_ok(f.call(1 ,99) == [1,42,99] )
+test_ok(f.call(1,43,99) == [1,43,99] )
+test_ok(f.call(1,43,99) == [1,43,99] )
+
+f = lambda { |b=42, *c, &block| [b,c,block&&block[]] }
+test_ok(f.call( ) == [42,[ ],nil] )
+test_ok(f.call(43 ) == [43,[ ],nil] )
+test_ok(f.call(43,44) == [43,[44],nil] )
+test_ok(f.call( ){45} == [42,[ ],45 ] )
+test_ok(f.call(43 ){45} == [43,[ ],45 ] )
+test_ok(f.call(43,44){45} == [43,[44],45 ] )
+
+f = lambda { |b=42, *c, d| [b,c,d] }
+test_ok(f.call( 99) == [42,[ ],99] )
+test_ok(f.call(43 ,99) == [43,[ ],99] )
+test_ok(f.call(43,44,99) == [43,[44],99] )
+
+f = lambda { |b=42, &block| [b,block&&block[]] }
+test_ok(f.call( ) == [42,nil] )
+test_ok(f.call(43) == [43,nil] )
+test_ok(f.call(43) == [43,nil] )
+test_ok(f.call( ){45} == [42,45 ] )
+test_ok(f.call(43){45} == [43,45 ] )
+test_ok(f.call(43){45} == [43,45 ] )
+
+f = lambda { |b=42, d| [b,d] }
+test_ok(f.call( 99) == [42,99] )
+test_ok(f.call(43,99) == [43,99] )
+test_ok(f.call(43,99) == [43,99] )
+
+
a,=*[1]
test_ok(a == 1)
a,=*[[1]]
@@ -307,48 +380,37 @@ a = loop do break [*[]]; end; test_ok(a == [])
a = loop do break [*[1]]; end; test_ok(a == [1])
a = loop do break [*[1,2]]; end; test_ok(a == [1,2])
-a = loop do break *nil; end; test_ok(a == nil)
-a = loop do break *1; end; test_ok(a == 1)
-a = loop do break *[]; end; test_ok(a == nil)
-a = loop do break *[1]; end; test_ok(a == 1)
-a = loop do break *[nil]; end; test_ok(a == nil)
-a = loop do break *[[]]; end; test_ok(a == [])
-a = loop do break *[*[]]; end; test_ok(a == nil)
-a = loop do break *[*[1]]; end; test_ok(a == 1)
+a = loop do break *[]; end; test_ok(a == [])
+a = loop do break *[1]; end; test_ok(a == [1])
+a = loop do break *[nil]; end; test_ok(a == [nil])
+a = loop do break *[[]]; end; test_ok(a == [[]])
+a = loop do break *[*[]]; end; test_ok(a == [])
+a = loop do break *[*[1]]; end; test_ok(a == [1])
a = loop do break *[*[1,2]]; end; test_ok(a == [1,2])
*a = loop do break; end; test_ok(a == [nil])
*a = loop do break nil; end; test_ok(a == [nil])
*a = loop do break 1; end; test_ok(a == [1])
-*a = loop do break []; end; test_ok(a == [[]])
-*a = loop do break [1]; end; test_ok(a == [[1]])
-*a = loop do break [nil]; end; test_ok(a == [[nil]])
-*a = loop do break [[]]; end; test_ok(a == [[[]]])
-*a = loop do break [1,2]; end; test_ok(a == [[1,2]])
-*a = loop do break [*[]]; end; test_ok(a == [[]])
-*a = loop do break [*[1]]; end; test_ok(a == [[1]])
-*a = loop do break [*[1,2]]; end; test_ok(a == [[1,2]])
-
-*a = loop do break *nil; end; test_ok(a == [nil])
-*a = loop do break *1; end; test_ok(a == [1])
-*a = loop do break *[]; end; test_ok(a == [nil])
+*a = loop do break []; end; test_ok(a == [])
+*a = loop do break [1]; end; test_ok(a == [1])
+*a = loop do break [nil]; end; test_ok(a == [nil])
+*a = loop do break [[]]; end; test_ok(a == [[]])
+*a = loop do break [1,2]; end; test_ok(a == [1,2])
+*a = loop do break [*[]]; end; test_ok(a == [])
+*a = loop do break [*[1]]; end; test_ok(a == [1])
+*a = loop do break [*[1,2]]; end; test_ok(a == [1,2])
+
+*a = loop do break *[]; end; test_ok(a == [])
*a = loop do break *[1]; end; test_ok(a == [1])
*a = loop do break *[nil]; end; test_ok(a == [nil])
*a = loop do break *[[]]; end; test_ok(a == [[]])
-*a = loop do break *[1,2]; end; test_ok(a == [[1,2]])
-*a = loop do break *[*[]]; end; test_ok(a == [nil])
+*a = loop do break *[1,2]; end; test_ok(a == [1,2])
+*a = loop do break *[*[]]; end; test_ok(a == [])
*a = loop do break *[*[1]]; end; test_ok(a == [1])
-*a = loop do break *[*[1,2]]; end; test_ok(a == [[1,2]])
-
-*a = *loop do break *nil; end; test_ok(a == [nil])
-*a = *loop do break *1; end; test_ok(a == [1])
-*a = *loop do break *[]; end; test_ok(a == [nil])
-*a = *loop do break *[1]; end; test_ok(a == [1])
-*a = *loop do break *[nil]; end; test_ok(a == [nil])
-*a = *loop do break *[[]]; end; test_ok(a == [])
+*a = loop do break *[*[1,2]]; end; test_ok(a == [1,2])
+
+*a = *loop do break *[[]]; end; test_ok(a == [[]])
*a = *loop do break *[1,2]; end; test_ok(a == [1,2])
-*a = *loop do break *[*[]]; end; test_ok(a == [nil])
-*a = *loop do break *[*[1]]; end; test_ok(a == [1])
*a = *loop do break *[*[1,2]]; end; test_ok(a == [1,2])
a,b,*c = loop do break; end; test_ok([a,b,c] == [nil,nil,[]])
@@ -363,12 +425,10 @@ a,b,*c = loop do break [*[]]; end; test_ok([a,b,c] == [nil,nil,[]])
a,b,*c = loop do break [*[1]]; end; test_ok([a,b,c] == [1,nil,[]])
a,b,*c = loop do break [*[1,2]]; end; test_ok([a,b,c] == [1,2,[]])
-a,b,*c = loop do break *nil; end; test_ok([a,b,c] == [nil,nil,[]])
-a,b,*c = loop do break *1; end; test_ok([a,b,c] == [1,nil,[]])
a,b,*c = loop do break *[]; end; test_ok([a,b,c] == [nil,nil,[]])
a,b,*c = loop do break *[1]; end; test_ok([a,b,c] == [1,nil,[]])
a,b,*c = loop do break *[nil]; end; test_ok([a,b,c] == [nil,nil,[]])
-a,b,*c = loop do break *[[]]; end; test_ok([a,b,c] == [nil,nil,[]])
+a,b,*c = loop do break *[[]]; end; test_ok([a,b,c] == [[],nil,[]])
a,b,*c = loop do break *[1,2]; end; test_ok([a,b,c] == [1,2,[]])
a,b,*c = loop do break *[*[]]; end; test_ok([a,b,c] == [nil,nil,[]])
a,b,*c = loop do break *[*[1]]; end; test_ok([a,b,c] == [1,nil,[]])
@@ -386,39 +446,30 @@ r([]){next [*[]]}
r([1]){next [*[1]]}
r([1,2]){next [*[1,2]]}
-r(nil){next *nil}
-r(1){next *1}
-r(nil){next *[]}
-r(1){next *[1]}
-r(nil){next *[nil]}
-r([]){next *[[]]}
-r(nil){next *[*[]]}
-r(1){next *[*[1]]}
+r([]){next *[]}
+r([1]){next *[1]}
+r([nil]){next *[nil]}
+r([[]]){next *[[]]}
+r([]){next *[*[]]}
+r([1]){next *[*[1]]}
r([1,2]){next *[*[1,2]]}
def r(val); *a = yield(); test_ok(a == val, 2); end
r([nil]){next}
r([nil]){next nil}
r([1]){next 1}
-r([[]]){next []}
-r([[1]]){next [1]}
-r([[nil]]){next [nil]}
-r([[[]]]){next [[]]}
-r([[1,2]]){next [1,2]}
-r([[]]){next [*[]]}
-r([[1]]){next [*[1]]}
-r([[1,2]]){next [*[1,2]]}
+r([]){next []}
+r([1]){next [1]}
+r([nil]){next [nil]}
+r([[]]){next [[]]}
+r([1,2]){next [1,2]}
+r([]){next [*[]]}
+r([1]){next [*[1]]}
+r([1,2]){next [*[1,2]]}
def r(val); *a = *yield(); test_ok(a == val, 2); end
-r([nil]){next *nil}
-r([1]){next *1}
-r([nil]){next *[]}
-r([1]){next *[1]}
-r([nil]){next *[nil]}
-r([]){next *[[]]}
+r([[]]){next *[[]]}
r([1,2]){next *[1,2]}
-r([nil]){next *[*[]]}
-r([1]){next *[*[1]]}
r([1,2]){next *[*[1,2]]}
def r(val); a,b,*c = yield(); test_ok([a,b,c] == val, 2); end
@@ -435,15 +486,8 @@ r([1,nil,[]]){next [*[1]]}
r([1,2,[]]){next [*[1,2]]}
def r(val); a,b,*c = *yield(); test_ok([a,b,c] == val, 2); end
-r([nil,nil,[]]){next *nil}
-r([1,nil,[]]){next *1}
-r([nil,nil,[]]){next *[]}
-r([1,nil,[]]){next *[1]}
-r([nil,nil,[]]){next *[nil]}
-r([nil,nil,[]]){next *[[]]}
+r([[],nil,[]]){next *[[]]}
r([1,2,[]]){next *[1,2]}
-r([nil,nil,[]]){next *[*[]]}
-r([1,nil,[]]){next *[*[1]]}
r([1,2,[]]){next *[*[1,2]]}
test_check "condition"
@@ -540,15 +584,15 @@ tmp.close
# test redo
$bad = false
tmp = open("while_tmp", "r")
-while tmp.gets()
- line = $_
- gsub(/vt100/, 'VT100')
- if $_ != line
- $_.gsub!('VT100', 'Vt100')
+while line = tmp.gets()
+ lastline = line
+ line = line.gsub(/vt100/, 'VT100')
+ if lastline != line
+ line.gsub!('VT100', 'Vt100')
redo
end
- $bad = 1 if /vt100/ =~ $_
- $bad = 1 if /VT100/ =~ $_
+ $bad = 1 if /vt100/ =~ line
+ $bad = 1 if /VT100/ =~ line
end
test_ok(tmp.eof? && !$bad)
tmp.close
@@ -617,10 +661,12 @@ begin
raise $string
end
test_ok(false)
-rescue
- test_ok(true) if $! == $string
+rescue => e
+ test_ok($! == e)
+ test_ok(e.message == $string)
+ test_ok(e != $string)
end
-
+
# exception in ensure clause
begin
begin
@@ -768,12 +814,11 @@ test_ok($x == [1,2,3,1,2,3])
test_check "hash"
$x = {1=>2, 2=>4, 3=>6}
-$y = {1, 2, 2, 4, 3, 6}
test_ok($x[1] == 2)
test_ok(begin
- for k,v in $y
+ for k,v in $x
raise if k*2 != v
end
true
@@ -787,19 +832,19 @@ test_ok($x.has_value?(4))
test_ok($x.values_at(2,3) == [4,6])
test_ok($x == {1=>2, 2=>4, 3=>6})
-$z = $y.keys.sort.join(":")
+$z = $x.keys.sort.join(":")
test_ok($z == "1:2:3")
-$z = $y.values.sort.join(":")
+$z = $x.values.sort.join(":")
test_ok($z == "2:4:6")
-test_ok($x == $y)
+test_ok($x == $x)
-$y.shift
-test_ok($y.length == 2)
+$x.shift
+test_ok($x.length == 2)
$z = [1,2]
-$y[$z] = 256
-test_ok($y[$z] == 256)
+$x[$z] = 256
+test_ok($x[$z] == 256)
$x = Hash.new(0)
$x[1] = 1
@@ -864,8 +909,9 @@ def tt
}
end
+i=0
tt{|i| break if i == 5}
-test_ok(i == 5)
+test_ok(i == 0)
def tt2(dummy)
yield 1
@@ -931,18 +977,6 @@ end
test_ok($x.size == 7)
test_ok($x == [1, 2, 3, 4, 5, 6, 7])
-$done = false
-$x = []
-for i in 1 .. 7 # see how retry works in iterator loop
- if i == 4 and not $done
- $done = true
- retry
- end
- $x.push(i)
-end
-test_ok($x.size == 10)
-test_ok($x == [1, 2, 3, 1, 2, 3, 4, 5, 6, 7])
-
# append method to built-in class
class Array
def iter_test1
@@ -980,11 +1014,11 @@ test_ok(IterTest.new(nil).method(:f).to_proc.call([m]) == [m])
IterTest.new([0]).each0 {|x| test_ok(x == 0)}
IterTest.new([1]).each1 {|x| test_ok(x == 1)}
IterTest.new([2]).each2 {|x| test_ok(x == [2])}
-IterTest.new([3]).each3 {|x| test_ok(x == 3)}
+#IterTest.new([3]).each3 {|x| test_ok(x == 3)}
IterTest.new([4]).each4 {|x| test_ok(x == 4)}
IterTest.new([5]).each5 {|x| test_ok(x == 5)}
IterTest.new([6]).each6 {|x| test_ok(x == [6])}
-IterTest.new([7]).each7 {|x| test_ok(x == 7)}
+#IterTest.new([7]).each7 {|x| test_ok(x == 7)}
IterTest.new([8]).each8 {|x| test_ok(x == 8)}
IterTest.new([[0]]).each0 {|x| test_ok(x == [0])}
@@ -997,18 +1031,24 @@ IterTest.new([[6]]).each6 {|x| test_ok(x == [[6]])}
IterTest.new([[7]]).each7 {|x| test_ok(x == 7)}
IterTest.new([[8]]).each8 {|x| test_ok(x == [8])}
-IterTest.new([[0,0]]).each0 {|x| test_ok(x == [0,0])}
-IterTest.new([[8,8]]).each8 {|x| test_ok(x == [8,8])}
+IterTest.new([[0,0]]).each0 {|*x| test_ok(x == [[0,0]])}
+IterTest.new([[8,8]]).each8 {|*x| test_ok(x == [[8,8]])}
-def m
- test_ok(block_given?)
+def m0(v)
+ v
end
-m{p 'test'}
+
+def m1
+ m0(block_given?)
+end
+test_ok(m1{p 'test'})
+test_ok(!m1)
def m
- test_ok(block_given?,&proc{})
+ m0(block_given?,&Proc.new{})
end
-m{p 'test'}
+test_ok(m1{p 'test'})
+test_ok(!m1)
class C
include Enumerable
@@ -1032,7 +1072,7 @@ end
block_test(NilClass)
block_test(Proc){}
-def argument_test(state, proc, *args)
+def call_argument_test(state, proc, *args)
x = state
begin
proc.call(*args)
@@ -1042,47 +1082,56 @@ def argument_test(state, proc, *args)
test_ok(x,2)
end
-argument_test(true, lambda{||})
-argument_test(false, lambda{||}, 1)
-argument_test(true, lambda{|a,|}, 1)
-argument_test(false, lambda{|a,|})
-argument_test(false, lambda{|a,|}, 1,2)
+call_argument_test(true, lambda{||})
+call_argument_test(false, lambda{||}, 1)
+call_argument_test(true, lambda{|a,|}, 1)
+call_argument_test(false, lambda{|a,|})
+call_argument_test(false, lambda{|a,|}, 1,2)
+
+call_argument_test(true, Proc.new{||})
+call_argument_test(true, Proc.new{||}, 1)
+call_argument_test(true, Proc.new{|a,|}, 1)
+call_argument_test(true, Proc.new{|a,|})
+call_argument_test(true, Proc.new{|a,|}, 1,2)
-def get_block(&block)
+def block_get(&block)
block
end
-test_ok(Proc == get_block{}.class)
-argument_test(true, get_block{||})
-argument_test(true, get_block{||}, 1)
-argument_test(true, get_block{|a,|}, 1)
-argument_test(true, get_block{|a,|})
-argument_test(true, get_block{|a,|}, 1,2)
+test_ok(Proc == block_get{}.class)
+call_argument_test(true, block_get{||})
+call_argument_test(true, block_get{||}, 1)
+call_argument_test(true, block_get{|a,|}, 1)
+call_argument_test(true, block_get{|a,|})
+call_argument_test(true, block_get{|a,|}, 1,2)
-argument_test(true, get_block(&lambda{||}))
-argument_test(false, get_block(&lambda{||}),1)
-argument_test(true, get_block(&lambda{|a,|}),1)
-argument_test(false, get_block(&lambda{|a,|}),1,2)
+call_argument_test(true, block_get(&lambda{||}))
+call_argument_test(false, block_get(&lambda{||}),1)
+call_argument_test(true, block_get(&lambda{|a,|}),1)
+call_argument_test(false, block_get(&lambda{|a,|}),1,2)
-block = get_block{11}
-test_ok(block.class == Proc)
-test_ok(block.to_proc.class == Proc)
-test_ok(block.clone.call == 11)
-test_ok(get_block(&block).class == Proc)
+blk = block_get{11}
+test_ok(blk.class == Proc)
+test_ok(blk.to_proc.class == Proc)
+test_ok(blk.clone.call == 11)
+test_ok(block_get(&blk).class == Proc)
-lambda = lambda{44}
-test_ok(lambda.class == Proc)
-test_ok(lambda.to_proc.class == Proc)
-test_ok(lambda.clone.call == 44)
-test_ok(get_block(&lambda).class == Proc)
+lmd = lambda{44}
+test_ok(lmd.class == Proc)
+test_ok(lmd.to_proc.class == Proc)
+test_ok(lmd.clone.call == 44)
+test_ok(block_get(&lmd).class == Proc)
-test_ok(Proc.new{|a,| a}.call(1,2,3) == 1)
-argument_test(true, Proc.new{|a,|}, 1,2)
+test_ok(Proc.new{|a,| a}.yield(1,2,3) == 1)
+call_argument_test(true, Proc.new{|a,|}, 1,2)
+
+test_ok(Proc.new{|&b| b.call(10)}.call {|x| x} == 10)
+test_ok(Proc.new{|a,&b| b.call(a)}.call(12) {|x| x} == 12)
def test_return1
Proc.new {
return 55
- }.call + 5
+ }.yield + 5
end
test_ok(test_return1() == 55)
def test_return2
@@ -1099,15 +1148,23 @@ def proc_yield()
yield
end
def proc_return1
- proc_call{return 42}+1
+ lambda{return 42}.call+1
end
-test_ok(proc_return1() == 42)
+test_ok(proc_return1() == 43)
def proc_return2
+ ->{return 42}.call+1
+end
+test_ok(proc_return2() == 43)
+def proc_return3
+ proc_call{return 42}+1
+end
+test_ok(proc_return3() == 42)
+def proc_return4
proc_yield{return 42}+1
end
-test_ok(proc_return2() == 42)
+test_ok(proc_return4() == 42)
-def ljump_test(state, proc, *args)
+def ljump_test(state, proc, *args)
x = state
begin
proc.call(*args)
@@ -1117,26 +1174,165 @@ def ljump_test(state, proc, *args)
test_ok(x,2)
end
-ljump_test(false, get_block{break})
+ljump_test(false, block_get{break})
ljump_test(true, lambda{break})
-test_ok(block.arity == -1)
-test_ok(lambda.arity == -1)
-test_ok(lambda{||}.arity == 0)
-test_ok(lambda{|a|}.arity == 1)
-test_ok(lambda{|a,|}.arity == 1)
-test_ok(lambda{|a,b|}.arity == 2)
+def exit_value_test(&block)
+ block.call
+rescue LocalJumpError
+ $!.exit_value
+end
+
+test_ok(45 == exit_value_test{break 45})
+
+test_ok(55 == begin
+ block_get{break 55}.call
+ rescue LocalJumpError
+ $!.exit_value
+ end)
+
+def block_call(&block)
+ block.call
+end
+
+def test_b1
+ block_call{break 11}
+end
+test_ok(test_b1() == 11)
+
+def ljump_rescue(r)
+ begin
+ yield
+ rescue LocalJumpError => e
+ r if /from proc-closure/ =~ e.message
+ end
+end
+
+def test_b2
+ ljump_rescue(22) do
+ block_get{break 21}.call
+ end
+end
+test_ok(test_b2() == 22)
+
+def test_b3
+ ljump_rescue(33) do
+ Proc.new{break 31}.yield
+ end
+end
+test_ok(test_b3() == 33)
+
+def test_b4
+ lambda{break 44}.call
+end
+test_ok(test_b4() == 44)
+
+def test_b5
+ ljump_rescue(55) do
+ b = block_get{break 54}
+ block_call(&b)
+ end
+end
+test_ok(test_b5() == 55)
+
+def test_b6
+ b = lambda{break 67}
+ block_call(&b)
+ 66
+end
+test_ok(test_b6() == 66)
+
+def util_r7
+ block_get{break 78}
+end
+
+def test_b7
+ b = util_r7()
+ ljump_rescue(77) do
+ block_call(&b)
+ end
+end
+test_ok(test_b7() == 77)
+
+def util_b8(&block)
+ block_call(&block)
+end
+
+def test_b8
+ util_b8{break 88}
+end
+test_ok(test_b8() == 88)
+
+def util_b9(&block)
+ lambda{block.call; 98}.call
+end
+
+def test_b9
+ util_b9{break 99}
+end
+test_ok(test_b9() == 99)
+
+def util_b10
+ util_b9{break 100}
+end
+
+def test_b10
+ util_b10()
+end
+test_ok(test_b10() == 100)
+
+def test_b11
+ ljump_rescue(111) do
+ loop do
+ Proc.new{break 110}.yield
+ break 112
+ end
+ end
+end
+test_ok(test_b11() == 111)
+
+def test_b12
+ loop do
+ break lambda{break 122}.call
+ break 121
+ end
+end
+test_ok(test_b12() == 122)
+
+def test_b13
+ ljump_rescue(133) do
+ while true
+ Proc.new{break 130}.yield
+ break 131
+ end
+ end
+end
+test_ok(test_b13() == 133)
+
+def test_b14
+ while true
+ break lambda{break 144}.call
+ break 143
+ end
+end
+test_ok(test_b14() == 144)
+
+def test_b15
+ [0].each {|c| yield 1 }
+ 156
+end
+test_ok(test_b15{|e| break 155 } == 155)
def marity_test(m)
method = method(m)
- test_ok(method.arity == method.to_proc.arity)
+ test_ok(method.arity == method.to_proc.arity, 2)
end
marity_test(:test_ok)
marity_test(:marity_test)
marity_test(:p)
lambda(&method(:test_ok)).call(true)
-lambda(&get_block{|a,n| test_ok(a,n)}).call(true, 2)
+lambda(&block_get{|a,n| test_ok(a,n)}).call(true, 2)
class ITER_TEST1
def a
@@ -1168,6 +1364,37 @@ end
ITER_TEST4.new.foo(44){55}
+class ITER_TEST5
+ def tt(aa)
+ aa
+ end
+
+ def uu(a)
+ class << self
+ define_method(:tt) do |sym|
+ super(sym)
+ end
+ end
+ end
+
+ def xx(*x)
+ x.size
+ end
+end
+
+a = ITER_TEST5.new
+a.uu(12)
+test_ok(a.tt(1) == 1)
+
+class ITER_TEST6 < ITER_TEST5
+ def xx(*a)
+ a << 12
+ super
+ end
+end
+
+test_ok(ITER_TEST6.new.xx([24]) == 2)
+
test_check "float"
test_ok(2.6.floor == 2)
test_ok((-2.6).floor == -3)
@@ -1258,7 +1485,6 @@ $good = true;
for i in 4000..4096
n1 = 1 << i;
if (n1**2-1) / (n1+1) != (n1-1)
- p i
$good = false
end
end
@@ -1330,7 +1556,7 @@ $x = <<END;
ABCD
ABCD
END
-$x.gsub!(/((.|\n)*?)B((.|\n)*?)D/){$1+$3}
+$x.gsub!(/((.|\n)*?)B((.|\n)*?)D/, '\1\3')
test_ok($x == "AC\nAC\n")
test_ok("foobar" =~ /foo(?=(bar)|(baz))/)
@@ -1362,9 +1588,9 @@ test_ok($x.sub(/.*\.([^\.]+)$/, '<\&>') == "<a.gif>")
# character constants(assumes ASCII)
test_ok("a"[0] == ?a)
test_ok(?a == ?a)
-test_ok(?\C-a == 1)
-test_ok(?\M-a == 225)
-test_ok(?\M-\C-a == 129)
+test_ok(?\C-a == "\1")
+test_ok(?\M-a == "\341")
+test_ok(?\M-\C-a == "\201")
test_ok("a".upcase![0] == ?A)
test_ok("A".downcase![0] == ?a)
test_ok("abc".tr!("a-z", "A-Z") == "ABC")
@@ -1376,7 +1602,7 @@ $x = "abcdef"
$y = [ ?a, ?b, ?c, ?d, ?e, ?f ]
$bad = false
$x.each_byte {|i|
- if i != $y.shift
+ if i.chr != $y.shift
$bad = true
break
end
@@ -1465,20 +1691,20 @@ test_ok(aaa(1, 2, 3, 4) == [1, 2, 3, 4])
test_ok(aaa(1, *[2, 3, 4]) == [1, 2, 3, 4])
test_check "proc"
-$proc = proc{|i| i}
+$proc = Proc.new{|i| i}
test_ok($proc.call(2) == 2)
test_ok($proc.call(3) == 3)
-$proc = proc{|i| i*2}
+$proc = Proc.new{|i| i*2}
test_ok($proc.call(2) == 4)
test_ok($proc.call(3) == 6)
-proc{
+Proc.new{
iii=5 # nested local variable
- $proc = proc{|i|
+ $proc = Proc.new{|i|
iii = i
}
- $proc2 = proc {
+ $proc2 = Proc.new {
$x = iii # nested variables shared by procs
}
# scope of nested variables
@@ -1507,12 +1733,15 @@ if defined? Process.kill
test_check "signal"
$x = 0
- trap "SIGINT", proc{|sig| $x = 2}
+ trap "SIGINT", Proc.new{|sig| $x = 2}
Process.kill "SIGINT", $$
- sleep 0.1
+ 100.times {
+ sleep 0.1
+ break if $x != 0
+ }
test_ok($x == 2)
- trap "SIGINT", proc{raise "Interrupt"}
+ trap "SIGINT", Proc.new{raise "Interrupt"}
x = false
begin
@@ -1586,51 +1815,53 @@ rescue NameError # must raise error
end
test_ok(!$bad)
-x = proc{}
+x = binding #! YARV Limitation: Proc.new{}
eval "i4 = 1", x
test_ok(eval("i4", x) == 1)
-x = proc{proc{}}.call
+x = Proc.new{binding}.call #! YARV Limitation: Proc.new{Proc.new{}}.call
eval "i4 = 22", x
test_ok(eval("i4", x) == 22)
$x = []
-x = proc{proc{}}.call
-eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
+x = Proc.new{binding}.call #! YARV Limitation: Proc.new{Proc.new{}}.call
+eval "(0..9).each{|i5| $x[i5] = Proc.new{i5*2}}", x
test_ok($x[4].call == 8)
x = binding
eval "i = 1", x
test_ok(eval("i", x) == 1)
-x = proc{binding}.call
+x = Proc.new{binding}.call
eval "i = 22", x
test_ok(eval("i", x) == 22)
$x = []
-x = proc{binding}.call
-eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
+x = Proc.new{binding}.call
+eval "(0..9).each{|i5| $x[i5] = Proc.new{i5*2}}", x
test_ok($x[4].call == 8)
-x = proc{binding}.call
+x = Proc.new{binding}.call
eval "for i6 in 1..1; j6=i6; end", x
test_ok(eval("defined? i6", x))
test_ok(eval("defined? j6", x))
-proc {
+Proc.new {
p = binding
eval "foo11 = 1", p
foo22 = 5
- proc{foo11=22}.call
- proc{foo22=55}.call
+ Proc.new{foo11=22}.call
+ Proc.new{foo22=55}.call
test_ok(eval("foo11", p) == eval("foo11"))
test_ok(eval("foo11") == 1)
test_ok(eval("foo22", p) == eval("foo22"))
test_ok(eval("foo22") == 55)
-}.call
+}.call if false #! YARV Limitation
-p1 = proc{i7 = 0; proc{i7}}.call
-test_ok(p1.call == 0)
+#! YARV Limitation: p1 = Proc.new{i7 = 0; Proc.new{i7}}.call
+p1 = Proc.new{i7 = 0; binding}.call
+#! YARV Limitation: test_ok(p1.call == 0)
eval "i7=5", p1
-test_ok(p1.call == 5)
+#! YARV Limitation: test_ok(p1.call == 5)
test_ok(!defined?(i7))
-p1 = proc{i7 = 0; proc{i7}}.call
+if false #! YARV Limitation
+p1 = Proc.new{i7 = 0; Proc.new{i7}}.call
i7 = nil
test_ok(p1.call == 0)
eval "i7=1", p1
@@ -1638,6 +1869,7 @@ test_ok(p1.call == 1)
eval "i7=5", p1
test_ok(p1.call == 5)
test_ok(i7 == nil)
+end
test_check "system"
test_ok(`echo foobar` == "foobar\n")
@@ -1665,7 +1897,7 @@ tmp.print "__END__\n";
tmp.print "this is a trailing junk\n";
tmp.close
-test_ok(`./miniruby -x script_tmp` == 'nil')
+test_ok(`./miniruby -x script_tmp` == '')
test_ok(`./miniruby -x script_tmp -zzz=555` == '555')
tmp = open("script_tmp", "w")
@@ -1674,7 +1906,7 @@ for i in 1..5
end
tmp.close
-`./miniruby -i.bak -pe 'sub(/^[0-9]+$/){$&.to_i * 5}' script_tmp`
+`./miniruby -i.bak -pe '$_.sub!(/^[0-9]+$/){$&.to_i * 5}' script_tmp`
done = true
tmp = open("script_tmp", "r")
while tmp.gets
@@ -1685,26 +1917,33 @@ while tmp.gets
end
tmp.close
test_ok(done)
-
+
File.unlink "script_tmp" or `/bin/rm -f "script_tmp"`
File.unlink "script_tmp.bak" or `/bin/rm -f "script_tmp.bak"`
$bad = false
-if (dir = File.dirname(File.dirname($0))) == '.'
+if (dir = File.dirname(File.dirname(__FILE__))) == '.'
dir = ""
else
dir << "/"
end
def valid_syntax?(code, fname)
- eval("BEGIN {return true}\n#{code}", nil, fname, 0)
+ p fname
+ code = code.dup.force_encoding("ascii-8bit")
+ code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n) {
+ "#$&#{"\n" if $1 && !$2}BEGIN{throw tag, :ok}\n"
+ }
+ code.force_encoding("us-ascii")
+ catch {|tag| eval(code, binding, fname, 0)}
rescue Exception
- puts $!.message
+ STDERR.puts $!.message
false
end
-for script in Dir["#{dir}{lib,sample,ext}/**/*.rb"]
+for script in Dir["#{dir}{lib,sample,ext,test}/**/*.rb"].sort
unless valid_syntax? IO::read(script), script
+ STDERR.puts script
$bad = true
end
end
@@ -1836,7 +2075,7 @@ $_ = foobar
test_ok($_ == foobar)
class Gods
- @@rule = "Uranus"
+ @@rule = "Uranus" # private to Gods
def ruler0
@@rule
end
@@ -1852,15 +2091,18 @@ class Gods
end
module Olympians
- @@rule ="Zeus"
- def ruler3
+ @@rule ="Zeus"
+ def ruler3
@@rule
end
end
class Titans < Gods
- @@rule = "Cronus"
- include Olympians # OK to cause warning (intentional)
+ @@rule = "Cronus" # do not affect @@rule in Gods
+ include Olympians
+ def ruler4
+ @@rule
+ end
end
test_ok(Gods.new.ruler0 == "Cronus")
@@ -1871,11 +2113,12 @@ test_ok(Titans.ruler2 == "Cronus")
atlas = Titans.new
test_ok(atlas.ruler0 == "Cronus")
test_ok(atlas.ruler3 == "Zeus")
+test_ok(atlas.ruler4 == "Cronus")
test_check "trace"
$x = 1234
$y = 0
-trace_var :$x, proc{$y = $x}
+trace_var :$x, Proc.new{$y = $x}
$x = 40414
test_ok($y == $x)
@@ -1883,7 +2126,7 @@ untrace_var :$x
$x = 19660208
test_ok($y != $x)
-trace_var :$x, proc{$x *= 2}
+trace_var :$x, Proc.new{$x *= 2}
$x = 5
test_ok($x == 10)
@@ -2001,6 +2244,15 @@ end
test_ok(File.expand_path(".", "//") == "//")
test_ok(File.expand_path("sub", "//") == "//sub")
+# test_check "Proc#binding"
+ObjectSpace.each_object(Proc){|o|
+ begin
+ b = o.binding
+ eval 'self', b
+ rescue ArgumentError
+ end
+}
+
test_check "gc"
begin
1.upto(10000) {
@@ -2029,8 +2281,14 @@ l = []
GC.start
test_ok true # reach here or dumps core
+ObjectSpace.each_object{|o|
+ o.class.name
+}
+
+test_ok true # reach here or dumps core
+
if $failed > 0
- printf "test: %d failed %d\n", $ntest, $failed
+ printf "not ok/test: %d failed %d\n", $ntest, $failed
else
printf "end of test(test: %d)\n", $ntest
end
diff --git a/sample/time.rb b/sample/time.rb
index 84fa9e1a8d..e16912052e 100644
--- a/sample/time.rb
+++ b/sample/time.rb
@@ -1,8 +1,12 @@
-#! /usr/local/bin/ruby
-cmd = ARGV.join(" ")
+#! /usr/bin/env ruby
+
b = Time.now
-system(cmd)
+system(*ARGV)
e = Time.now
-ut, st, cut, cst = Time.times.to_a
-total = (e - b).to_f
-STDERR.printf "%11.1f real %11.1f user %11.1f sys\n", total, cut, cst
+
+tms = Process.times
+real = e - b
+user = tms.cutime
+sys = tms.cstime
+
+STDERR.printf("%11.1f real %11.1f user %11.1f sys\n", real, user, sys)
diff --git a/sample/timeout.rb b/sample/timeout.rb
new file mode 100644
index 0000000000..2870ddb239
--- /dev/null
+++ b/sample/timeout.rb
@@ -0,0 +1,42 @@
+require 'timeout'
+
+def progress(n = 5)
+ n.times {|i| print i; STDOUT.flush; sleep 1; i+= 1}
+ puts "never reach"
+end
+
+p timeout(5) {
+ 45
+}
+p timeout(5, TimeoutError) {
+ 45
+}
+p timeout(nil) {
+ 54
+}
+p timeout(0) {
+ 54
+}
+begin
+ timeout(5) {progress}
+rescue => e
+ puts e.message
+end
+begin
+ timeout(3) {
+ begin
+ timeout(5) {progress}
+ rescue => e
+ puts "never reach"
+ end
+ }
+rescue => e
+ puts e.message
+end
+class MyTimeout < StandardError
+end
+begin
+ timeout(2, MyTimeout) {progress}
+rescue MyTimeout => e
+ puts e.message
+end
diff --git a/sample/tsvr.rb b/sample/tsvr.rb
index 52cdd32dce..2fa6c87ef9 100644
--- a/sample/tsvr.rb
+++ b/sample/tsvr.rb
@@ -3,7 +3,7 @@
require "socket"
-gs = TCPserver.open(0)
+gs = TCPServer.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))