This commit is contained in:
Artur Gurgul 2025-08-05 10:48:11 +02:00
parent 8d6eb57fe0
commit f3bb91d09e

View file

@ -3,6 +3,7 @@ require 'uri'
require 'open3' require 'open3'
require 'fileutils' require 'fileutils'
require 'open-uri' require 'open-uri'
require 'shellwords'
module Archive module Archive
MAGIC_NUMBERS = { MAGIC_NUMBERS = {
@ -12,6 +13,32 @@ module Archive
"\xFD\x37\x7A\x58" => 'xz' "\xFD\x37\x7A\x58" => 'xz'
} }
def self.fetch_and_extract(url, cache_path, destination_dir)
uri = URI.parse(url)
file_name = File.basename(uri.path)
archive_path = File.join(destination_dir, file_name)
format = detect_format_from_url(url)
puts "format #{format}"
download_file(uri, archive_path)
unless format
puts "case 1"
format = detect_format_from_headers(uri)
end
unless format
puts "case 2"
format = detect_format_from_magic(archive_path)
end
raise "Could not determine archive format" unless format
extract_archive(archive_path, format)
end
private
def self.detect_format_from_url(url) def self.detect_format_from_url(url)
case File.extname(url) case File.extname(url)
when '.gz', '.tgz' then 'gzip' when '.gz', '.tgz' then 'gzip'
@ -61,33 +88,16 @@ module Archive
when 'zstd' when 'zstd'
system("unzstd #{Shellwords.escape(file_path)}") system("unzstd #{Shellwords.escape(file_path)}")
when 'xz' when 'xz'
system("tar -xJf #{Shellwords.escape(file_path)}") # if file_path.end_with?('.tar.xz')
if `file #{Shellwords.escape(file_path)}`.include?('tar archive')
system("tar -xJf #{Shellwords.escape(file_path)}")
else
system("xz -dk #{Shellwords.escape(file_path)}")
end
else else
raise "Unsupported archive format: #{format}" raise "Unsupported archive format: #{format}"
end end
end end
def self.fetch_and_extract(url)
uri = URI.parse(url)
file_name = File.basename(uri.path)
tmp_path = "/tmp/#{file_name}"
format = detect_format_from_url(url)
puts "format #{format}"
download_file(uri, tmp_path)
unless format
format = detect_format_from_headers(uri)
end
unless format
format = detect_format_from_magic(tmp_path)
end
raise "Could not determine archive format" unless format
extract_archive(tmp_path, format)
end
end end
# Example usage: # Example usage:
# fetch_and_extract("https://codeberg.org/forgejo/forgejo/releases/download/v12.0.1/forgejo-12.0.1-linux-amd64.xz") # fetch_and_extract("https://codeberg.org/forgejo/forgejo/releases/download/v12.0.1/forgejo-12.0.1-linux-amd64.xz")