/
util.rb
256 lines (242 loc) · 7.4 KB
/
util.rb
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
# oaf - Care-free web app prototyping using files and scripts
# Copyright 2013 Ryan Uber <ru@ryanuber.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'open3'
require 'json'
module Oaf
module Util
extend Oaf
extend self
# Determines if a line of output looks anything like an HTTP header
# declaration.
#
# == Parameters:
# line::
# A line of text to examine
#
# == Returns:
# A boolean, true if it can be read as a header string, else false.
#
def is_http_header? line
line.split(':').length == 2
end
# Retrieves a hash in the form `name` => `value` from a string that
# describes an HTTP response header.
#
# == Parameters:
# line::
# A line of text to parse
#
# == Returns
# A hash in the form `name` => `value`, or `nil`
#
def get_http_header line
return nil if not is_http_header? line
parts = line.split(':')
[parts[0].strip, parts[1].strip]
end
# Retrieves the numeric value from a line of text as an HTTP status code.
#
# == Parameters:
# line::
# A line of text to parse
#
# == Returns:
# An integer if valid, else `nil`.
#
def get_http_status line
is_http_status?(line) ? line.to_i : nil
end
# Determines if an HTTP status code is valid per RFC2616
#
# == Parameters:
# code::
# A number to validate
#
# == Returns
# A boolean, true if valid, else false.
#
def is_http_status? code
(200..206).to_a.concat((300..307).to_a).concat((400..417).to_a) \
.concat((500..505).to_a).include? code.to_i
end
# Format data in preparation for passing it to an executable program as
# an argument on the command line.
#
# == Parameters:
# data::
# Some data to prepare
# flatten::
# A boolean flag determining whether or not to flatten the data
# structure before returning it. Default is true.
#
# == Returns:
# A JSON-encoded string
#
def arg_format data, flatten=true
data = Oaf::Util.arg_flatten data if flatten
if data.kind_of? Hash or data.kind_of? Array
result = data
else
result = [data]
end
JSON.dump result
end
# Flatten arguments in preparation for passing them around. This is mainly
# for ease of use so that we don't go indexing into hashes and arrays here
# and there for no reason.
#
# == Parameters:
# data::
# The data to flatten
#
# == Returns:
# A flattened data structure similar to the input.
#
def arg_flatten data
result = data
if data.kind_of? Hash
result = Hash.new
data.each do |key, val|
val = val.join if val.kind_of? Array and val.length == 1
result[key] = val
end
elsif data.kind_of? Array
result = Array.new
data.each do |item|
item = item.join if item.kind_of? Array and item.length == 1
result << item
end
end
result
end
# Given an array of text lines, iterate over each of them and determine if
# they may be interpreted as headers or status. If they can, add them to
# the result.
#
# == Parameters:
# text::
# Plain text data to examine
#
# == Returns:
# A 3-item structure containing headers, status, and the number of lines
# which the complete metadata (including the "---" delimiter) occupies.
#
def parse_http_meta text
headers = {}
status = 200
size = 0
if text.to_s != ''
parts = text.split /^---$/
if parts.length > 1
meta = parts.last.split "\n"
for part in meta
if Oaf::Util.is_http_header? part
header, value = Oaf::Util.get_http_header part
headers.merge! header => value
elsif Oaf::Util.is_http_status? part
status = Oaf::Util.get_http_status part
else
next
end
size += size == 0 ? 2 : 1 # compensate for delimiter
end
end
end
[headers, status, size]
end
# Return a default response string indicating that nothing could be
# done and no response files were found.
#
# == Returns:
# A string with response output for parsing.
#
def get_default_response
"oaf: Not Found\n---\n404"
end
# Returns the path to the file to use for the request. If the provided
# file path does not exist, this method will search for a file within
# the same directory matching the default convention "_*_".
#
# == Parameters:
# root::
# The root path to search within.
# uri::
# The URI of the request
# method::
# The HTTP method of the request
#
# == Returns:
# The path to a file to use, or `nil` if none is found.
#
def get_request_file root, uri, method
file = File.join root, "#{uri}.#{method}"
if not File.exist? file
Dir.glob(File.join(File.dirname(file), "_*_.#{method}")).each do |f|
file = f
break
end
end
File.exist?(file) ? file : nil
end
# Run a command with stdout and stderr buffered. This suppresses error
# messages from the server process and enables us to return them in the
# HTTP response instead.
#
# == Parameters:
# command::
# The command to execute against the server
#
# == Returns:
# A string of stderr concatenated to stdout.
#
def run_buffered command
stdin, stdout, stderr = Open3.popen3 "#{command} 2>&1"
stdout.read
end
# Executes a file, or reads its contents if it is not executable, passing
# it the request headers and body as arguments, and returns the result.
#
# == Parameters:
# file::
# The path to the file to use for output
# headers::
# The HTTP request headers to pass
# body::
# The HTTP request body to pass
# query::
# The HTTP query parameters to pass
#
# == Returns:
# The result from the file, or a default result if the file is not found.
#
def get_output file, headers=nil, body=nil, query=nil
if file.nil?
out = Oaf::Util.get_default_response
elsif File.executable? file
out = Oaf::Util.run_buffered "#{file} '#{headers}' '#{query}' '#{body}'"
else
out = File.open(file).read
end
out
end
end
end