From 28b6a4c93d25619c01803e3bddd4a8391b8838f2 Mon Sep 17 00:00:00 2001 From: Thomas Sawyer Date: Wed, 25 Nov 2026 14:21:57 -0500 Subject: [PATCH 1/2] Modernize: gemspec, CI, tests on Spectrum Reloader#update is public, the interval may be fractional, modification times are compared in full, and a file that fails to reload is not tried again until it changes. The Ruby 1.8 code is gone. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 30 ++++ .gitignore | 1 + .index | 68 -------- .travis.yml | 14 -- Assembly | 35 ---- Gemfile | 16 +- HISTORY.md | 192 +++++++++++---------- Index.rb | 27 --- Manifest.txt | 14 -- README.md | 42 +++-- Rakefile | 25 +-- autoreload.gemspec | 337 ++++--------------------------------- lib/autoreload/reloader.rb | 331 +++++++++++++++++------------------- lib/autoreload/version.rb | 2 +- spec/autoreload_spec.rb | 34 ---- spec/helper.rb | 29 ---- spec/require_spec.rb | 37 ---- test/case_autoreload.rb | 168 ++++++++++++++++++ test/helper.rb | 38 +++++ 19 files changed, 581 insertions(+), 859 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .index delete mode 100644 .travis.yml delete mode 100644 Assembly delete mode 100644 Index.rb delete mode 100644 Manifest.txt delete mode 100644 spec/autoreload_spec.rb delete mode 100644 spec/helper.rb delete mode 100644 spec/require_spec.rb create mode 100644 test/case_autoreload.rb create mode 100644 test/helper.rb diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8d5fbaa --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + # Monthly, to catch breakage from new Ruby or dependency releases + # when nothing has been pushed. + schedule: + - cron: '0 6 1 * *' + +permissions: + contents: read + +jobs: + test: + name: Ruby ${{ matrix.ruby }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ruby: ['3.1', '3.2', '3.3', '3.4', '4.0'] + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Tests + run: bundle exec rake test diff --git a/.gitignore b/.gitignore index 1811afc..5b452f2 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ tmp doc web *.gem +Gemfile.lock diff --git a/.index b/.index deleted file mode 100644 index 460a0f0..0000000 --- a/.index +++ /dev/null @@ -1,68 +0,0 @@ ---- -revision: 2013 -type: ruby -sources: -- Index.rb -- Gemfile -authors: -- name: Thomas Sawyer - email: transfire@gmail.com -- name: Kouichirou Eto -organizations: [] -requirements: -- groups: - - development - version: '>= 0' - name: rake -- groups: - - test - version: '>= 0' - name: minitest -- engines: - - name: rbx - version: 0+ - version: '>= 0' - name: psych -- engines: - - name: rbx - version: 0+ - version: ~> 2.0 - name: rubysl -- engines: - - name: rbx - version: 0+ - version: '>= 0' - name: minitest -conflicts: [] -alternatives: [] -resources: -- type: home - uri: http://rubyworks.github.com/autoreload - label: Homepage -- type: code - uri: http://github.com/rubyworks/autoreload - label: Source Code -- type: gems - uri: http://rubygems.org/gems/autoreload -repositories: [] -categories: [] -copyrights: -- holder: Thomas Sawyer - year: '2010' - license: BSD-2-Clause -- holder: Kouichiro Eto - year: '2003' - license: RUBY -customs: [] -paths: - lib: - - lib -version: 1.2.0 -name: autoreload -title: AutoReload -summary: Automatically reload library files -description: Autoreload automatically reloads library files when they have been updated. - It is especially useful when testing stateless services such as web applications. -created: '2007-07-01' -webcvs: https://github.com/rubyworks/autoreload/tree/master -date: '2015-05-07' diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0f942b9..0000000 --- a/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ ---- -language: ruby -script: "bundle exec rake test" -rvm: - - 1.9.3 - - 2.0.0 - - 2.1.1 - - rbx - - jruby -matrix: - allow_failures: - - rvm: rbx -cache: bundler - diff --git a/Assembly b/Assembly deleted file mode 100644 index 63d9efd..0000000 --- a/Assembly +++ /dev/null @@ -1,35 +0,0 @@ ---- -email: - mailto : - - ruby-talk@ruby-lang.org - - rubyworks-mailinglist@googlegroups.com - -gem: - active: true - -github: - gh_pages: web - -yard: - yardopts: true - priority: 2 - -minitest: - tests : spec/*_spec.rb - loadpath : lib - requires : ~ - active : true - -dnote: - labels: ~ - output: log/DNOTE.rdoc - -vclog: - output: - - log/Changes.rdoc - - log/History.rdoc - -#locat: -# path: lib,test -# output: log/LOCat.html - diff --git a/Gemfile b/Gemfile index 91420db..3be9c3c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,16 +1,2 @@ source "https://rubygems.org" - -group :development do - #gem 'detroit' - gem 'rake' -end - -group :test do - gem 'minitest' -end - -platforms :rbx do - gem 'psych' # yaml - gem 'rubysl', '~> 2.0' - gem 'minitest' -end +gemspec diff --git a/HISTORY.md b/HISTORY.md index d933f41..5b57f0a 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,85 +1,107 @@ -# RELEASE HISTORY - -## 1.2.0 - -Add `watch_gems` option to watch all required gems. The default -is now to only watch `.rb` files in the current working directory. - -Changes: - -* Add `:watch_gems` option. -* Watch current working directory only, as default. - - -## 1.1.0 - -This release is simply a maintenance release to bring the build -configuration up to date. - -Changes: - -* Modernize build configuration. -* Use interpolation on error message. - - -## 1.0.0 (2011-07-16) - -This release overhauls the API. The #autoreload method now -takes a block. All libraries required within this block -will be autoreloaded. The old API will raise an error!!! -This was done to simplify the overaul design of the library -and consequently make it much more efficient, but also to -fix a rather nasty bug that prevented scripts required by -other scripts that were to be autoreloaded from autoreloading -as well. - -The new design rely's solely on $LOADED_FEATURES, rather than -looking up files on the $LOAD_PATH itself. This has an important -consequence for Ruby 1.8 or older. Becuase older version of Ruby -do not put the expanded path in $LOADED_FEATURES, autoreloading -occurs regardless of whether the file has changed or not. On -Ruby 1.9+ however, where the full path is available, the file will -only be reloaded if it has changed, it does this by checking the -mtime of the file. - -Changes: - -* Overhaul API to use block form. -* Remove Lookup module (no longer needed). -* Fix require of require issue. - - -## 0.3.1 (2011-05-15) - -This release simply fixes licensing issues. Autoreload is licensed -under the GPL v3. - - -## 0.3.0 (2010-10-14) - -Changes: - -* Fix issue with looking up Roller libraries. -* Switch testing framework to RSpec2. - - -## 0.2.0 (2010-05-10) - -Changes: - -* Completely reworked API. - - -## 0.1.0 (2010-05-01) - -Changes: - -* Same as original, but now a RubyWorks project. - - -## 0.0.1 (2007-07-01) - -Changes: - -* Initial release - +# RELEASE HISTORY + +## Unreleased (1.3.0) + +A maintenance release, for Ruby 3.1 and up. + +Changes: + +* `Reloader#update` is public, to check for changes at once without + the thread. +* The interval can be a fraction of a second. Before, it was rounded + down, and an interval under one second made the thread spin. +* The list of watched files in verbose mode goes to standard error, + as the reload reports do. +* Drop the code for Ruby 1.8. +* Tests run on Spectrum. + +Fixes: + +* A change made in the same second as the last load was missed, as + times were compared in whole seconds. +* A file that failed to reload was tried again at every interval. + + +## 1.2.0 + +Add `watch_gems` option to watch all required gems. The default +is now to only watch `.rb` files in the current working directory. + +Changes: + +* Add `:watch_gems` option. +* Watch current working directory only, as default. + + +## 1.1.0 + +This release is simply a maintenance release to bring the build +configuration up to date. + +Changes: + +* Modernize build configuration. +* Use interpolation on error message. + + +## 1.0.0 (2011-07-16) + +This release overhauls the API. The #autoreload method now +takes a block. All libraries required within this block +will be autoreloaded. The old API will raise an error!!! +This was done to simplify the overaul design of the library +and consequently make it much more efficient, but also to +fix a rather nasty bug that prevented scripts required by +other scripts that were to be autoreloaded from autoreloading +as well. + +The new design rely's solely on $LOADED_FEATURES, rather than +looking up files on the $LOAD_PATH itself. This has an important +consequence for Ruby 1.8 or older. Becuase older version of Ruby +do not put the expanded path in $LOADED_FEATURES, autoreloading +occurs regardless of whether the file has changed or not. On +Ruby 1.9+ however, where the full path is available, the file will +only be reloaded if it has changed, it does this by checking the +mtime of the file. + +Changes: + +* Overhaul API to use block form. +* Remove Lookup module (no longer needed). +* Fix require of require issue. + + +## 0.3.1 (2011-05-15) + +This release simply fixes licensing issues. Autoreload is licensed +under the GPL v3. + + +## 0.3.0 (2010-10-14) + +Changes: + +* Fix issue with looking up Roller libraries. +* Switch testing framework to RSpec2. + + +## 0.2.0 (2010-05-10) + +Changes: + +* Completely reworked API. + + +## 0.1.0 (2010-05-01) + +Changes: + +* Same as original, but now a RubyWorks project. + + +## 0.0.1 (2007-07-01) + +Changes: + +* Initial release + diff --git a/Index.rb b/Index.rb deleted file mode 100644 index 006dcff..0000000 --- a/Index.rb +++ /dev/null @@ -1,27 +0,0 @@ -#!usr/bin/env ruby - -require File.dirname(__FILE__) + '/lib/autoreload/version' - - version AutoReload::VERSION - - name 'autoreload' - title 'AutoReload' - summary 'Automatically reload library files' - - description 'Autoreload automatically reloads library files when they have been ' + - 'updated. It is especially useful when testing stateless services ' + - 'such as web applications.' - - authors 'Thomas Sawyer ', - 'Kouichirou Eto' - - resources 'home' => 'http://rubyworks.github.com/autoreload', - 'code' => 'http://github.com/rubyworks/autoreload', - 'gems' => 'http://rubygems.org/gems/autoreload' - - created '2007-07-01' - - copyrights '2010 Thomas Sawyer (BSD-2-Clause)', - '2003 Kouichiro Eto (RUBY)' - - webcvs 'https://github.com/rubyworks/autoreload/tree/master' diff --git a/Manifest.txt b/Manifest.txt deleted file mode 100644 index 721069b..0000000 --- a/Manifest.txt +++ /dev/null @@ -1,14 +0,0 @@ -#!mast .index .yardopts bin data demo lib man spec test try [A-Z]*.* -.index -.yardopts -lib/autoreload/reloader.rb -lib/autoreload/version.rb -lib/autoreload.rb -spec/autoreload_spec.rb -spec/helper.rb -spec/require_spec.rb -try/changeme.rb -try/tryme.rb -LICENSE.md -HISTORY.md -README.md diff --git a/README.md b/README.md index 515e1ac..5b2315f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ # AutoReload -[Homepage](http://rubyworks.github.com/autoreload) | -[Development](http://github.com/rubyworks/autoreload) | -[Mailing List](http://groups.google.com/group/rubyworks-mailinglist) - -[![Build Status](https://secure.travis-ci.org/rubyworks/autoreload.png)](http://travis-ci.org/rubyworks/autoreload) +[Source Code](https://github.com/rubyworks/autoreload) / +[Report Issue](https://github.com/rubyworks/autoreload/issues)     +[![CI](https://github.com/rubyworks/autoreload/actions/workflows/ci.yml/badge.svg)](https://github.com/rubyworks/autoreload/actions/workflows/ci.yml) ## Description @@ -13,11 +11,9 @@ Autoreload automatically reloads library files after they have been updated. It is especially useful when testing stateless services such as web applications. -IMPORTANT! Version 1.0+ has a new API. It also works best -under Ruby 1.9 or above. Under Ruby 1.8 or older files are -reloaded regardless of whether they actually have changed -since the last load. Whereas in Ruby 1.9+, they only reload -if the mtime on the file is newer than the previous time. +It needs Ruby 3.1 or newer. + + $ gem install autoreload ## Synopsis @@ -49,11 +45,33 @@ Note that autoreload only works with _required_ files. It cannot monitor files that are brought in with `#load`. This is because `$LOADED_FEATURES` is used to track which files are monitored. +Only `.rb` files under the current working directory are watched. To +watch everything the block requires, gems included, pass +`:watch_gems=>true`. With `:verbose=>true` the watched files are listed +and each reload is reported, to standard error. + +A changed file is loaded again, on top of what is already defined. +Nothing is removed first, so a method or constant deleted from the file +stays until the program restarts. + + +## Doing it by hand + +`autoreload` starts a thread and returns it. To check for changes when +you choose instead, or to stop the checking, use a reloader directly: + + reloader = AutoReload::Reloader.new{ require 'foo' } + + reloader.update # reload whatever has changed, now + + reloader.start # or check every interval, in a thread + reloader.stop + ## Acknowledgements -The current version of Autoreload is a derviative of Kouichirou Eto's original -work which can still be found at http://autoreload.rubyforge.org. +The current version of Autoreload is a derivative of Kouichirou Eto's original +work. ## License & Copyrights diff --git a/Rakefile b/Rakefile index 5ee198c..3d0f16c 100644 --- a/Rakefile +++ b/Rakefile @@ -1,16 +1,21 @@ -require 'rake/testtask' +require 'rake/clean' +CLOBBER.include 'pkg' -task :default => [:test] +require 'bundler/gem_helper' -Rake::TestTask.new do |t| - t.libs << "lib" - t.libs << "tmp" - t.test_files = FileList['spec/*_spec.rb'] - t.verbose = false +# Bundler tags releases as v1.2.3, but Autoreload's tags have always been +# plain version numbers, so keep it that way. +class Bundler::GemHelper + def version_tag + version.to_s + end end -desc "git pull origin master" -task :pull do - sh "git pull origin master" +Bundler::GemHelper.install_tasks + +desc 'run tests' +task 'test' do + sh 'rubytest -Ilib -r spectrum/testcase -r ./test/helper test/case_*.rb' end +task 'default' => 'test' diff --git a/autoreload.gemspec b/autoreload.gemspec index ea0db60..58f4bfa 100644 --- a/autoreload.gemspec +++ b/autoreload.gemspec @@ -1,307 +1,32 @@ -# encoding: utf-8 - -require 'yaml' -require 'pathname' - -module Indexer - - # Convert index data into a gemspec. - # - # Notes: - # * Assumes all executables are in bin/. - # * Does not yet handle default_executable setting. - # * Does not yet handle platform setting. - # * Does not yet handle required_ruby_version. - # * Support for rdoc entries is weak. - # - class GemspecExporter - - # File globs to include in package --unless a manifest file exists. - FILES = ".index .yardopts alt bin data demo ext features lib man spec test try* [A-Z]*.*" unless defined?(FILES) - - # File globs to omit from FILES. - OMIT = "Config.rb" unless defined?(OMIT) - - # Standard file patterns. - PATTERNS = { - :root => '{.index,Gemfile}', - :bin => 'bin/*', - :lib => 'lib/{**/}*', #.rb', - :ext => 'ext/{**/}extconf.rb', - :doc => '*.{txt,rdoc,md,markdown,tt,textile}', - :test => '{test,spec}/{**/}*.rb' - } unless defined?(PATTERNS) - - # For which revision of indexer spec is this converter intended? - REVISION = 2013 unless defined?(REVISION) - - # - def self.gemspec - new.to_gemspec - end - - # - attr :metadata - - # - def initialize(metadata=nil) - @root_check = false - - if metadata - root_dir = metadata.delete(:root) - if root_dir - @root = root_dir - @root_check = true - end - metadata = nil if metadata.empty? - end - - @metadata = metadata || YAML.load_file(root + '.index') - - if @metadata['revision'].to_i != REVISION - warn "This gemspec exporter was not designed for this revision of index metadata." - end - end - - # - def has_root? - root ? true : false - end - - # - def root - return @root if @root || @root_check - @root_check = true - @root = find_root - end - - # - def manifest - return nil unless root - @manifest ||= Dir.glob(root + 'manifest{,.txt}', File::FNM_CASEFOLD).first - end - - # - def scm - return nil unless root - @scm ||= %w{git hg}.find{ |m| (root + ".#{m}").directory? }.to_sym - end - - # - def files - return [] unless root - @files ||= \ - if manifest - File.readlines(manifest). - map{ |line| line.strip }. - reject{ |line| line.empty? || line[0,1] == '#' } - else - list = [] - Dir.chdir(root) do - FILES.split(/\s+/).each do |pattern| - list.concat(glob(pattern)) - end - OMIT.split(/\s+/).each do |pattern| - list = list - glob(pattern) - end - end - list - end.select{ |path| File.file?(path) }.uniq - end - - # - def glob_files(pattern) - return [] unless root - Dir.chdir(root) do - Dir.glob(pattern).select do |path| - File.file?(path) && files.include?(path) - end - end - end - - def patterns - PATTERNS - end - - def executables - @executables ||= \ - glob_files(patterns[:bin]).map do |path| - File.basename(path) - end - end - - def extensions - @extensions ||= \ - glob_files(patterns[:ext]).map do |path| - File.basename(path) - end - end - - def name - metadata['name'] || metadata['title'].downcase.gsub(/\W+/,'_') - end - - def homepage - page = ( - metadata['resources'].find{ |r| r['type'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^web/i } - ) - page ? page['uri'] : false - end - - def licenses - metadata['copyrights'].map{ |c| c['license'] }.compact - end - - def require_paths - paths = metadata['paths'] || {} - paths['load'] || ['lib'] - end - - # - # Convert to gemnspec. - # - def to_gemspec - if has_root? - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - else - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - end - end - - # - # Convert pure data settings. - # - def to_gemspec_data(gemspec) - gemspec.name = name - gemspec.version = metadata['version'] - gemspec.summary = metadata['summary'] - gemspec.description = metadata['description'] - - metadata['authors'].each do |author| - gemspec.authors << author['name'] - - if author.has_key?('email') - if gemspec.email - gemspec.email << author['email'] - else - gemspec.email = [author['email']] - end - end - end - - gemspec.licenses = licenses - - requirements = metadata['requirements'] || [] - requirements.each do |req| - next if req['optional'] - next if req['external'] - - name = req['name'] - groups = req['groups'] || [] - - version = gemify_version(req['version']) - - if groups.empty? or groups.include?('runtime') - # populate runtime dependencies - if gemspec.respond_to?(:add_runtime_dependency) - gemspec.add_runtime_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - else - # populate development dependencies - if gemspec.respond_to?(:add_development_dependency) - gemspec.add_development_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - end - end - - # convert external dependencies into gemspec requirements - requirements.each do |req| - next unless req['external'] - gemspec.requirements << ("%s-%s" % req.values_at('name', 'version')) - end - - gemspec.homepage = homepage - gemspec.require_paths = require_paths - gemspec.post_install_message = metadata['install_message'] - end - - # - # Set gemspec settings that require a root directory path. - # - def to_gemspec_paths(gemspec) - gemspec.files = files - gemspec.extensions = extensions - gemspec.executables = executables - - if Gem::VERSION < '1.7.' - gemspec.default_executable = gemspec.executables.first - end - - gemspec.test_files = glob_files(patterns[:test]) - - unless gemspec.files.include?('.document') - gemspec.extra_rdoc_files = glob_files(patterns[:doc]) - end - end - - # - # Return a copy of this file. This is used to generate a local - # .gemspec file that can automatically read the index file. - # - def self.source_code - File.read(__FILE__) - end - - private - - def find_root - root_files = patterns[:root] - if Dir.glob(root_files).first - Pathname.new(Dir.pwd) - elsif Dir.glob("../#{root_files}").first - Pathname.new(Dir.pwd).parent - else - #raise "Can't find root of project containing `#{root_files}'." - warn "Can't find root of project containing `#{root_files}'." - nil - end - end - - def glob(pattern) - if File.directory?(pattern) - Dir.glob(File.join(pattern, '**', '*')) - else - Dir.glob(pattern) - end - end - - def gemify_version(version) - case version - when /^(.*?)\+$/ - ">= #{$1}" - when /^(.*?)\-$/ - "< #{$1}" - when /^(.*?)\~$/ - "~> #{$1}" - else - version - end - end - - end - +require_relative 'lib/autoreload/version' + +Gem::Specification.new do |s| + s.name = 'autoreload' + s.version = AutoReload::VERSION + s.summary = 'Automatically reload library files' + s.description = 'Autoreload automatically reloads library files when they have ' \ + 'been updated. It is especially useful when testing stateless ' \ + 'services such as web applications.' + + s.authors = ['Trans', 'Kouichirou Eto'] + s.email = ['transfire@gmail.com'] + s.homepage = 'https://github.com/rubyworks/autoreload' + s.license = 'BSD-2-Clause' + + s.metadata = { + 'source_code_uri' => 'https://github.com/rubyworks/autoreload', + 'bug_tracker_uri' => 'https://github.com/rubyworks/autoreload/issues', + 'changelog_uri' => 'https://github.com/rubyworks/autoreload/blob/master/HISTORY.md', + 'documentation_uri' => 'https://rubydoc.info/gems/autoreload' + } + + s.required_ruby_version = '>= 3.1' + + s.files = Dir['lib/**/*.rb', 'README.md', 'HISTORY.md', 'LICENSE.md'] + s.require_paths = ['lib'] + + s.add_development_dependency 'rake', '>= 13' + s.add_development_dependency 'rubytest', '>= 0.11.1' + s.add_development_dependency 'spectrum', '>= 0.2' + s.add_development_dependency 'assay', '>= 0.5.1' end - -Indexer::GemspecExporter.gemspec \ No newline at end of file diff --git a/lib/autoreload/reloader.rb b/lib/autoreload/reloader.rb index f647fb4..d702832 100644 --- a/lib/autoreload/reloader.rb +++ b/lib/autoreload/reloader.rb @@ -1,172 +1,159 @@ -require 'thread' - -module AutoReload - - # Reload class does all the heavy lifting - # for AutoReload library. - # - class Reloader - - # Public: Shortcut for Reloader.new(*args).start. - def self.start(*args, &block) - self.new(*args, &block).start - end - - # Public: Default interval is one second. - DEFAULT_INTERVAL = 1 - - # New Reloader. - # - # options - The Hash options used to refine the reloader (default: {}): - # :interval - Seconds between updates. - # :verbose - True provides reload warning. - # :reprime - Include $0 in reload list. - # - def initialize(options={}, &block) - @interval = (options[:interval] || DEFAULT_INTERVAL).to_i - @verbose = (options[:verbose]) - @reprime = (options[:reprime]) - @watch_gems = (options[:watch_gems]) - - @status = {} - - features = $".dup - if block - block.call - @files = ($" - features).select do |f| - (@watch_gems ? true : f.start_with?(Dir.pwd)) && f.end_with?(".rb") - end.reverse - - if @verbose - puts "watching files:" - puts "---------------" - puts @files - puts "---------------" - end - else - @files = [] - end - end - - # Public: Start the reload thread. - def start - update # prime the path loads - @thread = Thread.new do - loop do - begin - update - rescue Exception - warn "autoreload failed unexpectedly: #{$!}" - end - sleep @interval - end - end - @thread.abort_on_exception = true - @thread - end - - # Public: Kills the autoreload thread. - def stop - @thread.kill if @thread - end - - # Public: References the reload thread. - attr :thread - - # Public: List of files provided to autoreload. - attr :files - - # Public: Status hash, used to track reloads. - attr :status - - # Public: The periodic interval of reload in seconds. - attr :interval - - # Public: Provide warning on reload. - # - # Returns true/false if versboe mode. - def verbose? - @verbose || $VERBOSE - end - - # Public: Put $0 in the reload list? - # - # Returns true/false whether to include $0. - def reprime? - @reprime - end - - private - - # TODO: Why include $0 in #libraries ? - - # The library files to autoreload. - def libraries - if @files.empty? - @reprime ? [$0] + $" : $" - else - @files - end - end - - # Iterate through all selection library files and reload if needed. - def update - libraries.each{ |lib| check(lib) } - end - - # Check status and reload if out-of-date. - # - # We can't check mtime under 1.8 b/c $LOADED_FEATURES does not - # store the full path. - # - # lib - A library file. - # - # Returns Array of [file, mtime]. - def check(lib) - if RUBY_VERSION < '1.9' - warn "reload: '#{lib}'" if verbose? - begin - load lib - rescue LoadError - # file has been removed - end - else - file, mtime = @status[lib] - if file - if FileTest.exist?(file) - curtime = File.mtime(file).to_i - if mtime < curtime - warn "reload: '#{file}'" if verbose? - load file - @status[lib] = [file, curtime] - end - else - # file has been removed - end - else - @status[lib] = get_status(lib) - end - end - end - - # Get library file status. - # - # file - The file path from which to get status. - # - # Returns Array of [file, mtime] or [nil, nil] if file not found. - def get_status(file) - if FileTest.exist?(file) - [file, File.mtime(file).to_i] - else - warn "reload fail: library '#{file}' not found" if verbose? - #raise "The library '#{file}' is not found." - #$stdout.puts(message("The library '#{file}' is not found.")) if @verbose - [nil, nil] - end - end - - end - -end - -# Copyright (C) 2010 Rubyworks (BSD-2-Clause) +module AutoReload + + # Reload class does all the heavy lifting + # for AutoReload library. + # + class Reloader + + # Public: Shortcut for Reloader.new(*args).start. + def self.start(*args, &block) + self.new(*args, &block).start + end + + # Public: Default interval is one second. + DEFAULT_INTERVAL = 1 + + # New Reloader. + # + # options - The Hash options used to refine the reloader (default: {}): + # :interval - Seconds between updates. + # :verbose - True provides reload warning. + # :reprime - Include $0 in reload list. + # + def initialize(options={}, &block) + @interval = (options[:interval] || DEFAULT_INTERVAL).to_f + @verbose = (options[:verbose]) + @reprime = (options[:reprime]) + @watch_gems = (options[:watch_gems]) + + @status = {} + + features = $".dup + if block + block.call + @files = ($" - features).select do |f| + (@watch_gems ? true : f.start_with?(Dir.pwd)) && f.end_with?(".rb") + end.reverse + + if @verbose + warn "watching files:" + warn "---------------" + warn @files + warn "---------------" + end + else + @files = [] + end + end + + # Public: Start the reload thread. + def start + update # prime the path loads + @thread = Thread.new do + loop do + begin + update + rescue ScriptError, StandardError + warn "autoreload failed unexpectedly: #{$!}" + end + sleep @interval + end + end + @thread.abort_on_exception = true + @thread + end + + # Public: Kills the autoreload thread. + def stop + @thread.kill if @thread + end + + # Public: References the reload thread. + attr :thread + + # Public: List of files provided to autoreload. + attr :files + + # Public: Status hash, used to track reloads. + attr :status + + # Public: The periodic interval of reload in seconds. + attr :interval + + # Public: Provide warning on reload. + # + # Returns true/false if versboe mode. + def verbose? + @verbose || $VERBOSE + end + + # Public: Put $0 in the reload list? + # + # Returns true/false whether to include $0. + def reprime? + @reprime + end + + + + # The library files to autoreload. + def libraries + if @files.empty? + @reprime ? [$0] + $" : $" + else + @files + end + end + + # Check every watched file and reload those that have changed. + def update + libraries.each{ |lib| check(lib) } + end + + private :libraries + + private + + # Check status and reload if out-of-date. + # + # lib - A library file. + # + def check(lib) + file, mtime = @status[lib] + if file + if FileTest.exist?(file) + curtime = File.mtime(file) + if mtime < curtime + warn "reload: '#{file}'" if verbose? + @status[lib] = [file, curtime] + load file + end + else + # file has been removed + end + else + @status[lib] = get_status(lib) + end + end + + # Get library file status. + # + # file - The file path from which to get status. + # + # Returns Array of [file, mtime] or [nil, nil] if file not found. + def get_status(file) + if FileTest.exist?(file) + [file, File.mtime(file)] + else + warn "reload fail: library '#{file}' not found" if verbose? + #raise "The library '#{file}' is not found." + #$stdout.puts(message("The library '#{file}' is not found.")) if @verbose + [nil, nil] + end + end + + end + +end + +# Copyright (C) 2010 Rubyworks (BSD-2-Clause) diff --git a/lib/autoreload/version.rb b/lib/autoreload/version.rb index b8b5330..0d74fa5 100644 --- a/lib/autoreload/version.rb +++ b/lib/autoreload/version.rb @@ -1,4 +1,4 @@ module AutoReload # Public: Current release version. - VERSION = '1.2.0' + VERSION = '1.3.0' end diff --git a/spec/autoreload_spec.rb b/spec/autoreload_spec.rb deleted file mode 100644 index 4453225..0000000 --- a/spec/autoreload_spec.rb +++ /dev/null @@ -1,34 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/helper') - -describe "AutoReload" do - - it "should autoreload" do - # create a library - library = Pathname.new('tmp/library.rb') - library.write 'def foo; 1; end' - - # setup the autoreload - autoreload(:interval => 1) do #, :verbose=>true) - require "library" - end - - # check the number - foo.must_equal 1 - - # wait is needed for time stamp to not be same with the next file. - sleep 2 - - # recreate the file - library.write 'def foo; 2; end' - - # wait again for the autoreload loop to repeat. - sleep 2 - - # check the number again - foo.must_equal 2 - - # clean up - library.delete - end - -end diff --git a/spec/helper.rb b/spec/helper.rb deleted file mode 100644 index d3860d0..0000000 --- a/spec/helper.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'minitest/spec' -require 'minitest/autorun' - -require 'fileutils' -require 'pathname' -require 'autoreload' - -# Some helper stuff.... - -# create a tmp directory -FileUtils.mkdir('tmp') unless File.exist?('tmp') - -$LOAD_PATH.unshift 'lib' -$LOAD_PATH.unshift 'tmp' - -class Pathname - def write(str) - self.open('w') {|out| - out.puts str - } - end -end - -module AutoReload - class Reloader - public :warn - end -end - diff --git a/spec/require_spec.rb b/spec/require_spec.rb deleted file mode 100644 index 26317e2..0000000 --- a/spec/require_spec.rb +++ /dev/null @@ -1,37 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/helper') - -describe "AutoReload" do - - it "should autoreload a require of a require" do - library1 = Pathname.new('tmp/library1.rb') - library2 = Pathname.new('tmp/library2.rb') - - library1.write "require 'library2'" - library2.write "def foo; 1; end" - - # setup the autoreload - autoreload(:interval => 1) do #, :verbose=>true) - require "library1" - end - - # check the number - foo.must_equal 1 - - # wait is needed for time stamp to not be same with the next file. - sleep 2 - - # recreate the file - library2.write "def foo; 2; end" - - # wait again for the autoreload loop to repeat. - sleep 2 - - # check the number again - foo.must_equal 2 - - # clean up - library2.delete - library1.delete - end - -end diff --git a/test/case_autoreload.rb b/test/case_autoreload.rb new file mode 100644 index 0000000..19f04cc --- /dev/null +++ b/test/case_autoreload.rb @@ -0,0 +1,168 @@ +testcase AutoReload::Reloader do + + test "it watches the files required in its block" do + library_dir do |dir| + write_file('ar_watch.rb', 'def ar_watch; 1; end') + reloader = AutoReload::Reloader.new{ require 'ar_watch' } + reloader.files.assert == [File.join(dir, 'ar_watch.rb')] + end + end + + test "a changed file is reloaded" do + library_dir do + write_file('ar_change.rb', 'def ar_change; 1; end') + reloader = AutoReload::Reloader.new{ require 'ar_change' } + reloader.update + ar_change.assert == 1 + + write_file('ar_change.rb', 'def ar_change; 2; end', 10) + reloader.update + ar_change.assert == 2 + end + end + + test "a file that has not changed is not loaded again" do + library_dir do + write_file('ar_same.rb', '$ar_same = ($ar_same || 0) + 1') + reloader = AutoReload::Reloader.new{ require 'ar_same' } + reloader.update + reloader.update + $ar_same.assert == 1 + end + end + + test "a file required by a required file is watched too" do + library_dir do + write_file('ar_outer.rb', "require 'ar_inner'") + write_file('ar_inner.rb', 'def ar_inner; 1; end') + reloader = AutoReload::Reloader.new{ require 'ar_outer' } + reloader.update + ar_inner.assert == 1 + + write_file('ar_inner.rb', 'def ar_inner; 2; end', 10) + reloader.update + ar_inner.assert == 2 + end + end + + test "a change within the same second is seen" do + library_dir do + write_file('ar_quick.rb', 'def ar_quick; 1; end', -5) + reloader = AutoReload::Reloader.new{ require 'ar_quick' } + reloader.update + + File.write('ar_quick.rb', 'def ar_quick; 2; end') + base = File.mtime('ar_quick.rb').floor - 5 + File.utime(base + 0.25, base + 0.25, 'ar_quick.rb') + reloader.update + File.write('ar_quick.rb', 'def ar_quick; 3; end') + File.utime(base + 0.75, base + 0.75, 'ar_quick.rb') + reloader.update + ar_quick.assert == 3 + end + end + + test "a file outside the working directory is not watched, unless gems are" do + library_dir do |dir| + Dir.mkdir('app') + write_file('ar_outside.rb', '$ar_outside = true') + Dir.chdir('app') do + AutoReload::Reloader.new{ require 'ar_outside' }.files.assert == [] + end + write_file('ar_outside2.rb', '$ar_outside2 = true') + Dir.chdir('app') do + reloader = AutoReload::Reloader.new(:watch_gems=>true){ require 'ar_outside2' } + reloader.files.assert == [File.join(dir, 'ar_outside2.rb')] + end + end + end + + test "a file that has been removed is passed over" do + library_dir do + write_file('ar_gone.rb', 'def ar_gone; 1; end') + reloader = AutoReload::Reloader.new{ require 'ar_gone' } + reloader.update + File.delete('ar_gone.rb') + reloader.update + ar_gone.assert == 1 + end + end + + test "verbose mode reports a reload" do + library_dir do |dir| + write_file('ar_loud.rb', 'def ar_loud; 1; end') + reloader = nil + capture_stderr{ reloader = AutoReload::Reloader.new(:verbose=>true){ require 'ar_loud' } } + reloader.update + write_file('ar_loud.rb', 'def ar_loud; 2; end', 10) + out = capture_stderr{ reloader.update } + out.assert == "reload: '#{File.join(dir, 'ar_loud.rb')}'\n" + end + end + + test "the options" do + reloader = AutoReload::Reloader.new(:interval=>0.5, :reprime=>true) + reloader.interval.assert == 0.5 + reloader.assert.reprime? + AutoReload::Reloader.new.interval.assert == 1 + AutoReload::Reloader.new.files.assert == [] + end + + test "#start runs the checks in a thread, and #stop ends it" do + library_dir do + write_file('ar_thread.rb', 'def ar_thread; 1; end') + reloader = AutoReload::Reloader.new(:interval=>0.05){ require 'ar_thread' } + thread = reloader.start + thread.assert.is_a?(Thread) + thread.assert.equal?(reloader.thread) + + write_file('ar_thread.rb', 'def ar_thread; 2; end', 10) + 20.times{ break if ar_thread == 2; sleep 0.05 } + ar_thread.assert == 2 + + reloader.stop + thread.join(1) + thread.refute.alive? + end + end + + test "a file that fails to reload is reported and the thread carries on" do + library_dir do + write_file('ar_bad.rb', 'def ar_bad; 1; end') + write_file('ar_good.rb', 'def ar_good; 1; end') + reloader = AutoReload::Reloader.new(:interval=>0.05){ require 'ar_bad'; require 'ar_good' } + out = capture_stderr do + thread = reloader.start + write_file('ar_bad.rb', 'def ar_bad; (', 10) + sleep 0.2 + write_file('ar_good.rb', 'def ar_good; 2; end', 20) + 20.times{ break if ar_good == 2; sleep 0.05 } + thread.assert.alive? + reloader.stop + end + ar_good.assert == 2 + ar_bad.assert == 1 + out.assert.include?('autoreload failed') + end + end + +end + +testcase "Kernel#autoreload" do + + test "it starts a reloader and returns its thread" do + library_dir do + write_file('ar_kernel.rb', 'def ar_kernel; 1; end') + thread = autoreload(:interval=>0.05){ require 'ar_kernel' } + begin + thread.assert.is_a?(Thread) + write_file('ar_kernel.rb', 'def ar_kernel; 2; end', 10) + 20.times{ break if ar_kernel == 2; sleep 0.05 } + ar_kernel.assert == 2 + ensure + thread.kill + end + end + end + +end diff --git a/test/helper.rb b/test/helper.rb new file mode 100644 index 0000000..1422f14 --- /dev/null +++ b/test/helper.rb @@ -0,0 +1,38 @@ +require 'assay/ae' +require 'tmpdir' +require 'stringio' +require 'autoreload' + +module Spectrum::World + + # Run a block from inside a new directory that is on the load path, + # with a way to write library files there. + def library_dir + Dir.mktmpdir('autoreload') do |dir| + dir = File.realpath(dir) + $LOAD_PATH.unshift(dir) + begin + Dir.chdir(dir){ yield dir } + ensure + $LOAD_PATH.delete(dir) + end + end + end + + # Write a file and give it a modification time +age+ seconds from now, + # so that a change is seen without having to wait for the clock. + def write_file(name, text, age=0) + File.write(name, text) + time = Time.now + age + File.utime(time, time, name) + end + + def capture_stderr + old, $stderr = $stderr, StringIO.new + yield + $stderr.string + ensure + $stderr = old + end + +end From 3796320ad68df714c2a06f3b407ffccfca1ae01e Mon Sep 17 00:00:00 2001 From: Thomas Sawyer Date: Wed, 25 Nov 2026 14:23:08 -0500 Subject: [PATCH 2/2] Fix a test that depended on the clock's fraction Co-Authored-By: Claude Fable 5.2 --- test/case_autoreload.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/case_autoreload.rb b/test/case_autoreload.rb index 19f04cc..9a15153 100644 --- a/test/case_autoreload.rb +++ b/test/case_autoreload.rb @@ -47,14 +47,18 @@ test "a change within the same second is seen" do library_dir do - write_file('ar_quick.rb', 'def ar_quick; 1; end', -5) + base = Time.at(Time.now.to_i - 5) # a whole second, in the past + + File.write('ar_quick.rb', 'def ar_quick; 1; end') + File.utime(base, base, 'ar_quick.rb') reloader = AutoReload::Reloader.new{ require 'ar_quick' } reloader.update File.write('ar_quick.rb', 'def ar_quick; 2; end') - base = File.mtime('ar_quick.rb').floor - 5 File.utime(base + 0.25, base + 0.25, 'ar_quick.rb') reloader.update + ar_quick.assert == 2 + File.write('ar_quick.rb', 'def ar_quick; 3; end') File.utime(base + 0.75, base + 0.75, 'ar_quick.rb') reloader.update