Skip to content

Instantly share code, notes, and snippets.

@splattael
Created May 29, 2017 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save splattael/2408039c969513f5ee6f7799b16b54bb to your computer and use it in GitHub Desktop.
Save splattael/2408039c969513f5ee6f7799b16b54bb to your computer and use it in GitHub Desktop.
Create bundler setup file. Similar what `bundle --standalone` does.
require "bundler"
class BundlerSetup
def initialize(gemfile)
@gemfile = gemfile
@lockfile = "#{gemfile}.lock"
end
def run(io)
Dir.chdir(File.dirname(@gemfile)) do
puts_header(io)
puts_pathes(io)
end
end
private
def puts_header(io)
io.puts <<~END
# DO NOT MODIFY
#
# This file has been created by #{$0} at #{Time.now}
# Run `ruby #{$0}` to regenerated this file
home = Dir.home
pwd = File.expand_path("..", __dir__)
puts "HOME: \#{home}"
puts "PWD: \#{pwd}"
END
end
def puts_pathes(io)
defintion = Bundler::Definition.build(@gemfile, @lockfile, {})
defintion.specs.each do |spec|
next if spec.name == "bundler"
spec.require_paths.each do |path|
path = gem_path(path, spec)
puts_path(io, path)
end
end
end
def puts_path(io, path)
io.puts <<~END
$:.unshift "#{path}"
END
end
def normalize(path)
root_dir = File.expand_path("..", Dir.pwd)
case
when path.start_with?(Dir.home)
path.sub(Dir.home, '#{home}')
when path.start_with?(root_dir)
relative = Pathname.new(path).relative_path_from(Pathname.new(Dir.pwd))
"\#{pwd}/#{relative}"
else
raise "unhandled path: #{path}"
end
end
def gem_path(path, spec)
full_path = Pathname.new(path).absolute? ? path : File.join(spec.full_gem_path, path)
normalize(full_path)
rescue TypeError
error_message = "#{spec.name} #{spec.version} has an invalid gemspec"
raise Gem::InvalidSpecificationException.new(error_message)
end
end
gemfile = File.expand_path("../Gemfile", __dir__)
setup = File.expand_path("setup.rb", __dir__)
File.open(setup, "w") do |file|
BundlerSetup.new(gemfile).run(file)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment