# encoding: utf-8 require 'fedux_org_stdlib/require_files' require 'fedux_org_stdlib/rake/task' require 'digest/sha2' require_library %w(active_support/core_ext/string/strip excon addressable/uri) module FeduxOrgStdlib module Rake # Webserver Task # # @see Rakefile class WebserverTask < Task # @!attribute [r] report # The report to be generated attr_reader :site, :directory, :index_file_content, :files, :checksums_file, :checksums # Create a new webserver task # # @param [String] directory # The directory where the generated server should be stored # @param [String] url # The url which should be used to fetch the remote repository # @example Create new task # FeduxOrgStdlib::Rake::WebserverTask.new def initialize( directory: File.expand_path('utils/server'), site: 'http://fedux.org/downloads/local_webserver', checksums_file: 'CHECKSUMS', index_file_content: nil, files: %w( server.darwin.amd64 server.linux.amd64 server.windows.amd64.exe ), redirect_to: nil, **args ) super(**args) @site = Addressable::URI.heuristic_parse(site) @files = Array(files) @checksums_file = checksums_file @directory = File.expand_path(directory) @index_file_content = if index_file_content index_file_content elsif redirect_to redirect_to_destination(redirect_to) else nil end end # @private def run_task(_verbose) fetch_checksums fetch_files create_index_file unless index_file_content.blank? end private def create_index_file File.write(File.join(directory, 'index.html'), index_file_content) end def redirect_to_destination(destination) <<-EOS.strip_heredoc EOS end def fetch_checksums url = site.to_s + '/' + checksums_file response = Excon.get(url) puts "[INFO] Fetching #{url}." fail "[ERROR] Error while downloading #{url}." unless response.status == 200 @checksums = response.body.split("\n").each_with_object({}) do |e, a| sum, file = e.split(/\s+/) a[file] = sum end end def fetch_files files.each do |f| url = site.to_s + '/' + f puts "[INFO] Fetching #{url}" response = Excon.get(url) fail "[ERROR] Error while downloading \"#{url}\"." unless response.status == 200 puts "[INFO] Checking downloaded content against checksum \"#{checksums[f]}\"." fail "[ERROR] Checksum error for file \"#{url}\"." unless checksum?(response.body, checksums[f]) path = File.join(directory, f) puts "[INFO] Save content to #{path}." FileUtils.mkdir_p File.dirname(path) File.write(path, response.body) FileUtils.chmod 0755, path end end def checksum?(file, sum) Digest::SHA256.hexdigest(file) == sum end end end end