Skip to content

Instantly share code, notes, and snippets.

@glenux
Last active January 23, 2017 12:36
Show Gist options
  • Save glenux/13cbeea36b862a882976a2bf51d0da2e to your computer and use it in GitHub Desktop.
Save glenux/13cbeea36b862a882976a2bf51d0da2e to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# vim: set ts=2 sw=2 et:
require 'find'
require 'colorize'
require 'fileutils'
class Merger
def initialize
@ind = 0
end
def merge_pdfs where
pdf_basename = File.basename(File.expand_path(where))
pdf_path = File.join(File.dirname(where), pdf_basename + '.pdf')
outpdf_path = output_of pdf_path
outpdf_dir = File.dirname(outpdf_path)
FileUtils.mkdir_p outpdf_dir
FileUtils.mkdir_p (output_of where)
sub_pdfs = []
Dir.chdir(where) do
sub_pdfs.concat Dir['*.pdf']
end
Dir.chdir(output_of where) do
sub_pdfs.concat Dir['*.pdf']
end
sub_pdfs.sort!
puts "#{indent} #{where.yellow} merge PDF"
sub_pdfs.each do |file|
puts "#{indent} #{where.yellow} src = %s" % file
end
if sub_pdfs.size == 0 then
puts "#{indent} #{where.yellow}" + " no PDF found in subtree !".red + " skipping merge."
else
pdfs = sub_pdfs.map do |file|
if File.exist? File.join(where, file) then File.join(where, file)
else File.join(output_of(where), file)
end
end
puts "#{indent} #{pdf_path.green} merged"
system "pdftk", *pdfs, "cat", "output", outpdf_path
end
sub_pdfs = Dir["#{output_of File.dirname(where)}/*.pdf"].sort
end
def recurse where
puts "#{indent} #{where.yellow} begin recursing_dir"
indent_more
Find.find(where) do |path|
next unless FileTest.directory?(path)
next if File.basename(path) == "_build"
next if path == where
next if path == "."
recurse path
Find.prune
end
indent_less
puts "#{indent} #{where.yellow} end recursing_dir"
puts "#{indent} #{where.yellow} begin merging_pdfs"
merge_pdfs where
puts "#{indent} #{where.yellow} end merging_pdfs"
end
def run where
FileUtils.rm_rf "_build"
recurse where
end
private
def output_of where
File.join('_build', where)
end
def indent
(" " * @ind)
end
def indent_more
@ind += 1
end
def indent_less
@ind -= 1
end
end
app = Merger.new
if ARGV.size > 0 and File.directory? ARGV[0] then
app.run ARGV[0]
else
puts "Usage: #{$0} directory"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment