Top Level Namespace

Includes:
Rake::DSL

Defined Under Namespace

Modules: Benchmark, Bug, Bundler, CoreExtensions, Coverage, DidYouMean, Digest, English, Enumerable, ErrorHighlight, Etc, Fcntl, Fiddle, FileUtils, Find, Forwardable, Gem, IRB, JSON, Kernel, MakeMakefile, Memory, MemoryViewTestUtils, MonitorMixin, Net, Num2int, ObjectSpace, Open3, OpenSSL, OpenURI, PTY, Prism, Psych, RDoc, Racc, Rake, Reline, ResolveSymbolResolver, ResolveSymbolTarget, SecureRandom, Shellwords, SingleForwardable, Singleton, StringifySymbols, StringifyTarget, SyntaxSuggest, TSort, Timeout, UN, URI, UnicodeNormalize, Win32, YAML, Zlib Classes: Addrinfo, Array, BasicSocket, BigDecimal, Binding, CGI, Class, Complex, DSL, Data, Date, DateTime, Delegator, Dir, ENV, ERB, Exception, File, Hash, IO, IPAddr, IPSocket, Integer, LoadError, Logger, MatchData, Monitor, Object, OpenStruct, OptionParser, PP, PStore, Pathname, PrettyPrint, Range, Rational, Regexp, Resolv, Ripper, SOCKSSocket, Set, SimpleDelegator, Socket, SocketError, String, StringIO, StringScanner, Struct, Symbol, TCPServer, TCPSocket, Tempfile, Thread, Time, UDPSocket, UNIXServer, UNIXSocket, WIN32OLE, WeakRef, XMP

Constant Summary collapse

RubyLex =
IRB::RubyLex
ParseError =

:nodoc:

Racc::ParseError
DUMMY_SIGNATURE =
"***DUMMY MAKEFILE***"
EXEEXT =
MTIMES =
[__FILE__, 'rbconfig.rb', srcdir+'/lib/mkmf.rb'].collect {|f| File.mtime(f)}
OS_NAMES =
{
  'OS_MSDOS'   => 'MS-DOS',
  'OS_AMIGA'   => 'Amiga',
  'OS_VMS'     => 'VMS',
  'OS_UNIX'    => 'Unix',
  'OS_ATARI'   => 'Atari',
  'OS_MACOS'   => 'MacOS',
  'OS_TOPS20'  => 'TOPS20',
  'OS_WIN32'   => 'Win32',
  'OS_VMCMS'   => 'VM/CMS',
  'OS_ZSYSTEM' => 'Z-System',
  'OS_CPM'     => 'CP/M',
  'OS_QDOS'    => 'QDOS',
  'OS_RISCOS'  => 'RISCOS',
  'OS_UNKNOWN' => 'Unknown',
}
AF_INET6_SOCKET_CREATION_TEST =
<<EOF
#include <sys/types.h>
#ifndef _WIN32
#include <sys/socket.h>
#endif
int
main(void)
{
  socket(AF_INET6, SOCK_STREAM, 0);
  return 0;
}
EOF
GETADDRINFO_GETNAMEINFO_TEST =
<<EOF
#include <stdlib.h>

#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif

#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#endif

int
main(void)
{
  int passive, gaierr, inet4 = 0, inet6 = 0;
  struct addrinfo hints, *ai, *aitop;
  char straddr[INET6_ADDRSTRLEN], strport[16];
#ifdef _WIN32
  WSADATA retdata;

  WSAStartup(MAKEWORD(2, 0), &retdata);
#endif

  for (passive = 0; passive <= 1; passive++) {
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = passive ? AI_PASSIVE : 0;
    hints.ai_socktype = SOCK_STREAM;
    if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) {
      (void)gai_strerror(gaierr);
      goto bad;
    }
    for (ai = aitop; ai; ai = ai->ai_next) {
      if (ai->ai_family == AF_LOCAL) continue;
      if (ai->ai_addr == NULL)
        goto bad;
#if defined(_AIX)
      if (ai->ai_family == AF_INET6 && passive) {
        inet6++;
        continue;
      }
      ai->ai_addr->sa_len = ai->ai_addrlen;
      ai->ai_addr->sa_family = ai->ai_family;
#endif
      if (ai->ai_addrlen == 0 ||
          getnameinfo(ai->ai_addr, ai->ai_addrlen,
                      straddr, sizeof(straddr), strport, sizeof(strport),
                      NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
        goto bad;
      }
      if (strcmp(strport, "54321") != 0) {
        goto bad;
      }
      switch (ai->ai_family) {
      case AF_INET:
        if (passive) {
          if (strcmp(straddr, "0.0.0.0") != 0) {
            goto bad;
          }
        } else {
          if (strcmp(straddr, "127.0.0.1") != 0) {
            goto bad;
          }
        }
        inet4++;
        break;
      case AF_INET6:
        if (passive) {
          if (strcmp(straddr, "::") != 0) {
            goto bad;
          }
        } else {
          if (strcmp(straddr, "::1") != 0) {
            goto bad;
          }
        }
        inet6++;
        break;
      case AF_UNSPEC:
        goto bad;
        break;
      default:
        /* another family support? */
        break;
      }
    }
  }

  if (!(inet4 == 0 || inet4 == 2))
    goto bad;
  if (!(inet6 == 0 || inet6 == 2))
    goto bad;

  if (aitop)
    freeaddrinfo(aitop);
  return EXIT_SUCCESS;

 bad:
  if (aitop)
    freeaddrinfo(aitop);
  return EXIT_FAILURE;
}
EOF
RECVMSG_WITH_MSG_PEEK_ALLOCATE_FD_TEST =
<<'EOF'
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int ps[2], sv[2];
    int ret;
    ssize_t ss;
    int s_fd, r_fd;
    struct msghdr s_msg, r_msg;
    union {
        struct cmsghdr hdr;
        char dummy[CMSG_SPACE(sizeof(int))];
    } s_cmsg, r_cmsg;
    struct iovec s_iov, r_iov;
    char s_buf[1], r_buf[1];
    struct stat s_statbuf, r_statbuf;

    ret = pipe(ps);
    if (ret == -1) { perror("pipe"); exit(EXIT_FAILURE); }

    s_fd = ps[0];

    ret = socketpair(AF_UNIX, SOCK_DGRAM, 0, sv);
    if (ret == -1) { perror("socketpair"); exit(EXIT_FAILURE); }

    s_msg.msg_name = NULL;
    s_msg.msg_namelen = 0;
    s_msg.msg_iov = &s_iov;
    s_msg.msg_iovlen = 1;
    s_msg.msg_control = &s_cmsg;
    s_msg.msg_controllen = CMSG_SPACE(sizeof(int));;
    s_msg.msg_flags = 0;

    s_iov.iov_base = &s_buf;
    s_iov.iov_len = sizeof(s_buf);

    s_buf[0] = 'a';

    s_cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(int));
    s_cmsg.hdr.cmsg_level = SOL_SOCKET;
    s_cmsg.hdr.cmsg_type = SCM_RIGHTS;
    memcpy(CMSG_DATA(&s_cmsg.hdr), (char *)&s_fd, sizeof(int));

    ss = sendmsg(sv[0], &s_msg, 0);
    if (ss == -1) { perror("sendmsg"); exit(EXIT_FAILURE); }

    r_msg.msg_name = NULL;
    r_msg.msg_namelen = 0;
    r_msg.msg_iov = &r_iov;
    r_msg.msg_iovlen = 1;
    r_msg.msg_control = &r_cmsg;
    r_msg.msg_controllen = CMSG_SPACE(sizeof(int));
    r_msg.msg_flags = 0;

    r_iov.iov_base = &r_buf;
    r_iov.iov_len = sizeof(r_buf);

    r_buf[0] = '0';

    memset(&r_cmsg, 0xff, CMSG_SPACE(sizeof(int)));

    ss = recvmsg(sv[1], &r_msg, MSG_PEEK);
    if (ss == -1) { perror("recvmsg"); exit(EXIT_FAILURE); }

    if (ss != 1) {
        fprintf(stderr, "unexpected return value from recvmsg: %ld\n", (long)ss);
        exit(EXIT_FAILURE);
    }
    if (r_buf[0] != 'a') {
        fprintf(stderr, "unexpected return data from recvmsg: 0x%02x\n", r_buf[0]);
        exit(EXIT_FAILURE);
    }

    if (r_msg.msg_controllen < CMSG_LEN(sizeof(int))) {
        fprintf(stderr, "unexpected: r_msg.msg_controllen < CMSG_LEN(sizeof(int)) not hold: %ld\n",
                (long)r_msg.msg_controllen);
        exit(EXIT_FAILURE);
    }
    if (r_cmsg.hdr.cmsg_len < CMSG_LEN(sizeof(int))) {
        fprintf(stderr, "unexpected: r_cmsg.hdr.cmsg_len < CMSG_LEN(sizeof(int)) not hold: %ld\n",
                (long)r_cmsg.hdr.cmsg_len);
        exit(EXIT_FAILURE);
    }
    memcpy((char *)&r_fd, CMSG_DATA(&r_cmsg.hdr), sizeof(int));

    if (r_fd < 0) {
        fprintf(stderr, "negative r_fd: %d\n", r_fd);
        exit(EXIT_FAILURE);
    }

    if (r_fd == s_fd) {
        fprintf(stderr, "r_fd and s_fd is same: %d\n", r_fd);
        exit(EXIT_FAILURE);
    }

    ret = fstat(s_fd, &s_statbuf);
    if (ret == -1) { perror("fstat(s_fd)"); exit(EXIT_FAILURE); }

    ret = fstat(r_fd, &r_statbuf);
    if (ret == -1) { perror("fstat(r_fd)"); exit(EXIT_FAILURE); }

    if (s_statbuf.st_dev != r_statbuf.st_dev ||
        s_statbuf.st_ino != r_statbuf.st_ino) {
        fprintf(stderr, "dev/ino doesn't match: s_fd:%ld/%ld r_fd:%ld/%ld\n",
                (long)s_statbuf.st_dev, (long)s_statbuf.st_ino,
                (long)r_statbuf.st_dev, (long)r_statbuf.st_ino);
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
EOF
C_ESC =
{
  "\\" => "\\\\",
  '"' => '\"',
  "\n" => '\n',
}
C_ESC_PAT =
Regexp.union(*C_ESC.keys)
CONST_PREFIXES =
{
  'SC' => 'for Etc.sysconf; See <tt>man sysconf</tt>',
  'CS' => 'for Etc.confstr; See <tt>man constr</tt>',
  'PC' => 'for IO#pathconf; See <tt>man fpathconf</tt>',
}
COMMENTS =
Hash.new { |h, name| h[name] = name }
DEFS =
h.to_a
NAME_TO_INT_DEFS =
[]
INTERN_DEFS =
[]
OptParse =

An alias for OptionParser.

OptionParser

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.%(x) ⇒ Object



353
354
355
# File 'ext/socket/extconf.rb', line 353

def (fmt = "none").%(x)
  x || self
end

.defined?(var) ⇒ Boolean

Returns:

  • (Boolean)


380
381
382
383
# File 'ext/extmk.rb', line 380

def $mflags.defined?(var)
  grep(/\A#{var}=(.*)/) {return $1}
  false
end

.set?(flag) ⇒ Boolean

Returns:

  • (Boolean)


376
377
378
379
# File 'ext/extmk.rb', line 376

def $mflags.set?(flag)
  grep(/\A-(?!-).*#{flag.chr}/i) { return true }
  false
end

Instance Method Details

#atomic_write_open(filename) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'ext/extmk.rb', line 63

def atomic_write_open(filename)
  filename_new = filename + ".new.#$$"
  clean = false
  File.open(filename_new, "wbx") do |f|
    clean = true
    yield f
  end
  if File.binread(filename_new) != (File.binread(filename) rescue nil)
    File.rename(filename_new, filename)
    clean = false
  end
ensure
  if clean
    File.unlink(filename_new)
  end
end

#auto_ext(feat = $0[%r[/ext/(-test-/.*)/extconf.rb\z], 1], inc: false) ⇒ Object



2
3
4
5
6
7
8
9
10
11
# File 'ext/-test-/auto_ext.rb', line 2

def auto_ext(feat = $0[%r[/ext/(-test-/.*)/extconf.rb\z], 1], inc: false)
  $INCFLAGS << " -I$(topdir) -I$(top_srcdir)" if inc
  $srcs = Dir[File.join($srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
  inits = $srcs.map {|s| File.basename(s, ".*")}
  inits.delete("init")
  inits.map! {|s|"X(#{s})"}
  $defs << "-DTEST_INIT_FUNCS(X)=\"#{inits.join(' ')}\""
  create_header
  create_makefile(feat)
end

#c_str(str) ⇒ Object



15
16
17
# File 'ext/etc/mkconstants.rb', line 15

def c_str(str)
  '"' + str.gsub(C_ESC_PAT) {|s| C_ESC[s]} + '"'
end

#check_arity(h) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
# File 'ext/ripper/tools/generate.rb', line 153

def check_arity(h)
  invalid = false
  h.each do |event, list|
    unless list.map {|line, arity| arity }.uniq.size == 1
      invalid = true
      locations = list.map {|line, a| "#{line}:#{a}" }.join(', ')
      $stderr.puts "arity crash [event=#{event}]: #{locations}"
    end
  end
  abort if invalid
end

#check_socklen(headers) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'ext/socket/extconf.rb', line 352

def check_socklen(headers)
  def (fmt = "none").%(x)
    x || self
  end
  s = checking_for("RSTRING_SOCKLEN", fmt) do
    if try_static_assert("sizeof(socklen_t) >= sizeof(long)", headers)
      "RSTRING_LEN"
    else
      "RSTRING_LENINT"
    end
  end
  $defs << "-DRSTRING_SOCKLEN=(socklen_t)"+s
end

#chmodObject

Change the mode of each FILE to OCTAL-MODE.

ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE

-v          verbose


219
220
221
222
223
224
225
# File 'lib/un.rb', line 219

def chmod
  setup do |argv, options|
    mode = argv.shift
    mode = /\A\d/ =~ mode ? mode.oct : mode
    FileUtils.chmod mode, argv, **options
  end
end

#colorizeObject

Colorize ruby code.

ruby -run -e colorize -- [FILE]


384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/un.rb', line 384

def colorize
  begin
    require "irb/color"
  rescue LoadError
    raise "colorize requires irb 1.1.0 or later"
  end
  setup do |argv, |
    if argv.empty?
      puts IRB::Color.colorize_code STDIN.read
      return
    end
    argv.each do |file|
      puts IRB::Color.colorize_code File.read(file)
    end
  end
end

#cpObject

Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY

ruby -run -e cp -- [OPTION] SOURCE DEST

-p          preserve file attributes if possible
-r          copy recursively
-l          make hard link instead of copying (implies -r)
-v          verbose


85
86
87
88
89
90
91
92
93
94
95
# File 'lib/un.rb', line 85

def cp
  setup("prl") do |argv, options|
    cmd = "cp"
    cmd += "_r" if options.delete :r
    cmd = "cp_lr" if options.delete :l
    options[:preserve] = true if options.delete :p
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.__send__ cmd, argv, dest, **options
  end
end

#create_makefile(target, srcprefix = nil) ⇒ Object



135
136
137
138
139
140
141
# File 'ext/extmk.rb', line 135

def create_makefile(target, srcprefix = nil)
  if $static and target.include?("/")
    base = File.basename(target)
    $defs << "-DInit_#{base}=Init_#{target.tr('/', '_')}"
  end
  super
end

#create_win32ole_makefileObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'ext/win32ole/extconf.rb', line 16

def create_win32ole_makefile
  if have_library("ole32") and
     have_library("oleaut32") and
     have_library("uuid", "&CLSID_CMultiLanguage", "mlang.h") and
     have_library("user32") and
     have_library("kernel32") and
     have_library("advapi32") and
     have_header("windows.h")
    unless have_type("IMultiLanguage2", "mlang.h")
      have_type("IMultiLanguage", "mlang.h")
    end
    spec = nil
    checking_for('thread_specific', '%s') do
      spec = %w[__declspec(thread) __thread].find {|th|
        try_compile("#{th} int foo;", "", :werror => true)
      }
      spec or 'no'
    end
    $defs << "-DRB_THREAD_SPECIFIC=#{spec}" if spec
    create_makefile("win32ole")
  end
end

#def_intern(func_name, pat, prefix_optional = nil) ⇒ Object



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'ext/socket/mkconstants.rb', line 246

def def_intern(func_name, pat, prefix_optional=nil)
  prefix_pat = nil
  if prefix_optional
    if Regexp === prefix_optional
      prefix_pat = prefix_optional
    else
      prefix_pat = /\A#{Regexp.escape prefix_optional}/
    end
  end
  hash_var = "#{func_name}_hash"
  vardef = "static st_table *#{hash_var};"
  gen_hash = gen_int_to_name_hash(hash_var, pat, prefix_pat)
  decl = gen_int_to_name_decl(func_name, hash_var)
  func = gen_int_to_name_func(func_name, hash_var)
  INTERN_DEFS << [vardef, gen_hash, decl, func]
end

#def_name_to_int(funcname, pat, prefix_optional, guard = nil) ⇒ Object



203
204
205
206
207
# File 'ext/socket/mkconstants.rb', line 203

def def_name_to_int(funcname, pat, prefix_optional, guard=nil)
  decl = gen_name_to_int_decl(funcname, pat, prefix_optional, guard)
  func = gen_name_to_int_func(funcname, pat, prefix_optional, guard)
  NAME_TO_INT_DEFS << [decl, func]
end

#DelegateClass(superclass, &block) ⇒ Object

The primary interface to this library. Use to setup delegation when defining your class.

class MyClass < DelegateClass(ClassToDelegateTo) # Step 1
  def initialize
    super(obj_of_ClassToDelegateTo)              # Step 2
  end
end

or:

MyClass = DelegateClass(ClassToDelegateTo) do    # Step 1
  def initialize
    super(obj_of_ClassToDelegateTo)              # Step 2
  end
end

Here’s a sample of use from Tempfile which is really a File object with a few special rules about storage location and when the File should be deleted. That makes for an almost textbook perfect example of how to use delegation.

class Tempfile < DelegateClass(File)
  # constant and class member data initialization...

  def initialize(basename, tmpdir=Dir::tmpdir)
    # build up file path/name in var tmpname...

    @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)

    # ...

    super(@tmpfile)

    # below this point, all methods of File are supported...
  end

  # ...
end


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/delegate.rb', line 394

def DelegateClass(superclass, &block)
  klass = Class.new(Delegator)
  ignores = [*::Delegator.public_api, :to_s, :inspect, :=~, :!~, :===]
  protected_instance_methods = superclass.protected_instance_methods
  protected_instance_methods -= ignores
  public_instance_methods = superclass.public_instance_methods
  public_instance_methods -= ignores
  klass.module_eval do
    def __getobj__ # :nodoc:
      unless defined?(@delegate_dc_obj)
        return yield if block_given?
        __raise__ ::ArgumentError, "not delegated"
      end
      @delegate_dc_obj
    end
    def __setobj__(obj)  # :nodoc:
      __raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj)
      @delegate_dc_obj = obj
    end
    protected_instance_methods.each do |method|
      define_method(method, Delegator.delegating_block(method))
      protected method
    end
    public_instance_methods.each do |method|
      define_method(method, Delegator.delegating_block(method))
    end
  end
  klass.define_singleton_method :public_instance_methods do |all=true|
    super(all) | superclass.public_instance_methods
  end
  klass.define_singleton_method :protected_instance_methods do |all=true|
    super(all) | superclass.protected_instance_methods
  end
  klass.define_singleton_method :instance_methods do |all=true|
    super(all) | superclass.instance_methods
  end
  klass.define_singleton_method :public_instance_method do |name|
    super(name)
  rescue NameError
    raise unless self.public_instance_methods.include?(name)
    superclass.public_instance_method(name)
  end
  klass.define_singleton_method :instance_method do |name|
    super(name)
  rescue NameError
    raise unless self.instance_methods.include?(name)
    superclass.instance_method(name)
  end
  klass.module_eval(&block) if block
  return klass
end

#Digest(name) ⇒ Object

call-seq:

Digest(name) -> digest_subclass

Returns a Digest subclass by name in a thread-safe manner even when on-demand loading is involved.

require 'digest'

Digest("MD5")
# => Digest::MD5

Digest(:SHA256)
# => Digest::SHA256

Digest(:Foo)
# => LoadError: library not found for class Digest::Foo -- digest/foo


110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'ext/digest/lib/digest.rb', line 110

def Digest(name)
  const = name.to_sym
  Digest::REQUIRE_MUTEX.synchronize {
    # Ignore autoload's because it is void when we have #const_missing
    Digest.const_missing(const)
  }
rescue LoadError
  # Constants do not necessarily rely on digest/*.
  if Digest.const_defined?(const)
    Digest.const_get(const)
  else
    raise
  end
end

#digest_conf(name) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'ext/digest/digest_conf.rb', line 3

def digest_conf(name)
  unless with_config("bundled-#{name}")
    cc = with_config("common-digest")
    if cc != false or /\b#{name}\b/ =~ cc
      if File.exist?("#$srcdir/#{name}cc.h") and
        have_header("CommonCrypto/CommonDigest.h")
        $defs << "-D#{name.upcase}_USE_COMMONDIGEST"
        $headers << "#{name}cc.h"
        return :commondigest
      end
    end
  end
  $objs << "#{name}.#{$OBJEXT}"
  return
end

#disable_optimization_build_flag(flags) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'ext/fiddle/extconf.rb', line 10

def disable_optimization_build_flag(flags)
  if gcc?
    expanded_flags = RbConfig.expand(flags.dup)
    optimization_option_pattern = /(^|\s)?-O\d(\s|$)?/
    if optimization_option_pattern.match?(expanded_flags)
      expanded_flags.gsub(optimization_option_pattern, '\\1-Og\\2')
    else
      flags + " -Og"
    end
  else
    flags
  end
end

#each_constObject



69
70
71
72
73
# File 'ext/etc/mkconstants.rb', line 69

def each_const
  DEFS.each {|name, default_value|
    yield name, default_value
  }
end

#each_name(pat) ⇒ Object



75
76
77
78
79
80
# File 'ext/etc/mkconstants.rb', line 75

def each_name(pat)
  DEFS.each {|name, default_value|
    next if pat !~ name
    yield name
  }
end

#each_names_with_len(pat, prefix_optional = nil) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'ext/socket/mkconstants.rb', line 129

def each_names_with_len(pat, prefix_optional=nil)
  h = {}
  DEFS.each {|name, default_value|
    next if pat !~ name
    (h[name.length] ||= []) << [name, name]
  }
  if prefix_optional
    if Regexp === prefix_optional
      prefix_pat = prefix_optional
    else
      prefix_pat = /\A#{Regexp.escape prefix_optional}/
    end
    DEFS.each {|const, default_value|
      next if pat !~ const
      next if prefix_pat !~ const
      name = $'
      (h[name.length] ||= []) << [name, const]
    }
  end
  hh = {}
  h.each {|len, pairs|
    pairs.each {|name, const|
      raise "name crash: #{name}" if hh[name]
      hh[name] = true
    }
  }
  h.keys.sort.each {|len|
    yield h[len], len
  }
end

#enable_debug_build_flag(flags) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'ext/fiddle/extconf.rb', line 24

def enable_debug_build_flag(flags)
  if gcc?
    expanded_flags = RbConfig.expand(flags.dup)
    debug_option_pattern = /(^|\s)-g(?:gdb)?\d?(\s|$)/
    if debug_option_pattern.match?(expanded_flags)
      expanded_flags.gsub(debug_option_pattern, '\\1-ggdb3\\2')
    else
      flags + " -ggdb3"
    end
  else
    flags
  end
end

#extmake(target, basedir = 'ext', maybestatic = true) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'ext/extmk.rb', line 143

def extmake(target, basedir = 'ext', maybestatic = true)
  FileUtils.mkpath target unless File.directory?(target)
  begin
    # don't build if parent library isn't build
    parent = true
    d = target
    until (d = File.dirname(d)) == '.'
      if File.exist?("#{$top_srcdir}/#{basedir}/#{d}/extconf.rb")
        parent = (/^all:\s*install/ =~ File.read("#{d}/Makefile") rescue false)
        break
      end
    end

    dir = Dir.pwd
    FileUtils.mkpath target unless File.directory?(target)
    Dir.chdir target
    top_srcdir = $top_srcdir
    topdir = $topdir
    hdrdir = $hdrdir
    prefix = "../" * (basedir.count("/")+target.count("/")+1)
    $top_srcdir = relative_from(top_srcdir, prefix)
    $hdrdir = relative_from(hdrdir, prefix)
    $topdir = prefix + $topdir
    $target = target
    $mdir = target
    $srcdir = File.join($top_srcdir, basedir, $mdir)
    $preload = nil
    $objs = []
    $srcs = []
    $extso = []
    makefile = "./Makefile"
    static = $static
    $static = nil if noinstall = File.fnmatch?("-*", target)
    ok = parent && File.exist?(makefile)
    if parent
      rbconfig0 = RbConfig::CONFIG
      mkconfig0 = CONFIG
      rbconfig = {
	"hdrdir" => $hdrdir,
	"srcdir" => $srcdir,
	"topdir" => $topdir,
      }
      mkconfig = {
	"hdrdir" => ($hdrdir == top_srcdir) ? top_srcdir : "$(top_srcdir)/include",
	"srcdir" => "$(top_srcdir)/#{basedir}/#{$mdir}",
	"topdir" => $topdir,
      }
      rbconfig0.each_pair {|key, val| rbconfig[key] ||= val.dup}
      mkconfig0.each_pair {|key, val| mkconfig[key] ||= val.dup}
      RbConfig.module_eval {
	remove_const(:CONFIG)
	const_set(:CONFIG, rbconfig)
	remove_const(:MAKEFILE_CONFIG)
	const_set(:MAKEFILE_CONFIG, mkconfig)
      }
      MakeMakefile.class_eval {
	remove_const(:CONFIG)
	const_set(:CONFIG, mkconfig)
      }
      begin
	$extconf_h = nil
	ok &&= extract_makefile(makefile)
	old_objs = $objs
	old_cleanfiles = $distcleanfiles | $cleanfiles
	conf = ["#{$srcdir}/makefile.rb", "#{$srcdir}/extconf.rb"].find {|f| File.exist?(f)}
	if (!ok || ($extconf_h && !File.exist?($extconf_h)) ||
	    !(t = modified?(makefile, MTIMES)) ||
	    [conf, "#{$srcdir}/depend"].any? {|f| modified?(f, [t])})
        then
	  ok = false
          if verbose?
            print "#{conf}\n" if conf
          else
            print "#{$message} #{target}\n"
          end
          $stdout.flush
          init_mkmf
	  Logging::logfile 'mkmf.log'
	  rm_f makefile
	  if conf
            Logging.open do
              unless verbose?
                $stderr.reopen($stdout.reopen(@null))
              end
              load $0 = conf
            end
	  else
	    create_makefile(target)
	  end
	  $defs << "-DRUBY_EXPORT" if $static
	  ok = File.exist?(makefile)
	end
      rescue SystemExit
	# ignore
      rescue => error
        ok = false
      ensure
	rm_f "conftest*"
	$0 = $PROGRAM_NAME
      end
    end
    ok &&= File.open(makefile){|f| s = f.gets and !s[DUMMY_SIGNATURE]}
    unless ok
      mf = ["# #{DUMMY_SIGNATURE}\n", *dummy_makefile(CONFIG["srcdir"])].join("")
      atomic_write_open(makefile) do |f|
        f.print(mf)
      end

      return true if !error and target.start_with?("-")

      message = nil
      if error
        loc = error.backtrace_locations[0]
        message = "#{loc.absolute_path}:#{loc.lineno}: #{error.message}"
        if Logging.log_opened?
          Logging::message("#{message}\n\t#{error.backtrace.join("\n\t")}\n")
        end
      end

      return [parent, message]
    end
    args = $mflags
    unless $destdir.to_s.empty? or $mflags.defined?("DESTDIR")
      args += ["DESTDIR=" + relative_from($destdir, "../"+prefix)]
    end
    if $static and ok and !$objs.empty? and !noinstall
      args += ["static"]
      $extlist.push [(maybestatic ? $static : false), target, $target, $preload]
    end
    FileUtils.rm_f(old_cleanfiles - $distcleanfiles - $cleanfiles)
    FileUtils.rm_f(old_objs - $objs)
    if $static
      $extflags ||= ""
      $extlibs ||= []
      $extpath ||= []
      unless $mswin
        $extflags = split_libs($extflags, $DLDFLAGS, $LDFLAGS).uniq.join(" ")
      end
      $extlibs = merge_libs($extlibs, split_libs($libs, $LOCAL_LIBS).map {|lib| lib.sub(/\A\.\//, "ext/#{target}/")})
      $extpath |= $LIBPATH
    end
  ensure
    Logging::log_close
    if rbconfig0
      RbConfig.module_eval {
	remove_const(:CONFIG)
	const_set(:CONFIG, rbconfig0)
	remove_const(:MAKEFILE_CONFIG)
	const_set(:MAKEFILE_CONFIG, mkconfig0)
      }
    end
    if mkconfig0
      MakeMakefile.class_eval {
	remove_const(:CONFIG)
	const_set(:CONFIG, mkconfig0)
      }
    end
    $top_srcdir = top_srcdir
    $topdir = topdir
    $hdrdir = hdrdir
    $static = static
    Dir.chdir dir
  end
  begin
    Dir.rmdir target
    target = File.dirname(target)
  rescue SystemCallError
    break
  end while true
  true
end

#extract_makefile(makefile, keep = true) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'ext/extmk.rb', line 80

def extract_makefile(makefile, keep = true)
  m = File.read(makefile)
  s = m[/^CLEANFILES[ \t]*=[ \t](.*)/, 1] and $cleanfiles = s.split
  s = m[/^DISTCLEANFILES[ \t]*=[ \t](.*)/, 1] and $distcleanfiles = s.split
  s = m[/^EXTSO[ \t]*=[ \t](.*)/, 1] and $extso = s.split
  if !(target = m[/^TARGET[ \t]*=[ \t]*(\S*)/, 1])
    return keep
  end
  installrb = {}
  m.scan(/^(?:do-)?install-rb-default:.*[ \t](\S+)(?:[ \t].*)?\n\1:[ \t]*(\S+)/) {installrb[$2] = $1}
  oldrb = installrb.keys.sort
  newrb = install_rb(nil, "").collect {|d, *f| f}.flatten.sort
  if target_prefix = m[/^target_prefix[ \t]*=[ \t]*\/(.*)/, 1]
    target = "#{target_prefix}/#{target}"
  end
  unless oldrb == newrb
    if $extout
      newrb.each {|f| installrb.delete(f)}
      unless installrb.empty?
        config = CONFIG.dup
        install_dirs(target_prefix).each {|var, val| config[var] = val}
        FileUtils.rm_f(installrb.values.collect {|f| RbConfig.expand(f, config)},
                       :verbose => verbose?)
      end
    end
    return false
  end
  srcs = Dir[*SRC_EXT.map {|e| "*.#{e}"}, base: $srcdir].map {|fn| File.basename(fn)}.sort
  if !srcs.empty?
    old_srcs = m[/^ORIG_SRCS[ \t]*=[ \t](.*)/, 1] or return false
    (old_srcs.split - srcs).empty? or return false
  end
  $target = target
  $extconf_h = m[/^RUBY_EXTCONF_H[ \t]*=[ \t]*(\S+)/, 1]
  if $static.nil?
    $static ||= m[/^EXTSTATIC[ \t]*=[ \t]*(\S+)/, 1] || false
    /^STATIC_LIB[ \t]*=[ \t]*\S+/ =~ m or $static = false
  end
  $preload = Shellwords.shellwords(m[/^preload[ \t]*=[ \t]*(.*)/, 1] || "")
  if dldflags = m[/^dldflags[ \t]*=[ \t]*(.*)/, 1] and !$DLDFLAGS.include?(dldflags)
    $DLDFLAGS += " " + dldflags
  end
  if s = m[/^LIBS[ \t]*=[ \t]*(.*)/, 1]
    s.sub!(/^#{Regexp.quote($LIBRUBYARG)} */, "")
    s.sub!(/ *#{Regexp.quote($LIBS)}$/, "")
    $libs = s
  end
  $objs = (m[/^OBJS[ \t]*=[ \t](.*)/, 1] || "").split
  $srcs = (m[/^SRCS[ \t]*=[ \t](.*)/, 1] || "").split
  $headers = (m[/^LOCAL_HDRS[ \t]*=[ \t](.*)/, 1] || "").split
  $LOCAL_LIBS = m[/^LOCAL_LIBS[ \t]*=[ \t]*(.*)/, 1] || ""
  $LIBPATH = Shellwords.shellwords(m[/^libpath[ \t]*=[ \t]*(.*)/, 1] || "") - %w[$(libdir) $(topdir)]
  true
end

#find_openssl_libraryObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'ext/openssl/extconf.rb', line 67

def find_openssl_library
  if $mswin || $mingw
    # required for static OpenSSL libraries
    have_library("gdi32") # OpenSSL <= 1.0.2 (for RAND_screen())
    have_library("crypt32")
  end

  return false unless have_header("openssl/ssl.h")

  ret = have_library("crypto", "CRYPTO_malloc") &&
    have_library("ssl", "SSL_new")
  return ret if ret

  if $mswin
    # OpenSSL >= 1.1.0: libcrypto.lib and libssl.lib.
    if have_library("libcrypto", "CRYPTO_malloc") &&
        have_library("libssl", "SSL_new")
      return true
    end

    # OpenSSL <= 1.0.2: libeay32.lib and ssleay32.lib.
    if have_library("libeay32", "CRYPTO_malloc") &&
        have_library("ssleay32", "SSL_new")
      return true
    end

    # LibreSSL: libcrypto-##.lib and libssl-##.lib, where ## is the ABI version
    # number. We have to find the version number out by scanning libpath.
    libpath = $LIBPATH.dup
    libpath |= ENV["LIB"].split(File::PATH_SEPARATOR)
    libpath.map! { |d| d.tr(File::ALT_SEPARATOR, File::SEPARATOR) }

    ret = [
      ["crypto", "CRYPTO_malloc"],
      ["ssl", "SSL_new"]
    ].all? do |base, func|
      result = false
      libs = ["lib#{base}-[0-9][0-9]", "lib#{base}-[0-9][0-9][0-9]"]
      libs = Dir.glob(libs.map{|l| libpath.map{|d| File.join(d, l + ".*")}}.flatten).map{|path| File.basename(path, ".*")}.uniq
      libs.each do |lib|
        result = have_library(lib, func)
        break if result
      end
      result
    end
    return ret if ret
  end
  return false
end

#gcc?Boolean

:stopdoc:

Returns:

  • (Boolean)


6
7
8
# File 'ext/fiddle/extconf.rb', line 6

def gcc?
  RbConfig::CONFIG["GCC"] == "yes"
end

#gemfile(install = false, options = {}, &gemfile) ⇒ Object

Note:

Every gem that is specified in this ‘Gemfile’ will be ‘require`d, as if the user had manually called `Bundler.require`. To avoid a requested gem being automatically required, add the `:require => false` option to the `gem` dependency declaration.

Allows for declaring a Gemfile inline in a ruby script, optionally installing any gems that aren’t already installed on the user’s system.

Examples:

Using an inline Gemfile


#!/usr/bin/env ruby

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'json', require: false
  gem 'nap', require: 'rest'
  gem 'cocoapods', '~> 0.34.1'
end

puts Pod::VERSION # => "0.34.4"

Parameters:

  • install (Boolean) (defaults to: false)

    whether gems that aren’t already installed on the user’s system should be installed. Defaults to ‘false`.

  • gemfile (Proc)

    a block that is evaluated as a ‘Gemfile`.

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/bundler/inline.rb', line 32

def gemfile(install = false, options = {}, &gemfile)
  require_relative "../bundler"
  Bundler.reset!

  opts = options.dup
  ui = opts.delete(:ui) { Bundler::UI::Shell.new }
  ui.level = "silent" if opts.delete(:quiet) || !install
  Bundler.ui = ui
  raise ArgumentError, "Unknown options: #{opts.keys.join(", ")}" unless opts.empty?

  Bundler.with_unbundled_env do
    Bundler.instance_variable_set(:@bundle_path, Pathname.new(Gem.dir))
    Bundler::SharedHelpers.set_env "BUNDLE_GEMFILE", "Gemfile"

    Bundler::Plugin.gemfile_install(&gemfile) if Bundler.feature_flag.plugins?
    builder = Bundler::Dsl.new
    builder.instance_eval(&gemfile)
    builder.check_primary_source_safety

    Bundler.settings.temporary(deployment: false, frozen: false) do
      definition = builder.to_definition(nil, true)
      def definition.lock(*); end
      definition.validate_runtime!

      if install || definition.missing_specs?
        Bundler.settings.temporary(inline: true, no_install: false) do
          installer = Bundler::Installer.install(Bundler.root, definition, system: true)
          installer.post_install_messages.each do |name, message|
            Bundler.ui.info "Post-install message from #{name}:\n#{message}"
          end
        end
      end

      runtime = Bundler::Runtime.new(nil, definition)
      runtime.setup.require
    end
  end

  if ENV["BUNDLE_GEMFILE"].nil?
    ENV["BUNDLE_GEMFILE"] = ""
  end
end

#generate_eventids1(ids) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'ext/ripper/tools/generate.rb', line 94

def generate_eventids1(ids)
  buf = "".dup
  buf << %Q[#include "ruby/ruby.h"\n]
  buf << %Q[#include "eventids1.h"\n]
  buf << %Q[\n]
  buf << %Q[struct ripper_parser_ids ripper_parser_ids;\n]
  buf << %Q[\n]
  buf << %Q[void\n]
  buf << %Q[ripper_init_eventids1(void)\n]
  buf << %Q[{\n]
  buf << %Q[#define set_id1(name) ripper_id_##name = rb_intern_const("on_"#name)\n]
  ids.each do |id, arity|
    buf << %Q[    set_id1(#{id});\n]
  end
  buf << %Q[}\n]
  buf << %Q[\n]
  buf << %Q[#define intern_sym(name) ID2SYM(rb_intern_const(name))\n]
  buf << %Q[\n]
  buf << %Q[void\n]
  buf << %Q[ripper_init_eventids1_table(VALUE self)\n]
  buf << %Q[{\n]
  buf << %Q[    VALUE h = rb_hash_new();\n]
  buf << %Q[    rb_define_const(self, "PARSER_EVENT_TABLE", h);\n]
  ids.each do |id, arity|
    buf << %Q[    rb_hash_aset(h, intern_sym("#{id}"), INT2FIX(#{arity}));\n]
  end
  buf << %Q[}\n]
  buf
end

#generate_eventids1_h(ids) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'ext/ripper/tools/generate.rb', line 73

def generate_eventids1_h(ids)
  buf = "".dup
  buf << %Q[#ifndef RIPPER_EVENTIDS1\n]
  buf << %Q[#define RIPPER_EVENTIDS1\n]
  buf << %Q[\n]
  buf << %Q[void ripper_init_eventids1(void);\n]
  buf << %Q[void ripper_init_eventids1_table(VALUE self);\n]
  buf << %Q[\n]
  buf << %Q[struct ripper_parser_ids {\n]
  ids.each do |id, arity|
    buf << %Q[    ID id_#{id};\n]
  end
  buf << %Q[};\n]
  buf << %Q[\n]
  ids.each do |id, arity|
    buf << %Q[#define ripper_id_#{id} ripper_parser_ids.id_#{id}\n]
  end
  buf << %Q[#endif /* RIPPER_EVENTIDS1 */\n]
  buf << %Q[\n]
end

#generate_eventids2_table(ids) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'ext/ripper/tools/generate.rb', line 124

def generate_eventids2_table(ids)
  buf = "".dup
  buf << %Q[#include "ruby/ruby.h"\n]
  buf << %Q[\n]
  buf << %Q[#define intern_sym(name) ID2SYM(rb_intern_const(name))\n]
  buf << %Q[\n]
  buf << %Q[void\n]
  buf << %Q[ripper_init_eventids2_table(VALUE self)\n]
  buf << %Q[{\n]
  buf << %Q[    VALUE h = rb_hash_new();\n]
  buf << %Q[    rb_define_const(self, "SCANNER_EVENT_TABLE", h);\n]
  ids.each do |id|
    buf << %Q[    rb_hash_aset(h, intern_sym("#{id}"), INT2FIX(1));\n]
  end
  buf << %Q[}\n]
  buf << %Q[\n]
  buf << %Q[#define RIPPER_EVENTIDS2_TABLE_SIZE #{ids.size}\n]
  buf
end

#grammar(f, out) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'ext/ripper/tools/preproc.rb', line 89

def grammar(f, out)
  while line = f.gets
    case line
    when %r</\*% *ripper(?:\[(.*?)\])?: *(.*?) *%\*/>
      out << DSL.new($2, ($1 || "").split(",")).generate << "\n"
    when %r</\*%%%\*/>
      out << "#if 0\n"
    when %r</\*%>
      out << "#endif\n"
    when %r<%\*/>
      out << "\n"
    when /\A%%/
      out << "%%\n"
      return
    else
      out << line
    end
  end
end

#helpObject

Display help message.

ruby -run -e help [COMMAND]


407
408
409
410
411
# File 'lib/un.rb', line 407

def help
  setup do |argv,|
    UN.help(argv)
  end
end

#httpdObject

Run WEBrick HTTP server.

ruby -run -e httpd -- [OPTION] [DocumentRoot]

--bind-address=ADDR         address to bind
--port=NUM                  listening port number
--max-clients=MAX           max number of simultaneous clients
--temp-dir=DIR              temporary directory
--do-not-reverse-lookup     disable reverse lookup
--request-timeout=SECOND    request timeout in seconds
--http-version=VERSION      HTTP version
--server-name=NAME          name of the server host
--server-software=NAME      name and version of the server
--ssl-certificate=CERT      The SSL certificate file for the server
--ssl-private-key=KEY       The SSL private key file for the server certificate
-v                          verbose


325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/un.rb', line 325

def httpd
  setup("", "BindAddress=ADDR", "Port=PORT", "MaxClients=NUM", "TempDir=DIR",
        "DoNotReverseLookup", "RequestTimeout=SECOND", "HTTPVersion=VERSION",
        "ServerName=NAME", "ServerSoftware=NAME",
        "SSLCertificate=CERT", "SSLPrivateKey=KEY") do
    |argv, options|
    begin
      require 'webrick'
    rescue LoadError
      abort "webrick is not found. You may need to `gem install webrick` to install webrick."
    end
    opt = options[:RequestTimeout] and options[:RequestTimeout] = opt.to_i
    [:Port, :MaxClients].each do |name|
      opt = options[name] and (options[name] = Integer(opt)) rescue nil
    end
    if cert = options[:SSLCertificate]
      key = options[:SSLPrivateKey] or
        raise "--ssl-private-key option must also be given"
      require 'webrick/https'
      options[:SSLEnable] = true
      options[:SSLCertificate] = OpenSSL::X509::Certificate.new(File.read(cert))
      options[:SSLPrivateKey] = OpenSSL::PKey.read(File.read(key))
      options[:Port] ||= 8443   # HTTPS Alternate
    end
    options[:Port] ||= 8080     # HTTP Alternate
    options[:DocumentRoot] = argv.shift || '.'
    s = nil
    options[:StartCallback] = proc {
      logger = s.logger
      logger.info("To access this server, open this URL in a browser:")
      s.listeners.each do |listener|
        if options[:SSLEnable]
          addr = listener.addr
          addr[3] = "127.0.0.1" if addr[3] == "0.0.0.0"
          addr[3] = "::1" if addr[3] == "::"
          logger.info("    https://#{Addrinfo.new(addr).inspect_sockaddr}")
        else
          logger.info("    http://#{listener.connect_address.inspect_sockaddr}")
        end
      end
    }
    s = WEBrick::HTTPServer.new(options)
    shut = proc {s.shutdown}
    siglist = %w"TERM QUIT"
    siglist.concat(%w"HUP INT") if STDIN.tty?
    siglist &= Signal.list.keys
    siglist.each do |sig|
      Signal.trap(sig, shut)
    end
    s.start
  end
end

#installObject

Copy SOURCE to DEST.

ruby -run -e install -- [OPTION] SOURCE DEST

-p          apply access/modification times of SOURCE files to
            corresponding destination files
-m          set permission mode (as in chmod), instead of 0755
-o          set owner user id, instead of the current owner
-g          set owner group id, instead of the current group
-v          verbose


199
200
201
202
203
204
205
206
207
208
209
# File 'lib/un.rb', line 199

def install
  setup("pm:o:g:") do |argv, options|
    (mode = options.delete :m) and options[:mode] = /\A\d/ =~ mode ? mode.oct : mode
    options[:preserve] = true if options.delete :p
    (owner = options.delete :o) and options[:owner] = owner
    (group = options.delete :g) and options[:group] = group
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.install argv, dest, **options
  end
end

#installerObject

A post-install hook that displays “Successfully installed some_gem-1.0 as a default gem”



10
11
12
13
# File 'lib/rubygems/install_message.rb', line 10

Gem.post_install do |installer|
  ui = Gem::DefaultUserInteraction.ui
  ui.say "Successfully installed #{installer.spec.full_name}"
end

#lnObject

Create a link to the specified TARGET with LINK_NAME.

ruby -run -e ln -- [OPTION] TARGET LINK_NAME

-s          make symbolic links instead of hard links
-f          remove existing destination files
-v          verbose


107
108
109
110
111
112
113
114
115
116
# File 'lib/un.rb', line 107

def ln
  setup("sf") do |argv, options|
    cmd = "ln"
    cmd += "_s" if options.delete :s
    options[:force] = true if options.delete :f
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.__send__ cmd, argv, dest, **options
  end
end

#mainObject



7
8
9
10
11
12
13
14
15
16
# File 'ext/ripper/extconf.rb', line 7

def main
  $objs = %w(eventids1.o eventids2.o ripper.o ripper_init.o)
  $distcleanfiles.concat %w(ripper.y ripper.c eventids1.c eventids1.h eventids2table.c ripper_init.c)
  $cleanfiles.concat %w(ripper.E ripper.output y.output .eventids2-check)
  $defs << '-DRIPPER'
  $defs << '-DRIPPER_DEBUG' if $debug
  $VPATH << '$(topdir)' << '$(top_srcdir)'
  $INCFLAGS << ' -I$(topdir) -I$(top_srcdir)'
  create_makefile 'ripper'
end

#mkdirObject

Create the DIR, if they do not already exist.

ruby -run -e mkdir -- [OPTION] DIR

-p          no error if existing, make parent directories as needed
-v          verbose


162
163
164
165
166
167
168
# File 'lib/un.rb', line 162

def mkdir
  setup("p") do |argv, options|
    cmd = "mkdir"
    cmd += "_p" if options.delete :p
    FileUtils.__send__ cmd, argv, **options
  end
end

#mkmfObject

Create makefile using mkmf.

ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]

-d ARGS     run dir_config
-h ARGS     run have_header
-l ARGS     run have_library
-f ARGS     run have_func
-v ARGS     run have_var
-t ARGS     run have_type
-m ARGS     run have_macro
-c ARGS     run have_const
--vendor    install to vendor_ruby


290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/un.rb', line 290

def mkmf
  setup("d:h:l:f:v:t:m:c:", "vendor") do |argv, options|
    require 'mkmf'
    opt = options[:d] and opt.split(/:/).each {|n| dir_config(*n.split(/,/))}
    opt = options[:h] and opt.split(/:/).each {|n| have_header(*n.split(/,/))}
    opt = options[:l] and opt.split(/:/).each {|n| have_library(*n.split(/,/))}
    opt = options[:f] and opt.split(/:/).each {|n| have_func(*n.split(/,/))}
    opt = options[:v] and opt.split(/:/).each {|n| have_var(*n.split(/,/))}
    opt = options[:t] and opt.split(/:/).each {|n| have_type(*n.split(/,/))}
    opt = options[:m] and opt.split(/:/).each {|n| have_macro(*n.split(/,/))}
    opt = options[:c] and opt.split(/:/).each {|n| have_const(*n.split(/,/))}
    $configure_args["--vendor"] = true if options[:vendor]
    create_makefile(*argv)
  end
end

#mvObject

Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.

ruby -run -e mv -- [OPTION] SOURCE DEST

-v          verbose


126
127
128
129
130
131
132
# File 'lib/un.rb', line 126

def mv
  setup do |argv, options|
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.mv argv, dest, **options
  end
end

#parse_argsObject



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'ext/extmk.rb', line 315

def parse_args()
  $mflags = []
  $makeflags = [] # for make command to build ruby, so quoted

  $optparser ||= OptionParser.new do |opts|
    opts.on('-n') {$dryrun = true}
    opts.on('--[no-]extension [EXTS]', Array) do |v|
      $extension = (v == false ? [] : v)
    end
    opts.on('--[no-]extstatic [STATIC]', Array) do |v|
      if ($extstatic = v) == false
        $extstatic = []
      elsif v
        $force_static = true if $extstatic.delete("static")
        $extstatic = nil if $extstatic.empty?
      end
    end
    opts.on('--dest-dir=DIR') do |v|
      $destdir = v
    end
    opts.on('--extout=DIR') do |v|
      $extout = (v unless v.empty?)
    end
    opts.on('--make=MAKE') do |v|
      $make = v || 'make'
    end
    opts.on('--make-flags=FLAGS', '--mflags', Shellwords) do |v|
      v.grep(/\A([-\w]+)=(.*)/) {$configure_args["--#{$1}"] = $2}
      if arg = v.first
        arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg
      end
      $makeflags.concat(v.reject {|arg2| /\AMINIRUBY=/ =~ arg2}.quote)
      $mflags.concat(v)
    end
    opts.on('--message [MESSAGE]', String) do |v|
      $message = v
    end
    opts.on('--command-output=FILE', String) do |v|
      $command_output = v
    end
    opts.on('--gnumake=yes|no', true) do |v|
      $gnumake = v
    end
    opts.on('--extflags=FLAGS') do |v|
      $extflags = v || ""
    end
  end
  begin
    $optparser.parse!(ARGV)
  rescue OptionParser::InvalidOption => e
    retry if /^--/ =~ e.args[0]
    $optparser.warn(e)
    abort $optparser.to_s
  end
  $command_output or abort "--command-output option is mandatory"

  $destdir ||= ''

  $make, *rest = Shellwords.shellwords($make)
  $mflags.unshift(*rest) unless rest.empty?

  def $mflags.set?(flag)
    grep(/\A-(?!-).*#{flag.chr}/i) { return true }
    false
  end
  def $mflags.defined?(var)
    grep(/\A#{var}=(.*)/) {return $1}
    false
  end

  if $mflags.set?(?n)
    $dryrun = true
  else
    $mflags.unshift '-n' if $dryrun
  end

  $continue = $mflags.set?(?k)
  if $extout
    $extout = '$(topdir)/'+$extout
    RbConfig::CONFIG["extout"] = CONFIG["extout"] = $extout
    $extout_prefix = $extout ? "$(extout)$(target_prefix)/" : ""
    $mflags << "extout=#$extout" << "extout_prefix=#$extout_prefix"
  end
end

#prelude(f, out) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'ext/ripper/tools/preproc.rb', line 54

def prelude(f, out)
  @exprs = {}
  lex_state_def = false
  while line = f.gets
    case line
    when /\A%%/
      out << "%%\n"
      return
    when /\A%token/, /\A%type/, /\A} <node(?>_\w+)?>/
      # types in %union which have corresponding set_yylval_* macro.
      out << line.sub(/<(?:node(?>_\w+)?|num|id)>/, '<val>')
    when /^enum lex_state_(?:bits|e) \{/
      lex_state_def = true
      out << line
    when /^\}/
      lex_state_def = false
      out << line
    else
      out << line
    end
    if lex_state_def
      case line
      when /^\s*(EXPR_\w+),\s+\/\*(.+)\*\//
        @exprs[$1.chomp("_bit")] = $2.strip
      when /^\s*(EXPR_\w+)\s+=\s+(.+)$/
        name = $1
        val = $2.chomp(",")
        @exprs[name] = "equals to " + (val.start_with?("(") ? "<tt>#{val}</tt>" : "+#{val}+")
      end
    end
  end
end

#process(f, out, path, template) ⇒ Object



48
49
50
51
52
# File 'ext/ripper/tools/preproc.rb', line 48

def process(f, out, path, template)
  prelude f, out
  grammar f, out
  usercode f, out, path, template
end

#read_ids1(path) ⇒ Object



144
145
146
# File 'ext/ripper/tools/generate.rb', line 144

def read_ids1(path)
  strip_locations(read_ids1_with_locations(path))
end

#read_ids1_with_locations(path) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'ext/ripper/tools/generate.rb', line 167

def read_ids1_with_locations(path)
  h = {}
  File.open(path) {|f|
    f.each do |line|
      next if /\A\#\s*define\s+dispatch/ =~ line
      next if /ripper_dispatch/ =~ line
      line.scan(/\bdispatch(\d)\((\w+)/) do |arity, event|
        (h[event] ||= []).push [f.lineno, arity.to_i]
      end
      if line =~ %r</\*% *ripper(?:\[(.*?)\])?: *(.*?) *%\*/>
        gen = DSL.new($2, ($1 || "").split(","))
        gen.generate
        gen.events.each do |event, arity|
          (h[event] ||= []).push [f.lineno, arity.to_i]
        end
      end
    end
  }
  h
end

#read_ids2(path) ⇒ Object



188
189
190
191
192
193
194
195
196
# File 'ext/ripper/tools/generate.rb', line 188

def read_ids2(path)
  src = File.open(path) {|f| f.read}
  ids2 = src.scan(/ID\s+ripper_id_(\w+)/).flatten.uniq.sort
  diff = src.scan(/set_id2\((\w+)\);/).flatten - ids2
  unless diff.empty?
    abort "missing scanner IDs: #{diff}"
  end
  return ids2
end

#reverse_each_name(pat) ⇒ Object



122
123
124
125
126
127
# File 'ext/socket/mkconstants.rb', line 122

def reverse_each_name(pat)
  DEFS.reverse_each {|name, default_value|
    next if pat !~ name
    yield name
  }
end

#reverse_each_name_with_prefix_optional(pat, prefix_pat) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
# File 'ext/socket/mkconstants.rb', line 209

def reverse_each_name_with_prefix_optional(pat, prefix_pat)
  reverse_each_name(pat) {|n|
    yield n, n
  }
  if prefix_pat
    reverse_each_name(pat) {|n|
      next if prefix_pat !~ n
      yield n, $'
    }
  end
end

#ripperObject

This file contains stuff stolen outright from:

rtags.rb -
ruby-lex.rb - ruby lexcal analyzer
ruby-token.rb - ruby tokens
    by Keiju ISHITSUKA (Nippon Rational Inc.)


11
# File 'lib/rdoc/parser/ruby.rb', line 11

require 'ripper'

#rmObject

Remove the FILE

ruby -run -e rm -- [OPTION] FILE

-f          ignore nonexistent files
-r          remove the contents of directories recursively
-v          verbose


144
145
146
147
148
149
150
151
# File 'lib/un.rb', line 144

def rm
  setup("fr") do |argv, options|
    cmd = "rm"
    cmd += "_r" if options.delete :r
    options[:force] = true if options.delete :f
    FileUtils.__send__ cmd, argv, **options
  end
end

#rmdirObject

Remove the DIR.

ruby -run -e rmdir -- [OPTION] DIR

-p          remove DIRECTORY and its ancestors.
-v          verbose


179
180
181
182
183
184
# File 'lib/un.rb', line 179

def rmdir
  setup("p") do |argv, options|
    options[:parents] = true if options.delete :p
    FileUtils.rmdir argv, **options
  end
end

#setup(options = "", *long_options) {|argv, opt_hash| ... } ⇒ Object

:nodoc:

Yields:

  • (argv, opt_hash)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/un.rb', line 37

def setup(options = "", *long_options)
  caller = caller_locations(1, 1)[0].label
  opt_hash = {}
  argv = []
  OptionParser.new do |o|
    options.scan(/.:?/) do |s|
      opt_name = s.delete(":").intern
      o.on("-" + s.tr(":", " ")) do |val|
        opt_hash[opt_name] = val
      end
    end
    long_options.each do |s|
      opt_name, arg_name = s.split(/(?=[\s=])/, 2)
      opt_name.delete_prefix!('--')
      s = "--#{opt_name.gsub(/([A-Z]+|[a-z])([A-Z])/, '\1-\2').downcase}#{arg_name}"
      puts "#{opt_name}=>#{s}" if $DEBUG
      opt_name = opt_name.intern
      o.on(s) do |val|
        opt_hash[opt_name] = val
      end
    end
    o.on("-v") do opt_hash[:verbose] = true end
    o.on("--help") do
      UN.help([caller])
      exit
    end
    o.order!(ARGV) do |x|
      if /[*?\[{]/ =~ x
        argv.concat(Dir[x])
      else
        argv << x
      end
    end
  end
  yield argv, opt_hash
end

#strip_locations(h) ⇒ Object



148
149
150
151
# File 'ext/ripper/tools/generate.rb', line 148

def strip_locations(h)
  h.map {|event, list| [event, list.first[1]] }\
      .sort_by {|event, arity| event.to_s }
end

#strscanObject

For RDoc::Text#to_html



6
# File 'lib/rdoc/text.rb', line 6

require 'strscan'

#system(*args) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'ext/extmk.rb', line 52

def system(*args)
  if verbose?
    if args.size == 1
      puts args
    else
      puts Shellwords.join(args)
    end
  end
  super
end

#test_recvmsg_with_msg_peek_creates_fds(headers) ⇒ Object



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'ext/socket/extconf.rb', line 246

def test_recvmsg_with_msg_peek_creates_fds(headers)
  case RUBY_PLATFORM
  when /linux/
    # Linux 2.6.38 allocate fds by recvmsg with MSG_PEEK.
    close_fds = true
  when /bsd|darwin/
    # FreeBSD 8.2.0, NetBSD 5 and MacOS X Snow Leopard doesn't
    # allocate fds by recvmsg with MSG_PEEK.
    # [ruby-dev:44189]
    # http://bugs.ruby-lang.org/issues/5075
    close_fds = false
  when /cygwin/
    # Cygwin doesn't support fd passing.
    # http://cygwin.com/ml/cygwin/2003-09/msg01808.html
    close_fds = false
  else
    close_fds = nil
  end
  if !CROSS_COMPILING
    if checking_for("recvmsg() with MSG_PEEK allocate file descriptors") {
        try_run(cpp_include(headers) + RECVMSG_WITH_MSG_PEEK_ALLOCATE_FD_TEST)
       }
      if close_fds == false
        warn "unexpected fd-passing recvmsg() with MSG_PEEK behavor on #{RUBY_PLATFORM}: fd allocation unexpected."
      elsif close_fds == nil
        puts "info: #{RUBY_PLATFORM} recvmsg() with MSG_PEEK allocates fds on fd-passing."
      end
      close_fds = true
    else
      if close_fds == true
        warn "unexpected fd-passing recvmsg() with MSG_PEEK behavor on #{RUBY_PLATFORM}: fd allocation expected."
      elsif close_fds == nil
        puts "info: #{RUBY_PLATFORM}: recvmsg() with MSG_PEEK doesn't allocates fds on fd-passing."
      end
      close_fds = false
    end
  end
  if close_fds == nil
    abort <<EOS
Fatal: cannot test fd-passing recvmsg() with MSG_PEEK behavor
because cross-compilation for #{RUBY_PLATFORM}.
If recvmsg() with MSG_PEEK allocates fds on fd passing:
--enable-close-fds-by-recvmsg-with-peek
If recvmsg() with MSG_PEEK doesn't allocate fds on fd passing:
--disable-close-fds-by-recvmsg-with-peek
EOS
  end
  close_fds
end

#touchObject

Update the access and modification times of each FILE to the current time.

ruby -run -e touch -- [OPTION] FILE

-v          verbose


235
236
237
238
239
# File 'lib/un.rb', line 235

def touch
  setup do |argv, options|
    FileUtils.touch argv, **options
  end
end

#usage(msg) ⇒ Object



67
68
69
70
71
# File 'ext/ripper/tools/generate.rb', line 67

def usage(msg)
  $stderr.puts msg
  $stderr.puts @parser.help
  exit false
end

#usercode(f, out, path, template) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'ext/ripper/tools/preproc.rb', line 109

def usercode(f, out, path, template)
  require 'erb'
  lineno = nil
  src = nil
  compiler = ERB::Compiler.new('%-')
  compiler.put_cmd = compiler.insert_cmd = "out.<<"

  if template
    File.open(template) do |f|
      out.clear
      lineno = f.lineno
      src, = compiler.compile(f.read)
      path = template
    end
  else
    lineno = f.lineno
    src, = compiler.compile(f.read)
  end

  eval(src, binding, path, lineno)
end

#verbose?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'ext/extmk.rb', line 48

def verbose?
  $mflags.defined?("V") == "1"
end

#wait_writableObject

Wait until the file becomes writable.

ruby -run -e wait_writable -- [OPTION] FILE

-n RETRY    count to retry
-w SEC      each wait time in seconds
-v          verbose


251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/un.rb', line 251

def wait_writable
  setup("n:w:v") do |argv, options|
    verbose = options[:verbose]
    n = options[:n] and n = Integer(n)
    wait = (wait = options[:w]) ? Float(wait) : 0.2
    argv.each do |file|
      begin
        File.open(file, "r+b") {}
      rescue Errno::ENOENT
        break
      rescue Errno::EACCES => e
        raise if n and (n -= 1) <= 0
        if verbose
          puts e
          STDOUT.flush
        end
        sleep wait
        retry
      end
    end
  end
end

#xmp(exps, bind = nil) ⇒ Object

A convenience method that’s only available when the you require the IRB::XMP standard library.

Creates a new XMP object, using the given expressions as the exps parameter, and optional binding as bind or uses the top-level binding. Then evaluates the given expressions using the :XMP prompt mode.

For example:

require 'irb/xmp'
ctx = binding
xmp 'foo = "bar"', ctx
#=> foo = "bar"
  #==>"bar"
ctx.eval 'foo'
#=> "bar"

See XMP.new for more information.



159
160
161
162
163
164
# File 'lib/irb/xmp.rb', line 159

def xmp(exps, bind = nil)
  bind = IRB::Frame.top(1) unless bind
  xmp = XMP.new(bind)
  xmp.puts exps
  xmp
end