summary refs log tree commit diff stats
path: root/code/runcontext.rb
blob: 1e10aa8de0273fe89bc2bdc9c4d0a34ab78aa822 (plain) (blame)
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
class RunContext
	## accessors {{{
	attr_accessor( *%w[
		all detach wait new_term
		files handlers paths
		mode
		exec
		multi
	])
	attr_reader( :flags )
	def flags=(x)
		assert x, Array, String

		if x.is_a? Array
			@flagstring = x.join('')
			@flags = x
		elsif x.is_a? String
			@flagstring = x
			@flags = x.split(//)
		end

		parse_flags
		return x
	end
	## }}}

	def initialize(files, mode=0, flags='')
		@mode = mode.to_i
		@files = files.dup
		self.flags = flags
		
		@files.reject! {|file|
			file.handler == nil or !file.exists?
		}
		@handlers = @files.map {|file| file.handler}
		@paths = @files.map {|file| file.path}
		@handler = @handlers.first

		@multi = (@files.size > 1 and @handlers.uniq.size == 1)

		@exec = Application.send(@handler, self)
	end

	def has_flag? x
		if x.is_a? Regexp
			@flagstring =~ x
		elsif x.is_a? String
			@flags.include? x
		else
			false
		end
	end

	def parse_flags
		@all = @detach = @new_term = @wait = false

		## Positive flags
		if has_flag? 'a'
			@all = true
		end
		if has_flag? /[de]/
			@detach = true
		end
		if has_flag? 't'
			@new_term = true
			@detach = true
		end
		if has_flag? 'w'
			@wait = true
		end

		## Negative flags
		if has_flag? 'A'
			@all = false
		end
		if has_flag? /[DE]/
			@detach = false
		end
		if has_flag? 'T'
			@new_term = false
		end
		if has_flag? 'W'
			@wait = false
		end
	end

	def newway() true end

	def no_mode?()
		@mode == 0
	end

	def no_flags?()
		@flagstring.empty?
	end

	def default_flags=(x)
		if @flagstring.empty?
			self.flags = x
		end
		x
	end

	## set the mode and return self.
	def with_mode(n)
		@mode = n
		self
	end

	## wrapper {{{

	## escape all files for direct use in the shell.
	## if the _multi_ attribute is true, this is a shortcut for
	##   rc.paths.map {|x| ~x}.join(' ')
	## otherwise:
	##   ~(rc.paths.first)
	def ~
		if @multi
			@paths.map {|x| ~x}.join(' ')
		else
			~@paths.first
		end
	end

	## escape one (the first) file for direct use in the shell.
	## this is a shortcut for:
	##   ~(rc.paths.first)
	def one
		~@paths.first
	end

	## shortcut for _files.size_
	def size() @files.size end

	## shortcut for _files.first.path_
	def first() @files.first end

	## shortcut for _files.first.name_
	def name() @files.first.name end

	## }}}
end