Skip to content

Instantly share code, notes, and snippets.

@ryansch
Created June 16, 2016 12:17
Show Gist options
  • Save ryansch/e903c2492ae6e31f32bbce4b58277e24 to your computer and use it in GitHub Desktop.
Save ryansch/e903c2492ae6e31f32bbce4b58277e24 to your computer and use it in GitHub Desktop.
Create/Extract a tarball from ruby
require 'find'
require 'archive/tar/minitar'
module IdiomaticTar
def create_tarball(filename:, directory:)
base_dir = Pathname.new(directory).parent
FileUtils.cd(base_dir) do
Pathname.new(filename).open('wb') do |tarball|
Zlib::GzipWriter.wrap(tarball) do |gz|
Archive::Tar::Minitar::Output.open(gz) do |tar|
Find.find(directory) do |path|
pn = Pathname.new(path)
name = pn.relative_path_from(base_dir)
Archive::Tar::Minitar.pack_file(name.to_s, tar)
end
end
end
end
end
end
def extract_tarball(filename:, directory:)
Pathname.new(filename).open('rb') do |tarball|
Zlib::GzipReader.wrap(tarball) do |gz|
Archive::Tar::Minitar.unpack(gz, directory)
end
end
end
end
@ryansch
Copy link
Author

ryansch commented Jun 16, 2016

create_tarball doesn't use Minitar.pack as that method refuses to use relative paths. This approach creates a tarball with one top level directory that contains no slashes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment