Class: PluginTool::Plugin

Inherits:
Object
  • Object
show all
Defined in:
lib/plugin.rb

Constant Summary collapse

DEFAULT_PLUGIN_LOAD_PRIORITY =
9999999
@@pending_apply =

[]
@@pending_apply_kinds =
{}
@@apply_with_turbo =
false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir, options) ⇒ Plugin

Returns a new instance of Plugin.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/plugin.rb', line 13

def initialize(dir, options)
  @plugin_dir = dir
  @options = options
  @@apply_with_turbo = true if options.turbo
  # Check to see if the plugin is valid
  unless File.file?("#{@plugin_dir}/plugin.json")
    end_on_error "Plugin #{@plugin_dir} does not exist (no plugin.json file)"
  end
  pj = File.open("#{@plugin_dir}/plugin.json") { |f| JSON.parse(f.read) }
  @name = pj["pluginName"]
  end_on_error "#{@plugin_dir}/plugin.json: invalid pluginName" unless @name.kind_of?(String)
  @depend = pj["depend"] || []
  end_on_error "#{@plugin_dir}/plugin.json: invalid pluginName" unless @depend.kind_of?(Array)
end

Instance Attribute Details

#dependObject

Returns the value of attribute depend.



29
30
31
# File 'lib/plugin.rb', line 29

def depend
  @depend
end

#loaded_plugin_idObject

Returns the value of attribute loaded_plugin_id.



30
31
32
# File 'lib/plugin.rb', line 30

def loaded_plugin_id
  @loaded_plugin_id
end

#nameObject

Returns the value of attribute name.



27
28
29
# File 'lib/plugin.rb', line 27

def name
  @name
end

#plugin_dirObject

Returns the value of attribute plugin_dir.



28
29
30
# File 'lib/plugin.rb', line 28

def plugin_dir
  @plugin_dir
end

Class Method Details

.do_applyObject




244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/plugin.rb', line 244

def self.do_apply
  return if @@pending_apply.empty?
  puts "Applying changes on server: #{@@pending_apply.map { |p| p.name } .join(', ')}"
  params = {
    :plugins => @@pending_apply.map { |p| p.loaded_plugin_id }.join(' ')
  }
  if @@apply_with_turbo
    params[:turbo] = '1'
    if @@pending_apply_kinds == {:static=>true}
      params[:static_only] = '1'
    elsif @@pending_apply_kinds == {:template=>true}
      params[:template_change] = '1'
    end
  end
  r = PluginTool.post_with_json_response("/api/development-plugin-loader/apply", params)
  if r["result"] == 'success'
    @@pending_apply = []
    @@pending_apply_kinds = {}
  else
    puts "\n\nDidn't apply changes on server\n\n"
    PluginTool.beep
  end
end

Instance Method Details

#command(cmd, errors) ⇒ Object




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
# File 'lib/plugin.rb', line 118

def command(cmd, errors)
  case cmd
  when 'license-key'
    application_id = @options.args.first
    if application_id == nil || application_id !~ /\A\d+\z/
      end_on_error "Numeric application ID must be specified"
    end
    generate_license_key(application_id)

  when 'pack'
    PluginTool.pack_plugin(self, @options.output, @options.restrict_to_app_id, errors)

  when 'reset-db'
    puts "Resetting database on server for #{@name}..."
    reset_result = PluginTool.post_with_json_response("/api/development-plugin-loader/resetdb/#{@loaded_plugin_id}")
    end_on_error "Couldn't remove old database tables" unless reset_result["result"] == 'success'
    apply_result = PluginTool.post_with_json_response("/api/development-plugin-loader/apply", :plugins => @loaded_plugin_id)
    end_on_error "Couldn't apply changes" unless apply_result["result"] == 'success'
    puts "Done."

  when 'uninstall'
    puts "Uninstalling plugin #{@name} from server..."
    reset_result = PluginTool.post_with_json_response("/api/development-plugin-loader/uninstall/#{@loaded_plugin_id}")
    end_on_error "Couldn't uninstall plugin" unless reset_result["result"] == 'success'
    puts "Done."

  when 'test'
    puts "Running tests..."
    params = {}
    params["test"] = @options.args.first unless @options.args.empty?
    test_result = PluginTool.post_with_json_response("/api/development-plugin-loader/run-tests/#{@loaded_plugin_id}", params)
    end_on_error "Couldn't run tests" unless test_result["result"] == 'success'
    puts
    puts test_result["output"] || ''
    puts test_result["summary"] || "(unknown results)"

  when 'develop'
    # do nothing here

  else
    end_on_error "Unknown command '#{cmd}'"

  end
end

#default_locale_idObject



32
33
34
35
# File 'lib/plugin.rb', line 32

def default_locale_id
  # TODO: Other default locales
  'en'
end

#develop_scan_and_upload(first_run) ⇒ Object



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
# File 'lib/plugin.rb', line 168

def develop_scan_and_upload(first_run)
  should_apply = first_run
  next_manifest = PluginTool.generate_manifest(@plugin_dir)
  if !(next_manifest.has_key?("plugin.json"))
    # If the plugin.json file is deleted, just uninstall the plugin from the server
    command('uninstall')
    @is_uninstalled = true
    return
  elsif @is_uninstalled
    should_apply = true
  end
  changes = PluginTool.determine_manifest_changes(@current_manifest, next_manifest)
  upload_failed = false
  changes.each do |filename, action|
    filename =~ /\A(.*?\/)?([^\/]+)\z/
    params = {:filename => $2}
    params[:directory] = $1.gsub(/\/\z/,'') if $1
    if action == :delete
      puts "  #{@name}: Deleting #{filename}"
      PluginTool.post_with_json_response("/api/development-plugin-loader/delete-file/#{@loaded_plugin_id}", params)
    else
      puts "  #{@name}: Uploading #{filename}"
      data = File.open("#{@plugin_dir}/#{filename}", "rb") { |f| f.read }
      hash = action
      # Minimise file before uploading?
      if @options.minimiser != nil && filename =~ /\A(static|template)\//
        # Is this file explicitly excluded from minimisation?
        unless exclude_files_from_minimisation.include?(filename)
          size_before = data.length
          data = @options.minimiser.process(data, filename)
          size_after = data.length
          hash = Digest::SHA256.hexdigest(data)
          puts "        minimisation: #{size_before} -> #{size_after} (#{(size_after * 100) / size_before}%)"
        else
          puts "        minimisation: skipped by developer.json, unmodified file uploaded"
        end
      end
      r = PluginTool.post_with_json_response("/api/development-plugin-loader/put-file/#{@loaded_plugin_id}", params, {:file => [filename, data]})
      if r["result"] == 'success'
        # If the file was uploaded successfully, but the hash didn't match, abort now
        end_on_error "#{@name}: Disagreed with server about uploaded file hash: local=#{hash}, remote=#{r["hash"]}" unless hash == r["hash"]
      else
        # Otherwise mark as a failed upload to stop an apply operation which will fail
        upload_failed = true
      end
      PluginTool.syntax_check(self, filename) if filename =~ SYNTAX_CHECK_REGEXP
      if filename == 'requirements.schema'
        # Check all JS files if schema requirements changes, as removing an 'as' statement
        # could break JS files.
        ((File.open("#{@plugin_dir}/plugin.json") { |f| JSON.parse(f.read) } ['load']) || []).each do |js|
          PluginTool.syntax_check(self, js)
        end
      end
    end
    # Mark what kinds of files are being applied
    apply_kind = if filename =~ /\Astatic\//
      :static
    elsif filename =~ /\Atemplate\//
      :template
    else
      :other
    end
    @@pending_apply_kinds[apply_kind] = true
  end
  if upload_failed
    puts "\n#{@name}: Not applying changes due to failure\n\n"
  else
    if !(changes.empty?) || should_apply
      @@pending_apply.push(self) unless @@pending_apply.include?(self)
    end
  end
  @current_manifest = next_manifest
end

#develop_setupObject




165
166
# File 'lib/plugin.rb', line 165

def develop_setup
end

#developer_jsonObject




83
84
85
86
87
88
89
90
91
92
# File 'lib/plugin.rb', line 83

def developer_json
  @developer_json ||= begin
    developer_json_pathname = "#{@plugin_dir}/developer.json"
    if File.exist? developer_json_pathname
      JSON.parse(File.read(developer_json_pathname))
    else
      {}
    end
  end
end

#end_on_error(err) ⇒ Object



284
285
286
287
# File 'lib/plugin.rb', line 284

def end_on_error(err)
  puts err
  exit 1
end

#exclude_files_from_minimisationObject



105
106
107
108
109
110
111
112
113
114
# File 'lib/plugin.rb', line 105

def exclude_files_from_minimisation
  @exclude_files_from_minimisation ||= begin
    # developer.json file might specify files which should skip minimisation when packing
    if developer_json['excludeFromMinimisation'].kind_of?(Array)
      developer_json['excludeFromMinimisation']
    else
      []
    end
  end
end

#exclude_files_from_syntax_checkObject



94
95
96
97
98
99
100
101
102
103
# File 'lib/plugin.rb', line 94

def exclude_files_from_syntax_check
  @exclude_files_from_syntax_check ||= begin
    # developer.json file might contain some files which should not be syntax checked
    if developer_json['excludeFromSyntaxCheck'].kind_of?(Array)
      developer_json['excludeFromSyntaxCheck']
    else
      []
    end
  end
end

#generate_license_key(application_id) ⇒ Object




270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/plugin.rb', line 270

def generate_license_key(application_id)
  info = File.open("#{@plugin_dir}/plugin.json") { |f| JSON.parse(f.read) }
  if info["installSecret"] == nil
    end_on_error "#{@name}: No installSecret specified in plugin.json"
  end
  license_key = HMAC::SHA1.sign(info["installSecret"], "application:#{application_id}")
  puts <<__E

Plugin:       #{@name}
Application:  #{application_id}
License key:  #{license_key}
__E
end

#plugin_load_priorityObject



50
51
52
53
# File 'lib/plugin.rb', line 50

def plugin_load_priority
  pj = File.open("#{@plugin_dir}/plugin.json") { |f| JSON.parse(f.read) }
  pj['loadPriority'] || DEFAULT_PLUGIN_LOAD_PRIORITY
end

#setup_for_serverObject



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
# File 'lib/plugin.rb', line 55

def setup_for_server
  # Make the first empty manifest (may be replaced from server)
  @current_manifest = {}

  # If minimisation is active, clear the current manifest so all files are uploaded again.
  if @options.minimiser != nil
    @current_manifest = {}
  end

  # See if the plugin has already been registered with the server
  s_found_info = PluginTool.post_with_json_response("/api/development-plugin-loader/find-registration", {:name => @name})
  if s_found_info["found"]
    # Store info returned by the server
    @loaded_plugin_id = s_found_info["plugin_id"]
    @current_manifest = s_found_info["manifest"]
  end

  # If there isn't an existing plugin registered, create a new one
  if @loaded_plugin_id == nil
    s_create_info = PluginTool.post_with_json_response("/api/development-plugin-loader/create")
    end_on_error "Couldn't communicate successfully with server." if s_create_info["protocol_error"]
    end_on_error "Failed to create plugin on server" unless s_create_info["plugin_id"] != nil
    @loaded_plugin_id = s_create_info["plugin_id"]
  end
end

#startObject




45
46
47
48
# File 'lib/plugin.rb', line 45

def start
  # Setup for using the plugin
  @loaded_plugin_id = nil
end