Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ name: CI
on:
push:
branches: [master]
tags: ['v*']
pull_request:
workflow_dispatch:

Expand Down Expand Up @@ -51,3 +52,57 @@ jobs:
run: bundle exec rake sysinfo
- name: Test (cargo, minitest, rubocop, pbench, mspec)
run: env ${{ matrix.suite.env }} bundle exec rake test

# The prebuilt extension that `gem install` downloads when Cargo is missing:
# one Ruby per OS (see lib/faster_path/prebuilt.rb). Runs for a version tag
# and on request, to check the builds before tagging.
prebuilt:
name: Prebuilt extension (${{ matrix.os }})
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
needs: [test]
runs-on: ${{ matrix.os }}
defaults:
run:
shell: bash
strategy:
fail-fast: false
matrix:
os: [ubuntu-22.04, macos-latest, macos-15-intel, windows-latest]
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.4'
bundler-cache: true
- run: bundle exec rake prebuilt
- uses: actions/upload-artifact@v4
with:
name: prebuilt-${{ matrix.os }}
path: pkg/faster_path-*

# Attaches the gem and the prebuilt extensions to the GitHub release of a version tag.
release:
name: GitHub release
if: startsWith(github.ref, 'refs/tags/v')
needs: [prebuilt]
runs-on: ubuntu-22.04
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.4'
- run: gem build faster_path.gemspec
- uses: actions/download-artifact@v4
with:
pattern: prebuilt-*
merge-multiple: true
path: pkg
- run: ls -l pkg *.gem
- uses: softprops/action-gh-release@v2
with:
files: |
faster_path-*.gem
pkg/faster_path-*
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "faster_path"
version = "0.5.0"
version = "0.5.1"
authors = ["Daniel P. Clark <6ftdan@gmail.com>"]
description = "Alternative to Pathname"
homepage = "https://github.com/danielpclark/faster_path"
Expand Down
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,16 @@ As mentioned earlier Sprockets, which handles assets, changed away from using `P
## Requirements

* Ruby 3.2, 3.3 or 3.4 (the Rust extension is built with [Rutie](https://github.com/danielpclark/rutie) 0.13, which supports these)
* Rust 1.71 or later: `gem install` builds the extension with Cargo (through the
* Rust 1.71 or later, unless a prebuilt extension exists for your platform (see
[Installation](#installation)): `gem install` builds the extension with Cargo (through the
[rutie](https://rubygems.org/gems/rutie) gem's Rake task) and keeps only the built library

## Installation

Ensure Rust is installed, with `cargo` on your `PATH`:
Each [release](https://github.com/danielpclark/faster_path/releases) carries a prebuilt
extension for Ruby 3.4 on Linux x86_64, macOS (arm64 and x86_64) and Windows x64. On those,
`gem install` needs no Rust. Everywhere else (another Ruby version, OS or CPU), ensure Rust is
installed, with `cargo` on your `PATH`:

[Install Rust](https://www.rust-lang.org/tools/install)

Expand All @@ -130,7 +134,7 @@ curl -sSf https://sh.rustup.rs | sh
Add this line to your application's Gemfile:

```ruby
gem 'faster_path', '~> 0.5.0'
gem 'faster_path', '~> 0.5.1'
```

And then execute:
Expand All @@ -143,9 +147,11 @@ Or install it yourself as:

Installing compiles the Rust extension for the Ruby doing the installing ("Building native
extensions. This could take a while..."), which takes about a minute the first time while Cargo
fetches and builds the dependencies. If Rust is missing, the install fails at that step with
Cargo not being found; install Rust and run it again. Nothing is downloaded from GitHub: there are
no prebuilt binaries.
fetches and builds the dependencies. When Cargo is not found, the install downloads the release's
prebuilt extension for your platform instead (`faster_path-<version>-ruby<XY>-<os>-<cpu>.tar.gz`,
checked against its SHA-256 file) and fails with a message naming that file if there is none.
`FASTER_PATH_PREBUILT_URL` points the download at another directory holding the same files, for
mirrors or machines without access to GitHub.

## Visual Benchmarks

Expand Down
7 changes: 7 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ end
desc 'Build the Rust extension'
task build_lib: 'rutie:build'

desc 'Package the built extension as the prebuilt release asset for this platform, in pkg/'
task prebuilt: 'rutie:build' do
require 'faster_path/prebuilt'
FileUtils.mkdir_p('pkg')
puts FasterPath::Prebuilt.package(FasterPath::BuildTask.built_library, 'pkg')
end

desc 'Code Quality Check'
task :lint do
puts
Expand Down
32 changes: 29 additions & 3 deletions ext/Rakefile
Original file line number Diff line number Diff line change
@@ -1,14 +1,40 @@
require 'fileutils'
require_relative '../lib/faster_path/build_task'
require_relative '../lib/faster_path/prebuilt'

FasterPath::BuildTask.define

# Keeps the built library (in lib/faster_path, where FasterPath loads it from)
# and removes the rest of Cargo's output from the installed gem.
# Builds the extension, keeps the built library (in lib/faster_path, where
# FasterPath loads it from) and removes the rest of Cargo's output from the
# installed gem.
task install_library: 'rutie:build' do
FileUtils.mkdir_p(FasterPath::BuildTask::INSTALLED_LIBRARY_DIR)
FileUtils.cp(FasterPath::BuildTask.built_library, FasterPath::BuildTask::INSTALLED_LIBRARY_DIR)
Rake::Task['rutie:clean'].invoke
end

task default: :install_library
NO_PREBUILT = <<~MESSAGE
****
Rust's Cargo was not found, and this release of faster_path has no prebuilt
extension for this platform (%s).
Install Rust (https://www.rust-lang.org/tools/install) and run the install
again, or set FASTER_PATH_PREBUILT_URL to a directory holding the asset.
****
MESSAGE

# Installs the prebuilt library from this version's GitHub release instead.
task :install_prebuilt do
library = FasterPath::Prebuilt.install(FasterPath::BuildTask::PROJECT_DIR)
raise format(NO_PREBUILT, FasterPath::Prebuilt.asset_name) unless library

puts "Installed the prebuilt extension #{File.basename(library)}"
end

task :default do
if FasterPath::BuildTask.cargo?
Rake::Task[:install_library].invoke
else
puts 'Cargo was not found; downloading the prebuilt extension for this platform instead'
Rake::Task[:install_prebuilt].invoke
end
end
2 changes: 1 addition & 1 deletion faster_path.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Gem::Specification.new do |spec|
spec.files = [
'Cargo.lock', 'Cargo.toml', 'Gemfile', 'MIT-LICENSE.txt', 'README.md', 'Rakefile',
'bin/console', 'bin/setup', 'ext/Rakefile', 'faster_path.gemspec', 'lib/faster_path.rb',
'lib/faster_path/version.rb', 'lib/faster_path/build_task.rb',
'lib/faster_path/version.rb', 'lib/faster_path/build_task.rb', 'lib/faster_path/prebuilt.rb',
'lib/faster_path/optional/monkeypatches.rb', 'lib/faster_path/optional/refinements.rb'
]
spec.files += Dir['src/**/*']
Expand Down
10 changes: 10 additions & 0 deletions lib/faster_path/build_task.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,15 @@ def self.define
def self.built_library
Rutie.new(:faster_path).ffi_library(File.join(PROJECT_DIR, 'lib'))
end

# Whether Cargo can be run: named by CARGO, or on the PATH
def self.cargo?
return true if ENV['CARGO']

exts = RbConfig::CONFIG['EXEEXT'].empty? ? [''] : ['', RbConfig::CONFIG['EXEEXT']]
ENV.fetch('PATH', '').split(File::PATH_SEPARATOR).any? do |dir|
exts.any? { |ext| File.executable?(File.join(dir, "cargo#{ext}")) }
end
end
end
end
118 changes: 118 additions & 0 deletions lib/faster_path/prebuilt.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
require 'digest/sha2'
require 'fileutils'
require 'net/http'
require 'rbconfig'
require 'rubygems/package'
require 'stringio'
require 'uri'
require 'zlib'
require_relative 'version'

module FasterPath
# The prebuilt extension that the GitHub release of each version carries
# for a few platforms, so that the gem installs without Rust there:
# `gem install` falls back to it when Cargo is not found (see ext/Rakefile),
# and the release workflow builds it with `rake prebuilt`.
module Prebuilt
RELEASES = 'https://github.com/danielpclark/faster_path/releases/download'.freeze
# Where the library sits in the tarball and, unpacked, in the gem
LIBRARY_DIR = File.join('lib', 'faster_path').freeze
MAX_REDIRECTS = 5

# The asset for the running Ruby, e.g. "faster_path-0.5.0-ruby34-linux-x86_64.tar.gz":
# the gem version, the Ruby minor version the library was built for (an
# extension works with every patch release of it), the OS family and the CPU.
def self.asset_name(rbconfig = RbConfig::CONFIG, version = FasterPath::VERSION)
major, minor = rbconfig['ruby_version'].split('.')
"faster_path-#{version}-ruby#{major}#{minor}-#{os(rbconfig)}-#{cpu(rbconfig)}.tar.gz"
end

def self.os(rbconfig)
case rbconfig['host_os']
when /darwin/ then 'darwin'
when /mingw|mswin|cygwin/ then 'windows'
else rbconfig['host_os'][/\A[a-z]+/]
end
end

def self.cpu(rbconfig)
{ 'x64' => 'x86_64', 'amd64' => 'x86_64', 'aarch64' => 'arm64' }.fetch(rbconfig['target_cpu'], rbconfig['target_cpu'])
end

# Packs the built `library` as lib/faster_path/<file> into `dir`, with a
# SHA-256 checksum file next to it, and returns the tarball's path.
def self.package(library, dir, asset = asset_name)
path = File.join(dir, asset)
data = File.binread(library)
File.open(path, 'wb') do |file|
Zlib::GzipWriter.wrap(file) do |gz|
Gem::Package::TarWriter.new(gz) do |tar|
tar.add_file_simple(File.join(LIBRARY_DIR, File.basename(library)), 0o644, data.bytesize) { |io| io.write(data) }
end
end
end
File.write("#{path}.sha256", "#{Digest::SHA256.file(path).hexdigest} #{asset}\n")
path
end

# Downloads this platform's asset of this version's release, checks it
# against its checksum file and unpacks the library into `project_dir`.
# Returns the library's path, or nil when the release has no asset for
# this platform. FASTER_PATH_PREBUILT_URL replaces the release's URL.
def self.install(project_dir, base_url = ENV.fetch('FASTER_PATH_PREBUILT_URL', "#{RELEASES}/v#{FasterPath::VERSION}"))
asset = asset_name
tarball = fetch("#{base_url}/#{asset}")
return nil unless tarball

checksum = fetch("#{base_url}/#{asset}.sha256")
raise "#{asset} has no checksum file at #{base_url}" unless checksum

verify(tarball, checksum, asset)
unpack(tarball, project_dir)
end

# The body at `url`, following redirects, or nil if it does not exist.
def self.fetch(url, redirects = MAX_REDIRECTS)
uri = URI(url)
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') { |http| http.get(uri.request_uri) }
case response
when Net::HTTPSuccess then response.body
when Net::HTTPNotFound then nil
when Net::HTTPRedirection
raise "Too many redirects fetching #{url}" if redirects.zero?

fetch(URI.join(url, response['Location']).to_s, redirects - 1)
else raise "#{url}: #{response.code} #{response.message}"
end
end

def self.verify(tarball, checksum, asset)
expected = checksum.split.first.to_s.downcase
actual = Digest::SHA256.hexdigest(tarball)
raise "#{asset} does not match its checksum (expected #{expected}, got #{actual})" unless expected == actual
end

# Unpacks the library of the tarball `data` into `project_dir` and returns its path.
def self.unpack(data, project_dir)
installed = nil
Zlib::GzipReader.wrap(StringIO.new(data)) do |gz|
Gem::Package::TarReader.new(gz) do |tar|
tar.each do |entry|
next unless entry.file? && File.dirname(entry.full_name) == LIBRARY_DIR

installed = write_library(project_dir, File.basename(entry.full_name), entry.read)
end
end
end
installed || raise("No #{LIBRARY_DIR} library in the tarball")
end

def self.write_library(project_dir, name, data)
dir = File.join(project_dir, LIBRARY_DIR)
FileUtils.mkdir_p(dir)
path = File.join(dir, name)
File.binwrite(path, data)
path
end
end
end
2 changes: 1 addition & 1 deletion lib/faster_path/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module FasterPath
VERSION = "0.5.0"
VERSION = "0.5.1"
end
61 changes: 61 additions & 0 deletions test/prebuilt_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
require 'test_helper'
require 'faster_path/build_task'
require 'faster_path/prebuilt'
require 'tmpdir'

# The prebuilt extension of a release, as the release workflow packs it and
# `gem install` unpacks it
class PrebuiltTest < Minitest::Test
LINUX = { 'host_os' => 'linux', 'target_cpu' => 'x86_64', 'ruby_version' => '3.4.0' }.freeze
MACOS = { 'host_os' => 'darwin24', 'target_cpu' => 'arm64', 'ruby_version' => '3.4.0' }.freeze
WINDOWS = { 'host_os' => 'mingw32', 'target_cpu' => 'x64', 'ruby_version' => '3.4.0' }.freeze

def test_the_asset_is_named_after_the_gem_version_ruby_minor_version_os_and_cpu
assert_equal 'faster_path-0.5.0-ruby34-linux-x86_64.tar.gz', FasterPath::Prebuilt.asset_name(LINUX, '0.5.0')
assert_equal 'faster_path-0.5.0-ruby34-darwin-arm64.tar.gz', FasterPath::Prebuilt.asset_name(MACOS, '0.5.0')
assert_equal 'faster_path-0.5.0-ruby34-windows-x86_64.tar.gz', FasterPath::Prebuilt.asset_name(WINDOWS, '0.5.0')
assert_equal 'faster_path-0.5.0-ruby33-linux-arm64.tar.gz',
FasterPath::Prebuilt.asset_name(LINUX.merge('target_cpu' => 'aarch64', 'ruby_version' => '3.3.0'), '0.5.0')
end

def test_the_asset_for_this_ruby_uses_the_gem_version
assert_match(/\Afaster_path-#{Regexp.escape(FasterPath::VERSION)}-ruby\d\d-[a-z]+-[a-z0-9_]+\.tar\.gz\z/,
FasterPath::Prebuilt.asset_name)
end

def test_packing_and_unpacking_round_trips_the_built_library
Dir.mktmpdir do |dir|
tarball = FasterPath::Prebuilt.package(FasterPath::FFI_LIBRARY, dir)

assert_equal File.join(dir, FasterPath::Prebuilt.asset_name), tarball
assert_match(/\A\h{64} #{Regexp.escape(FasterPath::Prebuilt.asset_name)}\n\z/, File.read("#{tarball}.sha256"))

data = File.binread(tarball)
FasterPath::Prebuilt.verify(data, File.read("#{tarball}.sha256"), 'asset')
installed = FasterPath::Prebuilt.unpack(data, File.join(dir, 'gem'))

assert_equal File.join(dir, 'gem', 'lib', 'faster_path', File.basename(FasterPath::FFI_LIBRARY)), installed
assert_equal File.binread(FasterPath::FFI_LIBRARY), File.binread(installed)
end
end

def test_a_wrong_checksum_is_refused
error = assert_raises(RuntimeError) { FasterPath::Prebuilt.verify('data', "#{'0' * 64} asset\n", 'asset') }
assert_match(/does not match its checksum/, error.message)
end

def test_a_tarball_without_the_library_is_refused
data = Zlib.gzip(Gem::Package::TarWriter.new(StringIO.new).then { |t| t.add_file_simple('other', 0o644, 0) { |io| io }; t.close; '' })
assert_raises(RuntimeError) { FasterPath::Prebuilt.unpack(data, Dir.mktmpdir) }
end

def test_cargo_is_found_on_the_path
assert FasterPath::BuildTask.cargo?

original = ENV['PATH']
ENV['PATH'] = Dir.mktmpdir
refute FasterPath::BuildTask.cargo?
ensure
ENV['PATH'] = original
end
end
Loading