summaryrefslogtreecommitdiff
path: root/lib/shell.rb
blob: 3d8dda044587383c76f379fdcf0e990859ec77bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
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
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
314
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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
#
#   shell.rb - 
#   	$Release Version: 0.1 $
#   	$Revision: 1.1 $
#   	$Date: 1998/03/29 17:10:09 $
#   	by Keiju ISHITSUKA(Nippon Rational Inc.)
#
# --
#
#   
#

require "e2mmap"
require "ftools"

class Shell
  @RCS_ID='-$Id: shell.rb,v 1.1 1998/03/29 17:10:09 keiju Exp $-'

  module Error
    extend Exception2MessageMapper
    def_exception :DirStackEmpty, "Directory stack empty."
    def_exception :CanNotDefine, "Can't define method(%s, %s)."
    def_exception :CanNotMethodApply, "This method(%s) can't apply this type(%s)."
    def_exception :CommandNotFound, "Command not found(%s)."
  end
  include Error

  class << Shell
    attr :cascade, TRUE
    attr :debug, TRUE
    attr :verbose, TRUE

    alias cascade? cascade
    alias debug? debug
    alias verbose? verbose
  end

  def Shell.cd(path)
    sh = new
    sh.cd path
    sh
  end

  def Shell.default_system_path
    if @default_system_path
      @default_system_path
    else
      ENV["PATH"].split(":")
    end
  end

  def Shell.default_system_path=(path)
    @default_system_path = path
  end

  def Shell.default_record_separator
    if @default_record_separator
      @default_record_separator
    else
      $/
    end
  end

  def Shell.default_record_separator=(rs)
    @default_record_separator = rs
  end

  @cascade = TRUE
  @debug = FALSE
  @verbose = TRUE

  def initialize
    @cwd = Dir.pwd
    @dir_stack = []
    @umask = nil

    @system_commands = {}

    @system_path = Shell.default_system_path
    @record_separator = Shell.default_record_separator

    @verbose = Shell.verbose
  end

  attr :system_path
  
  def system_path=(path)
    @system_path = path
    @system_commands = {}
  end

  def rehash
    @system_commands = {}
  end

  attr :record_separator, TRUE

  attr :umask, TRUE
  attr :verbose, TRUE

  alias verbose? verbose

  def expand_path(path)
    if /^\// =~ path
      File.expand_path(path)
    else
      File.expand_path(File.join(@cwd, path))
    end
  end

  def effect_umask
    if @umask
      Thread.critical = TRUE
      save = File.umask
      begin
	yield
      ensure
	File.umask save
	Thread.critical = FALSE
      end
    else
      yield
    end
  end

  def [](pattern)
    Thread.critical=TRUE
    back = Dir.pwd
    begin
      Dir.chdir @cwd
      Dir[pattern]
    ensure
      Dir.chdir back
      Thread.critical = FALSE
    end
  end
  alias glob []

  def chdir(path = nil)
    path = "~" unless path
    @cwd = expand_path(path)
    @system_commands.clear
  end
  alias cd chdir

  def pushdir(path = nil)
    if iterator?
      pushdir(path)
      begin
	yield
      ensure
	popdir
      end
    elsif path
      @dir_stack.push @cwd
      @cwd = expand_path(path)
    else
      if pop = @dir_stack.pop
	@dir_stack.push @cwd
	chdir pop
      else
	Shell.fail DirStackEmpty
      end
    end
  end
  alias pushd pushdir

  def popdir
    if pop = @dir_stack.pop
      @cwd = pop
    else
      Shell.fail DirStackEmpty
    end
  end
  alias popd popdir

  attr :cwd
  alias dir cwd
  alias getwd cwd
  alias pwd cwd
  
  def foreach(path = nil, *rs)
    path = "." unless path
    path = expand_path(path)

    if File.directory?(path)
      Dir.foreach(path){|fn| yield fn}
    else
      IO.foreach(path, *rs){|l| yield l}
    end
  end

  def mkdir(path)
    Dir.mkdir(expand_path(path))
  end
  
  #
  # `mode' is effective iff `path' is specifying a file.
  #
  def open(path, mode)
    path = expand_path(path)
    if File.directory?(path)
      Dir.open(path)
    else
      effect_umask do
	File.open(path, mode)
      end
    end
  end
#  public :open

  def rmdir(path)
    Dir.rmdir(expand_path(path))
  end

  def unlink(path)
    path = expand_path(path)
    if File.directory?(path)
      Dir.unlink(path)
    else
      IO.unlink(path)
    end
  end

  #
  # command extension
  #   command_specs = [[command_name, [arguments,...]]]
  # FILENAME* -> expand_path(filename*)
  # \*FILENAME* -> filename*.collect{|fn| expand_path(fn)}.join(", ")
  #
  def Shell.def_commands(delegation_class, command_specs)
    for meth, args in command_specs
      arg_str = args.collect{|arg| arg.downcase}.join(", ")
      call_arg_str = args.collect{
	|arg|
	case arg
	when /^(FILENAME.*)$/
	  format("expand_path(%s)", $1.downcase)
	when /^(\*FILENAME.*)$/
	  # \*FILENAME* -> filenames.collect{|fn| expand_path(fn)}.join(", ")
	  $1.downcase + '.collect{|fn| expand_path(fn)}'
	else
	  arg
	end
      }.join(", ")
      d = %Q[
        def #{meth}(#{arg_str})
	  #{delegation_class}.#{meth}(#{call_arg_str})
        end
      ]
      if debug?
	print d
      elsif verbose?
	print "Define #{meth}(#{arg_str})\n"
      end
      eval d
    end
  end

  #
  # File methods
  #	open/foreach/unlink are defined elsewhere.
  #
  normal_delegation_file_methods = [
    ["atime", ["FILENAME"]],
    ["basename", ["fn", "*opts"]],
    ["chmod", ["mode", "*FILENAMES"]], 
    ["chown", ["owner", "group", "FILENAME"]],
    ["ctime", ["group", "*FILENAMES"]],
    ["delete", ["*FILENAMES"]],
    ["dirname", ["FILENAME"]],
    ["ftype", ["FILENAME"]],
    ["join", ["*items"]],
    ["link", ["FILENAME_O", "FILENAME_N"]],
    ["lstat", ["FILENAME"]],
    ["mtime", ["FILENAME"]],
    ["readlink", ["FILENAME"]],
    ["rename", ["FILENAME_FROM", "FILENAME_TO"]],
    ["size", ["FILENAME"]],
    ["split", ["pathname"]],
    ["stat", ["FILENAME"]],
    ["symlink", ["FILENAME_O", "FILENAME_N"]],
    ["truncate", ["FILENAME", "length"]],
    ["utime", ["atime", "mtime", "*FILENAMES"]]]
  def_commands(File,
	       normal_delegation_file_methods)
  alias rm delete

  # FileTest method
  def_commands(FileTest, 
	       FileTest.singleton_methods.collect{|m| [m, ["FILENAME"]]})

  # ftools methods
  normal_delegation_ftools_methods = [
    ["syscopy", ["FILENAME_FROM", "FILENAME_TO"]],
    ["copy", ["FILENAME_FROM", "FILENAME_TO"]],
    ["move", ["FILENAME_FROM", "FILENAME_TO"]],
    ["compare", ["FILENAME_FROM", "FILENAME_TO"]],
    ["safe_unlink", ["*FILENAMES"]],
    ["makedirs", ["*FILENAMES"]],
#    ["chmod", ["mode", "*FILENAMES"]],
    ["install", ["FILENAME_FROM", "FILENAME_TO", "mode"]],
  ]
  def_commands(File,
	       normal_delegation_ftools_methods)
  alias cmp compare
  alias mv move
  alias cp copy
  alias rm_f safe_unlink
  alias mkpath makedirs

  # test function
  alias top_level_test test
  def test(command, file1, file2 = nil)
    if file2
      top_level_test command, expand_path(file1), expand_path(file2)
    else
      top_level_test command, expand_path(file1)
    end
  end

  # shell functions
  def echo(*strings)
    Echo.new(self, *strings)
  end

  def cat(*filenames)
    Cat.new(self, *filenames)
  end

  def tee(file)
    Tee.new(self, file)
  end

#   def sort(*filenames)
#     Sort.new(self, *filenames)
#   end

  def system(command, *opts)
    System.new(self, find_system_command(command), *opts)
  end

  #
  # search for command, raise exception if not found.
  #
  def find_system_command(command)
    return command if /^\// =~ command
    case path = @system_commands[command]
    when String
      if sh.exists?(path)
	return path
      else
	Shell.fail CommandNotFound, command
      end
    when FALSE
      Shell.fail CommandNotFound, command
    end

    for p in @system_path
      path = join(p, command)
      if FileTest.exists?(path)
	@system_commands[command] = path
	return path
      end
    end
    @system_commands[command] = FALSE
    Shell.fail CommandNotFound, command
  end

  #
  # define command as singleton method.
  #
  def def_system_command(command, path = command)
    d = "
      def self.#{command}(*opts)
	System.new(self, find_system_command('#{path}'), *opts)
      end
    "
    begin
      eval d
    rescue
      print "Can't define self.#{command} path: #{path}\n" if debug? or verbose?
      Shell.fail CanNotDefine, comamnd, path
    end
    if debug?
      print d
    elsif verbose?
      print "Define self.#{command} path: #{path}\n"
    end
  end

  #
  # define command as Shell method.
  #
  def Shell.def_system_command(command, path = command)
    d = "
      def #{command}(*opts)
	System.new(self, '#{path}', *opts)
      end
    "
    begin
      eval d
    rescue
      print "Can't define #{command} path: #{path}\n" if debug? or verbose?
      Shell.fail CanNotDefine, comamnd, path
    end
    if debug?
      print d
    elsif verbose?
      print "Define #{command} path: #{path}\n"
    end
  end

  #
  # defines commands on default_path.  if the method is already defined,
  # do nothing.  as default, methods are prefixed by "sys_".
  # invalid characters as method name are converted into "_".
  #
  def Shell.install_system_command(pre = "sys_")
    defined_meth = {}
    for m in Shell.methods
      defined_meth[m] = TRUE
    end
    sh = Shell.new
    for path in Shell.default_path
      next unless sh.directory? path
      sh.cd path
      sh.foreach do
	|cn|
	if !defined_meth[pre + cn] && sh.file?(cn) && sh.executable?(cn)
	  command = (pre + cn).gsub(/\W/, "_").sub(/^([0-9])/, '_\1')
	  begin
	    def_system_command(command, sh.expand_path(cn))
	  rescue
            printf("Warning: Can't define %s path: %s\n",
		   comamnd,
		   cn) unless debug? or verbose?
	  end
	  defined_meth[command] = command
	end
      end
    end
  end

  #
  # Filter
  # required method:
  #    each()
  class Filter
    include Enumerable
    include Error

    def initialize(sh)
      @shell = sh
    end

    def input=(filter)
      @input = filter
    end

    def each(rs = nil)
      rs = @shell.record_separator unless rs
      if @input
	@input.each(rs){|l| yield l}
      end
    end

    def < (src)
      case src
      when String
	cat = Cat.new(@shell, src)
	cat | self
      when IO
	@input = src
	self
      else
	Filter.fail CanNotMethodApply, "<", to.type
      end
    end

    def > (to)
      case to
      when String
	dst = @shell.open(to, "w")
	begin
	  each(){|l| dst << l}
	ensure
	  dst.close
	end
      when IO
	each(){|l| to << l}
      else
	Filter.fail CanNotMethodApply, ">", to.type
      end
      self
    end

    def >> (to)
      case to
      when String
	dst = @shell.open(to, "a")
	begin
	  each(){|l| dst << l}
	ensure
	  dst.close
	end
      when IO
	each(){|l| to << l}
      else
	Filter.fail CanNotMethodApply, ">>", to.type
      end
      self
    end

    def | (filter)
      filter.input = self
      filter
    end

    def method_missing(method, *args)
      if Shell.cascade? and @shell.respond_to?(method)
	self | @shell.send(method, *args)
      else
	super
      end
    end

    def to_a
      ary = []
      each(){|l| ary.push l}
      ary
    end

    def to_s
      str = ""
      each(){|l| str.concat l}
      str
    end
  end

  class Echo < Filter
    def initialize(sh, *strings)
      super sh
      @strings = strings
    end
    
    def each(rs = nil)
      rs =  @shell.record_separator unless rs
      for str  in @strings
	yield str + rs
      end
    end
  end

  class Cat < Filter
    def initialize(sh, *filenames)
      super sh
      @cat_files = filenames
    end

    def each(rs = nil)
      if @cat_files.empty?
	super
      else
	for src in @cat_files
	  @shell.foreach(src, rs){|l| yield l}
	end
      end
    end
  end

#   class Sort < Cat
#     def initialize(sh, *filenames)
#       super
#     end
#
#     def each(rs = nil)
#       ary = []
#       super{|l|	ary.push l}
#       for l in ary.sort!
# 	yield l
#       end
#     end
#   end

  class Tee < Filter
    def initialize(sh, filename)
      super sh
      @to_filename = filename
    end

    def each(rs = nil)
      to = @shell.open(@to_filename, "w")
      begin
	super{|l| to << l; yield l}
      ensure
	to.close
      end
    end
  end

  class System < Filter
    def initialize(sh, command, *opts)
      require "socket"
      
      super(sh)
#      @sock_me, @sock_peer = Socket.pair(Socket::AF_UNIX, Socket::SOCK_STREAM, 0)
      @pipe_me_in, @pipe_peer_out = pipe
      @pipe_peer_in, @pipe_me_out = pipe
      begin
	pid = fork {
#	  @sock_me.close
	  @pipe_me_in.close
	  @pipe_me_out.close
#	  STDIN.reopen(@sock_peer)
#	  STDOUT.reopen(@sock_peer)
	  STDIN.reopen(@pipe_peer_in)
	  STDOUT.reopen(@pipe_peer_out)
	  fork {
	    exec(command + " " + opts.join(" "))
	  }
	  exit
	}
#	print pid; $stdout.flush
      ensure
#       sock_peer.close
        @pipe_peer_in.close
	@pipe_peer_out.close
	begin
	  Process.waitpid(pid, nil)
	rescue Errno::ECHILD
	end
      end
    end

    def each(rs = nil)
      rs = @shell.record_separator unless rs
      begin
	th_o = Thread.start{
	  super{|l| @pipe_me_out.print l}
#	  @sock_me.shutdown(0)
	  @pipe_me_out.close
	}
	begin
	  @pipe_me_in.each(rs) do
	    |l|
#	    print l
	    yield l
	  end
	ensure
	  th_o.exit
	end
      ensure
#	@sock_peer.close unless @sock_peer.closed?
#	@sock_me.close
	@pipe_me_in.close
      end
    end
  end
end