-
Notifications
You must be signed in to change notification settings - Fork 22
/
viewer.rb
134 lines (103 loc) · 2.6 KB
/
viewer.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
require "webrick"
require "launchy"
require "optparse"
module HAR
class Viewer
attr_reader :options, :har
def initialize(args)
@running = false
@options = parse(args)
if @options[:validate]
args = validate(args)
end
if args == ["-"]
progress("Reading HAR from stdin...") {
@har = Archive.from_file $stdin
}
else
progress("Merging HARs...") {
@har = Archive.by_merging args
}
end
end
def show
s = server(create_root)
launch_browser
s.join
end
private
def validate(hars)
progress("Validating archives...") {
hars = hars.map { |path| Archive.from_file(path) }
hars.each { |h| h.validate! }
hars
}
end
def create_root
progress("Creating viewer...") {
viewer = File.expand_path("../viewer", __FILE__)
tmp_dir = Dir.mktmpdir("harviewer")
at_exit { FileUtils.rm_rf tmp_dir }
FileUtils.cp_r viewer, tmp_dir
har.save_to File.join(tmp_dir, 'viewer', url_friendly(@har.uri))
tmp_dir
}
end
DEFAULT_OPTIONS = {
:port => 9292,
:validate => false
}
def parse(args)
options = DEFAULT_OPTIONS.dup
OptionParser.new do |opts|
opts.banner = "Usage: har [options] [files|-]"
opts.on "-p", "--port PORT", Integer do |int|
options[:port] = int
end
opts.on "-v", "--version" do
puts "har #{HAR::VERSION}"
exit
end
opts.on "-w", "--validate" do
options[:validate] = true
end
end.parse!(args)
options
end
def url
"http://localhost:#{port}/viewer/index.html?path=#{url_friendly @har.uri}"
end
def port
@options[:port]
end
def url_friendly(str)
str.gsub(/\W/, '_').gsub("_har", ".har")
end
def start_hook
lambda { @running = true }
end
def server(root)
Thread.new do
puts "Starting server..."
puts "Type ^C to exit\n\n"
server = WEBrick::HTTPServer.new(:Port => port,
:DocumentRoot => root,
:StartCallback => start_hook)
[:INT, :TERM].each do |signal|
trap(signal) { server.shutdown }
end
server.start
end
end
def launch_browser
sleep 0.1 until @running
Launchy.open url
end
def progress(msg, &blk)
print msg
res = yield
puts "done."
res
end
end # Viewer
end # HAR