Skip to content

Instantly share code, notes, and snippets.

@YOCKOW
Last active November 28, 2022 03:44
Show Gist options
  • Select an option

  • Save YOCKOW/52756b7061c4e92ca960cf2ff9506560 to your computer and use it in GitHub Desktop.

Select an option

Save YOCKOW/52756b7061c4e92ca960cf2ff9506560 to your computer and use it in GitHub Desktop.
Install files symbolically...
#!/usr/bin/env ruby
=begin
sym-install.rb
©︎ 2017, 2022 YOCKOW.
Licensed under MIT License.
=end
require 'date'
require 'fileutils'
def symbolic_install(source_dir, dest_dir, filename)
source_dir_abs_path = File.realpath('.', source_dir)
source_abs_path = "#{source_dir_abs_path}/#{filename}"
dest_dir_abs_path = File.realpath('.', dest_dir)
dest_abs_path = "#{dest_dir_abs_path}/#{filename}"
$stdout.puts("#{source_abs_path}")
$stdout.puts("-> #{dest_abs_path}")
source_is_dir = File.directory?(source_abs_path)
if (File.exists?(dest_abs_path))
dest_is_dir = File.directory?(dest_abs_path)
if (source_is_dir != dest_is_dir)
$stderr.puts("TYPE MISMATCH")
$stderr.puts(" #{source_abs_path} is directory?: #{source_is_dir ? 'Yes' : 'No'}")
$stderr.puts(" #{dest_abs_path} is directory?: #{dest_is_dir ? 'Yes' : 'No'}")
exit
end
if !dest_is_dir && !File.symlink?(dest_abs_path)
suffix = DateTime.now.strftime("%Y%m%d-%H%M%S")
FileUtils.mv(dest_abs_path, "#{dest_abs_path}_#{suffix}")
$stdout.puts("** Created backup: #{dest_abs_path}_#{suffix}")
end
else # dest_abs_path doesn't exist
if source_is_dir
FileUtils.mkdir_p(dest_abs_path)
$stdout.puts("** Created Directory: #{dest_abs_path}")
end
end
if source_is_dir # install recursively
$stdout.puts("=== Opening Directory: #{source_abs_path}")
Dir.open(source_abs_path).each{|file_or_dir|
next if file_or_dir =~ /^\.\.?$/
symbolic_install(source_abs_path, dest_abs_path, file_or_dir)
}
$stdout.puts("=== Closed Directory: #{source_abs_path}")
else
FileUtils.ln_s(source_abs_path, dest_abs_path, **{:force => true})
$stdout.puts("** Created a symbolic link")
end
end
source = ARGV[0]
destination = ARGV[1]
if (!source || source.empty?)
$stderr.puts("From where?")
exit
end
if (source !~ /^\//)
source = File.realpath(source, Dir.pwd)
end
if (!destination || destination.empty?)
destination = '/usr/local'
end
if (destination !~ /^\//)
destination = File.realpath(destination, Dir.pwd)
end
if (!File.exists?(source))
$stderr.puts("Directory Not Found: #{source}")
end
if (!File.exists?(destination))
$stderr.puts("Directory Not Found: #{destination}")
end
if (!File.directory?(source) || !File.directory?(destination))
$stderr.puts("Both paths must be directory.")
exit
end
Dir.open(source).each {|file_or_dir|
next if (file_or_dir !~ /^(bin|doc|etc|include|lib.*|sbin|share)$/)
source_abs_path = File.realpath(file_or_dir, source)
next if (!File.directory?(source_abs_path))
symbolic_install(source, destination, file_or_dir)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment