Skip to content

Instantly share code, notes, and snippets.

@snipsnipsnip
Created June 9, 2019 13:16
Show Gist options
  • Save snipsnipsnip/79bb0b3d7535b6f78ab9eb4d9f795e38 to your computer and use it in GitHub Desktop.
Save snipsnipsnip/79bb0b3d7535b6f78ab9eb4d9f795e38 to your computer and use it in GitHub Desktop.
autozip.rb is a 7za wrapper extracts/archives any zips/folders (respectively) put in the working directory
# frozen-string-literal: true
require 'fileutils'
require 'shellwords'
require 'date'
Outdir = 'out'
def run(cmd)
puts "!#{cmd}"
system cmd
end
def make_extract_path(name)
File.join(Outdir, "#{Time.now.strftime '%Y%m%d'}_#{name}")
end
def each_extract_command(dst, src)
yield %{7za x -y -o#{Shellwords.escape dst} #{Shellwords.escape zip}}
end
def each_compress_command(dst, src)
yield %{7za a -mx9 #{Shellwords.escape dst} #{Shellwords.escape dir}}
end
def main
paths = nil
loop do
curr = Dir['*']
if curr != paths
sweep(curr)
paths = curr
end
sleep 3
end
end
def sweep(paths)
ok = 0
paths.each do |path|
if path =~ /\.zip\z|\.7z\z/i
extract path
elsif path != Outdir && File.directory?(path)
compress path
else
puts "##{path}: skipped unknown"
end
ok = $?.to_i if ok == 0
end
ok == 0
end
def compress(dir)
dst = File.join(Outdir, "#{dir}.7z")
mtime = File.mtime(dir)
if File.exist?(dst) && mtime < File.mtime(dst)
puts "##{dir}: skipped compressing"
return
end
each_compress_command(dst, dir) do |cmd|
run cmd
end
end
def extract(zip)
name = File.basename(zip, '.*')
prev = Dir[File.join(Outdir, "*#{name}*")]
if prev.any? {|x| File.directory? x }
puts "File exists: #{prev}"
return
end
dst = make_extract_path(name)
mtime = File.mtime(zip)
if File.exist?(dst) && mtime < File.mtime(dst)
puts "##{zip}: skipped extracting"
return
end
FileUtils.mkdir_p File.dirname(dst)
each_extract_command(dst, zip) do |cmd|
run cmd and return
FileUtils.rm_rf dst
end
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment