Class: NOMS::Command::Application

Inherits:
Base
  • Object
show all
Defined in:
lib/noms/command/application.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#default_logger

Constructor Details

#initialize(origin, argv, attrs = {}) ⇒ Application

Returns a new instance of Application.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/noms/command/application.rb', line 32

def initialize(origin, argv, attrs={})
    @document = nil
    @origin = NOMS::Command::URInion.parse(origin)
    if @origin.scheme == 'file' and @origin.host.nil?
        @origin.host = 'localhost'
    end
    @argv = argv
    @options = { }
    @type = nil

    @log = attrs[:logger] || default_logger

    @window = NOMS::Command::Window.new($0, @origin, :logger => @log)

    @log.debug "Application #{argv[0]} has origin: #{origin}"
    @useragent = NOMS::Command::UserAgent.new(@origin, :logger => @log,
                                              :specified_identities => (attrs[:specified_identities] || []))
end

Instance Attribute Details

#bodyObject

Should user-agent actually be here?



28
29
30
# File 'lib/noms/command/application.rb', line 28

def body
  @body
end

#documentObject

Should user-agent actually be here?



28
29
30
# File 'lib/noms/command/application.rb', line 28

def document
  @document
end

#optionsObject

Should user-agent actually be here?



28
29
30
# File 'lib/noms/command/application.rb', line 28

def options
  @options
end

#typeObject

Should user-agent actually be here?



28
29
30
# File 'lib/noms/command/application.rb', line 28

def type
  @type
end

#useragentObject

Should user-agent actually be here?



28
29
30
# File 'lib/noms/command/application.rb', line 28

def useragent
  @useragent
end

#windowObject

Should user-agent actually be here?



28
29
30
# File 'lib/noms/command/application.rb', line 28

def window
  @window
end

Instance Method Details

#_sanitize(thing) ⇒ Object

Get rid of V8 stuff



189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/noms/command/application.rb', line 189

def _sanitize(thing)
    if thing.kind_of? V8::Array or thing.respond_to? :to_ary
        thing.map do |item|
            _sanitize item
        end
    elsif thing.respond_to? :keys
        Hash[
             thing.keys.map do |key|
                 [key, _sanitize(thing[key])]
             end]
    else
        thing
    end
end

#abbrev(s, limit = 10) ⇒ Object



161
162
163
164
165
166
167
# File 'lib/noms/command/application.rb', line 161

def abbrev(s, limit=10)
    if s.length > (limit - 3)
        s[0 .. (limit - 3)] + '...'
    else
        s
    end
end

#displayObject



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/noms/command/application.rb', line 169

def display
    case @type
    when 'noms-v2'
        NOMS::Command::Formatter.new(_sanitize(@document.body)).render
    when 'noms-raw'
        @body.to_yaml
    when /^text(\/|$)/
        @body
    else
        if @window.isatty
            # Should this be here?
            @log.warn "Unknown data of type '#{@type}' not sent to terminal"
            []
        else
            @body
        end
    end
end

#exitcodeObject



101
102
103
# File 'lib/noms/command/application.rb', line 101

def exitcode
    @document ? @document.exitcode : 0
end

#fetch!Object



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
# File 'lib/noms/command/application.rb', line 51

def fetch!
    # Get content and build object, set @type
    case @origin.scheme
    when 'file'
        @type = (MIME::Types.of(@origin.path).first || MIME::Types['text/plain'].first).content_type
        @body = File.open(@origin.path, 'r') { |fh| fh.read }
    when 'data'
        @type = @origin.mime_type
        raise NOMS::Command::Error.new("data URLs must contain application/json") unless @type == 'application/json'
        @body = @origin.data
    when /^http/
        response, landing_url = @useragent.get(@origin)
        new_url = landing_url
        @origin = new_url
        @useragent.origin = new_url
        @window.origin = new_url
        @log.debug "Setting origin to: #{@origin}"
        if response.ok?
            # Unlike typical ReST data sources, this
            # should very rarely fail unless there is
            # a legitimate communication issue.
            @type = response.contenttype || 'text/plain'
            @body = response.content
        else
            raise NOMS::Command::Error.new("Failed to request #{@origin}: #{response.status} #{response.reason}")
        end
    else
        raise NOMS::Command::Error.new("noms command #{@argv[0].inspect} not found: not a URL or bookmark")
    end

    case @type
    when /^(application|text)\/(x-|)json/
        begin
            @body = JSON.parse(@body)
        rescue JSON::ParserError => e
            raise NOMS::Command::Error.new("JSON error in #{@origin}: #{e.message}")
        end
        if @body.respond_to? :has_key? and @body.has_key? '$doctype'
            @type = @body['$doctype']
            @log.debug "Treating as #{@type} document"
            @document = NOMS::Command::Document.new @body
            @document.argv = @argv
            @document.exitcode = 0
        else
            @log.debug "Treating as raw object (no '$doctype')"
            @type = 'noms-raw'
        end
    end
end

#render!Object



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
# File 'lib/noms/command/application.rb', line 105

def render!
    if @document and @document.script
        # Crashes when using @window as global object
        @v8 = V8::Context.new
        # Set up same-origin context and stuff--need
        # Ruby objects to do XHR and limit local I/O
        @window.document = @document
        @v8[:window] = @window
        @v8[:document] = @document
        @v8.eval 'var alert = function (s) { window.alert(s); };'
        @v8.eval 'var prompt = function (s, echo) { window.prompt(s, echo); };'
        @v8.eval 'var location = window.location;'
        @v8.eval 'var console = window.console;'
        NOMS::Command::XMLHttpRequest.origin = @origin
        NOMS::Command::XMLHttpRequest.useragent = @useragent
        @v8[:XMLHttpRequest] = NOMS::Command::XMLHttpRequest
        script_index = 0
        @document.script.each do |script|
            if script.respond_to? :has_key? and script.has_key? '$source'
                # Parse relative URL and load
                response, landing_url = @useragent.get(script['$source'])
                # Don't need landing_url
                script_name = File.basename(@useragent.absolute_url(script['$source']).path)
                script_ref = "#{script_index},#{script_name}"
                if response.ok?
                    case response.contenttype
                    when /^(application|text)\/(x-|)javascript/
                        begin
                            @v8.eval response.content
                        rescue StandardError => e
                            @log.warn "Javascript[#{script_ref}] error: #{e.message}"
                            @log.debug e.backtrace.join("\n")
                        end
                    else
                        @log.warn "Unsupported script type '#{response.contenttype.inspect}' " +
                            "for script from #{script['$source'].inspect}"
                    end
                else
                    @log.warn "Couldn't load script from #{script['$source'].inspect}: #{response.status} #{response.reason}"
                    @log.debug "Body of unsuccessful request: #{response.body}"
                end
            else
                # It's javascript text
                script_ref = "#{script_index},\"#{abbrev(script)}\""
                begin
                    @v8.eval script
                rescue StandardError => e
                    @log.warn "Javascript[#{script_ref}] error: #{e.message}"
                    @log.debug e.backtrace.join("\n")
                end
            end
            script_index += 1
        end
    end
end