2020-10-10 14:16:11 +02:00
|
|
|
# typed: true
|
2019-04-19 15:38:03 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-10-10 17:53:31 +02:00
|
|
|
require "system_command"
|
|
|
|
|
2018-07-23 20:59:21 +02:00
|
|
|
module UnpackStrategy
|
2020-08-09 06:09:05 +02:00
|
|
|
# Strategy for unpacking tar archives.
|
2018-07-23 20:59:21 +02:00
|
|
|
class Tar
|
|
|
|
include UnpackStrategy
|
2020-10-10 17:53:31 +02:00
|
|
|
extend SystemCommand::Mixin
|
2018-07-23 20:59:21 +02:00
|
|
|
|
2020-10-20 12:03:48 +02:00
|
|
|
sig { returns(T::Array[String]) }
|
2018-07-30 09:49:59 +02:00
|
|
|
def self.extensions
|
|
|
|
[
|
|
|
|
".tar",
|
|
|
|
".tbz", ".tbz2", ".tar.bz2",
|
|
|
|
".tgz", ".tar.gz",
|
2018-08-21 15:46:24 +02:00
|
|
|
".tlzma", ".tar.lzma",
|
2021-09-16 15:56:31 +01:00
|
|
|
".txz", ".tar.xz",
|
|
|
|
".tar.zst"
|
2018-07-30 09:49:59 +02:00
|
|
|
]
|
|
|
|
end
|
|
|
|
|
2018-07-29 10:04:51 +02:00
|
|
|
def self.can_extract?(path)
|
|
|
|
return true if path.magic_number.match?(/\A.{257}ustar/n)
|
|
|
|
|
2021-09-16 15:56:31 +01:00
|
|
|
return false unless [Bzip2, Gzip, Lzip, Xz, Zstd].any? { |s| s.can_extract?(path) }
|
2018-07-23 20:59:21 +02:00
|
|
|
|
|
|
|
# Check if `tar` can list the contents, then it can also extract it.
|
2021-04-15 12:17:55 +01:00
|
|
|
stdout, _, status = system_command("tar", args: ["--list", "--file", path], print_stderr: false)
|
2019-10-13 17:19:02 +02:00
|
|
|
status.success? && !stdout.empty?
|
2018-07-23 20:59:21 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2020-10-20 12:03:48 +02:00
|
|
|
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).returns(T.untyped) }
|
2018-07-23 20:59:21 +02:00
|
|
|
def extract_to_dir(unpack_dir, basename:, verbose:)
|
2018-07-30 16:31:29 +02:00
|
|
|
Dir.mktmpdir do |tmpdir|
|
2021-09-16 15:56:31 +01:00
|
|
|
tar_path = if DependencyCollector.tar_needs_xz_dependency? && Xz.can_extract?(path)
|
|
|
|
subextract(Xz, Pathname(tmpdir), verbose)
|
|
|
|
elsif Zstd.can_extract?(path)
|
|
|
|
subextract(Zstd, Pathname(tmpdir), verbose)
|
|
|
|
else
|
|
|
|
path
|
2018-07-30 16:31:29 +02:00
|
|
|
end
|
|
|
|
|
2018-07-24 18:43:20 +02:00
|
|
|
system_command! "tar",
|
2021-04-15 12:17:55 +01:00
|
|
|
args: ["--extract", "--no-same-owner",
|
|
|
|
"--file", tar_path,
|
|
|
|
"--directory", unpack_dir],
|
2018-07-24 18:43:20 +02:00
|
|
|
verbose: verbose
|
2018-07-30 16:31:29 +02:00
|
|
|
end
|
2018-07-23 20:59:21 +02:00
|
|
|
end
|
2021-09-16 15:56:31 +01:00
|
|
|
|
|
|
|
sig {
|
|
|
|
params(extractor: T.any(T.class_of(Xz), T.class_of(Zstd)), dir: Pathname, verbose: T::Boolean).returns(Pathname)
|
|
|
|
}
|
|
|
|
def subextract(extractor, dir, verbose)
|
|
|
|
extractor.new(path).extract(to: dir, verbose: verbose)
|
|
|
|
T.must(dir.children.first)
|
|
|
|
end
|
2018-07-23 20:59:21 +02:00
|
|
|
end
|
|
|
|
end
|