diff --git a/.gemspec b/.gemspec deleted file mode 100644 index 351d722..0000000 --- a/.gemspec +++ /dev/null @@ -1,187 +0,0 @@ -# encoding: utf-8 - -require 'yaml' - -module DotRuby - - # - class GemSpec - - # For which revision of .ruby is this gemspec intended? - REVISION = 0 - - # - PATTERNS = { - :bin_files => 'bin/*', - :lib_files => 'lib/{**/}*.rb', - :ext_files => 'ext/{**/}extconf.rb', - :doc_files => '*.{txt,rdoc,md,markdown,tt,textile}', - :test_files => '{test/{**/}*_test.rb,spec/{**/}*_spec.rb}' - } - - # - def self.instance - new.to_gemspec - end - - attr :metadata - - attr :manifest - - # - def initialize - @metadata = YAML.load_file('.ruby') - @manifest = Dir.glob('manifest{,.txt}', File::FNM_CASEFOLD).first - - if @metadata['revision'].to_i != REVISION - warn "You have the wrong revision. Trying anyway..." - end - end - - # - def scm - @scm ||= \ - case - when File.directory?('.git') - :git - end - end - - # - def files - @files ||= \ - #glob_files[patterns[:files]] - case - when manifest - File.readlines(manifest). - map{ |line| line.strip }. - reject{ |line| line.empty? || line[0,1] == '#' } - when scm == :git - `git ls-files -z`.split("\0") - else - Dir.glob('{**/}{.*,*}') # TODO: be more specific using standard locations ? - end.select{ |path| File.file?(path) } - end - - # - def glob_files(pattern) - Dir.glob(pattern).select { |path| - File.file?(path) && files.include?(path) - } - end - - # - def patterns - PATTERNS - end - - # - def executables - @executables ||= \ - glob_files(patterns[:bin_files]).map do |path| - File.basename(path) - end - end - - def extensions - @extensions ||= \ - glob_files(patterns[:ext_files]).map do |path| - File.basename(path) - end - end - - # - def name - metadata['name'] || metadata['title'].downcase.gsub(/\W+/,'_') - end - - # - def to_gemspec - Gem::Specification.new do |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 = metadata['copyrights'].map{ |c| c['license'] }.compact - - metadata['requirements'].each do |req| - name = req['name'] - version = req['version'] - groups = req['groups'] || [] - - case version - when /^(.*?)\+$/ - version = ">= #{$1}" - when /^(.*?)\-$/ - version = "< #{$1}" - when /^(.*?)\~$/ - version = "~> #{$1}" - end - - 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 a requirements - if metadata['external_dependencies'] - ##gemspec.requirements = [] unless metadata['external_dependencies'].empty? - metadata['external_dependencies'].each do |req| - gemspec.requirements << req.to_s - end - end - - # determine homepage from resources - homepage = metadata['resources'].find{ |key, url| key =~ /^home/ } - gemspec.homepage = homepage.last if homepage - - gemspec.require_paths = metadata['load_path'] || ['lib'] - gemspec.post_install_message = metadata['install_message'] - - # RubyGems specific metadata - 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_files]) - - unless gemspec.files.include?('.document') - gemspec.extra_rdoc_files = glob_files(patterns[:doc_files]) - end - end - end - - end #class GemSpec - -end - -DotRuby::GemSpec.instance 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 2eebfaf..933e7eb 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ log pkg tmp site/documentation + +Gemfile.lock +*.gem diff --git a/.ruby b/.ruby deleted file mode 100644 index 312a27b..0000000 --- a/.ruby +++ /dev/null @@ -1,99 +0,0 @@ ---- -name: ratch -spec_version: 1.0.0 -repositories: - public: git://github.com/rubyworks/ratch.git -title: Ratch -contact: trans -requires: -- group: [] - - name: facets - version: 2.9.1+ -- group: [] - - name: minitar - version: 0.5.3+ -- group: - - test - name: ko - version: 1.2.0~ -- group: - - test - name: qed - version: 0+ -- group: - - build - name: syckle - version: 0+ -resources: - code: http://github.org/rubyworks/ratch - mail: http://groups.gooogle.com/group/rubyworks-mailinglist - home: http://rubyworks.github.org/ratch -manifest: -- .ruby -- bin/ludo -- bin/ratch -- lib/ratch/batch.rb -- lib/ratch/console.rb -- lib/ratch/core_ext/facets.rb -- lib/ratch/core_ext/filetest.rb -- lib/ratch/core_ext/to_actual_filename.rb -- lib/ratch/core_ext/to_console.rb -- lib/ratch/core_ext/to_list.rb -- lib/ratch/core_ext/to_yamlfrag.rb -- lib/ratch/core_ext/unfold_paragraphs.rb -- lib/ratch/core_ext.rb -- lib/ratch/file_list.rb -- lib/ratch/script/help.rb -- lib/ratch/script.rb -- lib/ratch/shell.rb -- lib/ratch/system.rb -- lib/ratch/utils/cli.rb -- lib/ratch/utils/config.rb -- lib/ratch/utils/email.rb -- lib/ratch/utils/ftp.rb -- lib/ratch/utils/pom.rb -- lib/ratch/utils/rdoc.rb -- lib/ratch/utils/tar.rb -- lib/ratch/utils/xdg.rb -- lib/ratch/utils/zlib.rb -- lib/ratch.rb -- lib/ratch.yml -- man/ratch.1 -- spec/01_shell.rdoc -- spec/02_script.rdoc -- spec/03_batch.rdoc -- spec/04_system.rdoc -- spec/applique/array.rb -- spec/applique/setup.rb -- test/case_batch.rb -- test/case_shell.rb -- test/core_ext/case_pathname.rb -- test/helper.rb -- test/utils/case_cli.rb -- test/utils/case_config.rb -- test/utils/case_email.rb -- test/utils/case_ftp.rb -- test/utils/case_pom.rb -- test/utils/case_rdoc.rb -- test/utils/case_tar.rb -- test/utils/case_zlib.rb -- test/utils/fixtures/pom_sample/Profile -- test/utils/fixtures/rdoc_sample/README.rdoc -- test/utils/fixtures/rdoc_sample/lib/rdoc_sample/rdoc_sample.rb -- README.rdoc -- History.rdoc -- Version -- License.txt -- COPYING -version: 1.2.0 -licenses: -- Apache 2.0 -copyright: Copyright (c) 2009 Thomas Sawyer -description: Ratch is a Ruby-based batch scripting language. It's a DSL over regular Ruby to make the life of the batch script writter easier. -summary: Ruby-based Batch Scripting -organization: RubyWorks -authors: -- Trans -created: 2009-09-22 diff --git a/Assembly b/Assembly deleted file mode 100644 index b3434f4..0000000 --- a/Assembly +++ /dev/null @@ -1,95 +0,0 @@ ---- -email: - service : Email - file : ~ - subject : ~ - mailto : ruby-talk@ruby-lang.org - active : true - -grancher: - service: grancher - active: true - -gemcutter: - service: GemCutter - active: true - -box: - service: Box - types : [gem] - active : true - -ridoc: - service: RIDoc - include: ~ - exclude: ~ - active : true - -rdoc: - service : RDoc - template: newfish - output : site/documentation/api - include : ~ - exclude : [ Syckfile ] - active : true - -syntax: - service : Syntax - loadpath : ~ - exclude : ~ - active : false - -testrb: - service : testrb - tests : ~ - exclude : ~ - loadpath : ~ - requires : ~ - live : false - active : false - -dnote: - service : DNote - loadpath : ~ - labels : ~ - exclude : [work] - output : ~ - format : ~ - active : true - -stats: - service : Stats - title : ~ - loadpath : ~ - exclude : ~ - output : ~ - active : true - -vclog: - service : VClog - formats : [json] - #layout : rel # gnu - typed : false - output : ~ - active : false - - -#sow: -# service: SowGen - -#test: -# service: TestUnit - -#rdoc: -# service : RDoc -# template: ./.config/rdoc-template -# inline : true - -#rubygem: -# service: Gem -# exclude: [gen, doc/rdoc, doc/ri, log, web, work] - -#rubyforge: -# service: Rubyforge -# groupid: 6276 - diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..3be9c3c --- /dev/null +++ b/Gemfile @@ -0,0 +1,2 @@ +source "https://rubygems.org" +gemspec diff --git a/HISTORY.rdoc b/HISTORY.rdoc index e505956..da0d4da 100644 --- a/HISTORY.rdoc +++ b/HISTORY.rdoc @@ -1,5 +1,57 @@ = RELEASE HISTORY +== Unreleased (2.0.0) + +Ratch is revived, for Ruby 3.1 and up. Neither 1.2.0 nor the unreleased +code after it ran on Ruby 3: file operations failed on their options, and +the development line didn't load. + +Changes: + +* Shell no longer changes the process's working directory to do its work. + Paths are resolved against the shell's own directory, so shells at + different directories can be used side by side and from threads. Only + +cd+ with a block changes the process's directory, for the block. +* Shell does its own tracing, to standard error, with paths as they were + given. +* Shell#/ gives a new shell at the sub-directory, in the same mode. +* Shell#sh takes a command in parts as well as a string, returns whether + it succeeded, and drops the command's output in quiet mode. +* Shell#glob gives paths relative to the shell's directory. +* Shell#batch gives a Batch in the shell's mode. +* Modes can be given for one command (:noop, :trace, :dryrun). +* Batch.new takes options as its last argument; a destination is taken + from the batch's directory. +* TarUtils uses the tar reader and writer that come with RubyGems, so + minitar is no longer needed. Unpacking refuses entries that would land + outside the directory. +* EmailUtils uses the current Net::SMTP interface. +* Array#to_argv and Hash#to_argv give plain arguments, without quotes; + #to_console quotes for the shell. +* ludo is rewritten: it passes arguments on, runs the script from the + directory it was found in, reports a script it can't find, and returns + the script's exit status. +* Tests run on Spectrum. + +Fixes: + +* Batch#rm removed nothing. +* Batch#exists? and Shell#exists? used a method Ruby has dropped. +* Batch's map methods (#rename and so on) ignored their options. +* Script#define_method lost the method's name. +* FileList#ext needed Rake to be loaded. +* TarUtils failed on being included, and #untar emptied the archive. +* XDGUtils didn't report a missing xdg gem. + +Removed: + +* FTPUtils, which was unfinished and could not run. +* POMUtils, as the POM project is gone. +* Ratch::System and Ratch::Console, a stub and an unfinished console. +* FileList#pathmap, which needed Rake. +* The ShellUtils module, an unfinished refactoring. + + == 1.2.0 | 2011-01-24 Ratch has remerged with the Path gem (formerly Folio), and will be taking over diff --git a/MANIFEST b/MANIFEST deleted file mode 100644 index c5c33a9..0000000 --- a/MANIFEST +++ /dev/null @@ -1,57 +0,0 @@ -#!mast -x Syckfile -x Profile .ruby bin demo lib man spec test [A-Z]* -.ruby -bin/ludo -bin/ratch -lib/ratch/batch.rb -lib/ratch/console.rb -lib/ratch/core_ext/facets.rb -lib/ratch/core_ext/filetest.rb -lib/ratch/core_ext/to_actual_filename.rb -lib/ratch/core_ext/to_console.rb -lib/ratch/core_ext/to_list.rb -lib/ratch/core_ext/to_yamlfrag.rb -lib/ratch/core_ext/unfold_paragraphs.rb -lib/ratch/core_ext.rb -lib/ratch/file_list.rb -lib/ratch/script/help.rb -lib/ratch/script.rb -lib/ratch/shell.rb -lib/ratch/system.rb -lib/ratch/utils/cli.rb -lib/ratch/utils/config.rb -lib/ratch/utils/email.rb -lib/ratch/utils/ftp.rb -lib/ratch/utils/pom.rb -lib/ratch/utils/rdoc.rb -lib/ratch/utils/tar.rb -lib/ratch/utils/xdg.rb -lib/ratch/utils/zlib.rb -lib/ratch.rb -lib/ratch.yml -man/ratch.1 -spec/01_shell.rdoc -spec/02_script.rdoc -spec/03_batch.rdoc -spec/04_system.rdoc -spec/applique/array.rb -spec/applique/setup.rb -test/case_batch.rb -test/case_shell.rb -test/core_ext/case_pathname.rb -test/helper.rb -test/utils/case_cli.rb -test/utils/case_config.rb -test/utils/case_email.rb -test/utils/case_ftp.rb -test/utils/case_pom.rb -test/utils/case_rdoc.rb -test/utils/case_tar.rb -test/utils/case_zlib.rb -test/utils/fixtures/pom_sample/Profile -test/utils/fixtures/rdoc_sample/README.rdoc -test/utils/fixtures/rdoc_sample/lib/rdoc_sample/rdoc_sample.rb -README.rdoc -History.rdoc -Version -License.txt -COPYING diff --git a/PROFILE b/PROFILE deleted file mode 100644 index 4559a6b..0000000 --- a/PROFILE +++ /dev/null @@ -1,33 +0,0 @@ ---- -title : Ratch -summary: Ruby-based Batch Scripting -contact: trans - -requires: - - facets 2.9.1+ - - minitar 0.5.3+ - - ko 1.2.0~ (test) - - qed (test) - - syckle (build) - -description: - Ratch is a Ruby-based batch scripting language. - It's a DSL over regular Ruby to make the life - of the batch script writter easier. - -resources: - home: http://rubyworks.github.org/ratch - code: http://github.org/rubyworks/ratch - mail: http://groups.gooogle.com/group/rubyworks-mailinglist - -repositories: - public: git://github.com/rubyworks/ratch.git - -authors: - - Trans - -created : 2009-09-22 -organization : RubyWorks -license : Apache 2.0 -copyright : Copyright (c) 2009 Thomas Sawyer - diff --git a/README.rdoc b/README.rdoc index e98df35..5f1076c 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,113 +1,133 @@ -= Ratch += Ratch -Ruby-based Batch Scripts +{Source Code}[https://github.com/rubyworks/ratch] / +{Report Issue}[https://github.com/rubyworks/ratch/issues] +{CI}[https://github.com/rubyworks/ratch/actions/workflows/ci.yml] +A file system shell in code, and batch scripts in Ruby. -== Introduction +Ratch needs Ruby 3.1 or newer. -Ratch is Ruby-based DSL for building batch scripts. It's intent -is to ease the burden of batch script writers by supplementing -the standard ruby environment to be more conducive to the needs -of batch scripting. -In addition to using Ratch to write stand-alone batch scripts, -it makes a very powerful library for other applications that -require batch-like functionality. In general any program that -access the file system extensively could benefit from it's use. +== The Shell +A Ratch::Shell stands at a directory and works from there, as a shell +prompt does. Paths given to it are taken from its directory, whatever the +process's own working directory is. -== Resources + require 'ratch' -* home: http://rubyworks.github.com/ratch -* code: http://github.com/rubyworks/ratch -* talk: http://googlegroups.com/ + shell = Ratch::Shell.new('project') -== Usage + shell.file?('README.md') #=> true + shell.glob('lib/**/*.rb') #=> ["lib/project.rb", ...] + shell.read('VERSION') #=> "1.0.0\n" -=== Batch Scripting + shell.mkdir_p('tmp/cache') + shell.cp('README.md', 'tmp') + shell.write('tmp/stamp', Time.now.to_s) + shell.sh('git status') #=> true, if the command succeeded -To use for your own scripts, simply add a bang line. +It has the tests of FileTest, the operations of FileUtils (+mkdir+, +rm+, ++cp+, +mv+, +ln+, +install+, +chmod+, +touch+ and their variations), ++read+, +write+ and +append+, +glob+, and +sh+ to run a command. - #!/usr/bin/env ratch +Moving about: -On Windows, of course, you will want to associate the .ratch extension -name to the ratch executable instead. + lib = shell / 'lib' # a new shell at project/lib -=== As a Library + shell.cd('lib') # move this shell + shell.cd('..') -To use Ratch as a library, require 'ratch' and create an instance of -Ratch::Shell. + shell.cd('lib') do # move it for a block only + shell.files #=> [#, ...] + end -If you wish to extend Ratch::Shell for your application, it is recommend -that you either subclass Ratch::Shell, e.g. +A shell can be put in a mode in which it only pretends, to rehearse a +script before it touches anything: - require 'ratch' + shell = Ratch::Shell.new('project', :dryrun=>true) - class MyClass < Ratch::Shell + shell.rm_r('tmp') # prints "rm -r tmp" and removes nothing + shell.sh('make install') # prints the command and doesn't run it +The modes are :noop (change nothing), :trace (report +each step to standard error), :dryrun (both) and :quiet. +The first three can also be given to a single command: - end + shell.rm('old.txt', :dryrun=>true) -Or delegate to a Ratch::Shell instance, e.g. +To build on it, subclass Ratch::Shell, or keep one and delegate to it. - require 'ratch' - class MyClass +== Batches - def initialize(path) - @shell = Ratch::Shell.new(path) - end +A Ratch::Batch does the same over a list of files. - end + batch = shell.batch('**/*.txt') -For details on all the functionality Ratch provides, please refer to -the API documentation. + batch.file? # are they all files? + batch.cp('backup') + batch.rename{ |name| name.sub('.txt', '.text') } +It keeps its files in a Ratch::FileList, which is Rake's lazy file list: +patterns are resolved when the list is first read, and version control +directories, backup and core files are left out. -== Bonus Feature -Ratch also includes the `ludo` command, which stands for "lookup and do". -It will ascend up the directory tree searching for a matching executable -script. If it finds one it will execute the script relative the currently -ascended directory. +== Scripts +The +ratch+ command runs a Ruby script inside a shell at the present +directory, so the script can use all of the above without a receiver. -== Installation + #!/usr/bin/env ratch -Standard installation procedure apply. + glob('*.md').each do |file| + cp file, 'site' + end - $ gem install ratch + sh 'rsync -a site/ host:/var/www' -or manually using Setup.rb +The shell's modes can be given on the command line, and anything else is +in +arguments+: - $ tar -xzf ratch-1.0.0.tgz - $ cd ratch-1.0.0 - $ setup.rb + $ ./publish.ratch --dryrun -== Development +== Utilities -Ratch is hosted on GitHub. +These modules add to a shell when included in a subclass: -To pull the 'ratch' repository anonymously, use: +Ratch::ZlibUtils:: +gzip+ and +ungzip+ +Ratch::TarUtils:: +tar+, +untar+, +tar_gzip+ and +untar_gzip+ +Ratch::ConfigUtils:: +configuration+, to load a YAML file +Ratch::RDocUtils:: +rdoc+, to generate documentation (needs the +rdoc+ gem on Ruby 4) +Ratch::EmailUtils:: +email+, to send a message by SMTP (needs the +net-smtp+ gem) +Ratch::XDGUtils:: +xdg+ (needs the +xdg+ gem) +Ratch::CLI:: takes options and +arguments+ from the command line - git clone git://github.com/rubyworks/ratch.git - +The email delivery itself is not covered by the tests. -== Copying -Copyright (c) 2008 Thomas Sawyer +== ludo + +Ratch also comes with the +ludo+ command, which stands for "lookup and +do". It looks for an executable script by name in the present directory +and then in each directory above it, and runs the first it finds, from +the directory it is in. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this program except in compliance with the License. -You may obtain a copy of the License at + $ cd project/lib/project + $ ludo script/test --verbose # runs project/script/test - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. +== Installation + + $ gem install ratch + + +== Copying +Copyright (c) 2008 Thomas Sawyer, Rubyworks +Ratch is distributed under the terms of the Apache License, Version 2.0. +See LICENSE.txt for details. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..c99915c --- /dev/null +++ b/Rakefile @@ -0,0 +1,21 @@ +require 'rake/clean' +CLOBBER.include 'pkg' + +require 'bundler/gem_helper' + +# Bundler tags releases as v1.2.3, but Ratch's tags have always been +# plain version numbers, so keep it that way. +class Bundler::GemHelper + def version_tag + version.to_s + end +end + +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/VERSION b/VERSION deleted file mode 100644 index 26aaba0..0000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -1.2.0 diff --git a/bin/ludo b/bin/ludo index 8e0e91e..c72af90 100755 --- a/bin/ludo +++ b/bin/ludo @@ -1,16 +1,32 @@ -#! /usr/bin/ruby1.8 +#!/usr/bin/env ruby -# for FileTest.root? -require 'facets/filetest' +# ludo: "lookup and do". Looks for an executable script by name, in the +# present directory and then in each directory above it, and runs the +# first one found, from the directory it is in, passing along any further +# arguments. +# +# $ ludo script/test --verbose -name = ARGV[0] +name, *args = ARGV -if name - Dir.chdir '..' until FileTest.executable?(name) or FileTest.root?(Dir.pwd) - if FileTest.executable?( name ) - system name +if name.nil? || name == '-h' || name == '--help' + $stderr.puts "Usage: ludo SCRIPT [ARGUMENTS]" + $stderr.puts "Run the first executable SCRIPT found in this directory or one above it." + exit(name.nil? ? 1 : 0) +end + +dir = Dir.pwd + +loop do + file = File.join(dir, name) + if File.file?(file) && File.executable?(file) + Dir.chdir(dir) + exec(file, *args) end -else - puts "Script #{name} not found." + parent = File.dirname(dir) + break if parent == dir + dir = parent end +$stderr.puts "ludo: script not found -- #{name}" +exit 1 diff --git a/lib/ratch.rb b/lib/ratch.rb index b12f341..a4d182c 100644 --- a/lib/ratch.rb +++ b/lib/ratch.rb @@ -1,28 +1,12 @@ -module Ratch - # Access to project metadata. - def self.metadata - @metadata ||= ( - require 'yaml' - YAML.load(File.dirname(__FILE__) + '/ratch.yml') - ) - end - - # Access to project metadata via constants. - def self.const_missing(name) - metadata[name.to_s.downcase] || super(name) - end - - # TODO: Only here b/c of issue with Ruby 1.8.x. - VERSION = metadata['version'] -end - +require 'ratch/version' require 'ratch/script' -# Load utility extension modules. +# Utility extension modules, to include in a Shell subclass or extend a +# shell with. Each loads what it depends on only when it is used. require 'ratch/utils/cli' -require 'ratch/utils/pom' +require 'ratch/utils/config' +require 'ratch/utils/zlib' +require 'ratch/utils/tar' require 'ratch/utils/rdoc' require 'ratch/utils/email' -#require 'ratch/utils/tar' -#require 'ratch/utils/zlib' - +require 'ratch/utils/xdg' diff --git a/lib/ratch.yml b/lib/ratch.yml deleted file mode 120000 index 064ee51..0000000 --- a/lib/ratch.yml +++ /dev/null @@ -1 +0,0 @@ -../.ruby \ No newline at end of file diff --git a/lib/ratch/batch.rb b/lib/ratch/batch.rb index 15db8c8..bf1ecfe 100644 --- a/lib/ratch/batch.rb +++ b/lib/ratch/batch.rb @@ -11,23 +11,35 @@ module Ratch class Batch include Enumerable - # + # A batch of the files matching +patterns+ under the present + # directory. def self.[](*patterns) new('.', *patterns) end - # + # Like #new, but without the usual exclusions (version control + # directories, backup and core files). + def self.all(local, *patterns) + options = (Hash === patterns.last ? patterns.pop.dup : {}) + new(local, *patterns, options.merge(:all=>true)) + end + + # New batch of the files matching +patterns+, which are relative to + # the directory +local+. A final Hash gives options: :noop, :verbose + # (or :trace) and :dryrun, as for Shell, and :all to leave nothing out. def initialize(local, *patterns) - @local = Pathname.new(local) - @options = (Hash === patterns.last ? patterns.pop : {}).rekey(&:to_sym) + @local = Pathname.new(local.to_s) + @options = {} + (Hash === patterns.last ? patterns.pop : {}).each{ |k, v| @options[k.to_sym] = v } - @file_list = FileList.all + @file_list = @options[:all] ? FileList.all : FileList.new - patterns.each do |pattern| - if @local == Pathname.new('.') + patterns.flatten.each do |pattern| + pattern = pattern.to_s + if @local == Pathname.new('.') || FileTest.absolute?(pattern) @file_list.add(pattern) else - @file_list.add(File.join(local,pattern)) + @file_list.add(File.join(@local.to_s, pattern)) end end end @@ -103,7 +115,7 @@ def symlink? ; all?{ |path| FileTest.symlink?(path) } ; end def readable? ; all?{ |path| FileTest.readable?(path) } ; end def chardev? ; all?{ |path| FileTest.chardev?(path) } ; end def exist? ; all?{ |path| FileTest.exist?(path) } ; end - def exists? ; all?{ |path| FileTest.exists?(path) } ; end + def exists? ; all?{ |path| FileTest.exist?(path) } ; end def zero? ; all?{ |path| FileTest.zero?(path) } ; end def pipe? ; all?{ |path| FileTest.pipe?(path) } ; end def file? ; all?{ |path| FileTest.file?(path) } ; end @@ -170,7 +182,7 @@ def mkdir(options={}) raise Errno::EEXIST, "File exists - #{dir}" end end - list.map{ |dir| fileutils.mkdir(dir, options) } + list.map{ |dir| fu(:mkdir, options, dir){ |opts| ::FileUtils.mkdir(dir, **opts) } } end # Make a directory for every entry. @@ -180,42 +192,36 @@ def mkdir_p(options={}) raise Errno::EEXIST, "File exists - #{dir}" end end - list.map{ |dir| fileutils.mkdir_p(dir, options) } + list.map{ |dir| fu(:mkdir_p, options, dir){ |opts| ::FileUtils.mkdir_p(dir, **opts) } } end alias_method :mkpath, :mkdir_p # Remove every directory. def rmdir(options={}) - list.map{ |dir| fileutils.rmdir(dir, options) } + list.map{ |dir| fu(:rmdir, options, dir){ |opts| ::FileUtils.rmdir(dir, **opts) } } end # ln(list, destdir, options={}) def ln(dir, options={}) - #src = list.to_a - #new = localize(new) - fileutils.ln(list, dir, options) + fu(:ln, options, list, dir){ |opts| ::FileUtils.ln(list, localize(dir), **opts) } end alias_method :link, :ln # ln_s(list, destdir, options={}) def ln_s(dir, options={}) - #src = list.to_a - #new = localize(new) - fileutils.ln_s(list, dir, options) + fu(:ln_s, options, list, dir){ |opts| ::FileUtils.ln_s(list, localize(dir), **opts) } end alias_method :symlink, :ln_s def ln_sf(dir, options={}) - #src = list.to_a - #new = localize(new) - fileutils.ln_sf(list, dir, options) + fu(:ln_sf, options, list, dir){ |opts| ::FileUtils.ln_sf(list, localize(dir), **opts) } end # cp(list, dir, options={}) def cp(dir, options={}) #src = list.to_a #dest = localize(dest) - fileutils.cp(list, dir, options) + fu(:cp, options, list, dir){ |opts| ::FileUtils.cp(list, localize(dir), **opts) } end alias_method :copy, :cp @@ -223,21 +229,20 @@ def cp(dir, options={}) def cp_r(dir, options={}) #src = list.to_a #dest = localize(dest) - fileutils.cp_r(list, dir, options) + fu(:cp_r, options, list, dir){ |opts| ::FileUtils.cp_r(list, localize(dir), **opts) } end # mv(list, dir, options={}) def mv(dir, options={}) #src = list.to_a #dest = localize(dest) - fileutils.mv(list, dir, options) + fu(:mv, options, list, dir){ |opts| ::FileUtils.mv(list, localize(dir), **opts) } end alias_method :move, :mv # def rm(options={}) - list = list.to_a - fileutils.rm(list, options) + fu(:rm, options, list){ |opts| ::FileUtils.rm(list, **opts) } end # Alias for #rm. @@ -245,68 +250,68 @@ def rm(options={}) # Remove, recursively removing the contents of directories. def rm_r(options={}) - #list = list.to_a - fileutils.rm_r(list, options) + fu(:rm_r, options, list){ |opts| ::FileUtils.rm_r(list, **opts) } end # Remove, with force option. def rm_f(options={}) - #list = list.to_a - fileutils.rm_f(list, options) + fu(:rm_f, options, list){ |opts| ::FileUtils.rm_f(list, **opts) } end # Remove with force option, recursively removing the contents of directories. def rm_rf(options={}) - #list = list.to_a - fileutils.rm_rf(list, options) + fu(:rm_rf, options, list){ |opts| ::FileUtils.rm_rf(list, **opts) } end # Install files to a directory with given mode. Unlike #cp, this will # not copy the file if an up-to-date copy already exists. def install(dir, mode, options={}) - #src = list.to_a #dest = localize(dest) - fileutils.install(list, dir, mode, options) + fu(:install, options.merge(:mode=>mode), list, dir){ |opts| ::FileUtils.install(list, localize(dir), **opts) } end # Change mode of files. def chmod(mode, options={}) - #list = list.to_a - fileutils.chmod(mode, list, options) + fu(:chmod, options, mode, list){ |opts| ::FileUtils.chmod(mode, list, **opts) } end # Change mode of files, following directories recursively. def chmod_r(mode, options={}) - #list = list.to_a - fileutils.chmod_r(mode, list, options) + fu(:chmod_R, options, mode, list){ |opts| ::FileUtils.chmod_R(mode, list, **opts) } end #alias_method :chmod_R, :chmod_r # Change owner of files. def chown(user, group, options={}) - #list = list.to_a - fileutils.chown(user, group, list, options) + fu(:chown, options, user, group, list){ |opts| ::FileUtils.chown(user, group, list, **opts) } end # Change owner of files, following directories recursively. def chown_r(user, group, options={}) - #list = list.to_a - fileutils.chown_r(user, group, list, options) + fu(:chown_R, options, user, group, list){ |opts| ::FileUtils.chown_R(user, group, list, **opts) } end #alias_method :chown_R, :chown_r # Touch each file. def touch(options={}) - #list = list.to_a - fileutils.touch(list, options) + fu(:touch, options, list){ |opts| ::FileUtils.touch(list, **opts) } end - # Stage files. This is like #install but uses hardlinks. - def stage(dir) - #dir = localize(directory) - #files = localize(files) - #list = list.to_a - fileutils.stage(dir, local, list) + # Stage files: hard link each into +dir+, at its path relative to + # the batch's own directory. This is like #install but uses hardlinks. + def stage(dir, options={}) + stage = localize(dir) + entries.each do |entry| + src = localize(entry) + dest = File.join(stage, entry.to_s) + if File.directory?(src) + fu(:mkdir_p, options, dest){ |opts| ::FileUtils.mkdir_p(dest, **opts) } + else + fu(:mkdir_p, options, File.dirname(dest)){ |opts| ::FileUtils.mkdir_p(File.dirname(dest), **opts) } + fu(:ln, options, src, dest){ |opts| ::FileUtils.ln(src, dest, **opts) } + end + end + dir end # Convenient alias for #map_mv. @@ -324,7 +329,7 @@ def rename(options={}, &block) # # Returns the changed FileList instance. def map_mv(options={}, &block) - @file_list = map_send(:mv, options={}, &block) + @file_list = map_send(:mv, options, &block) end # Hard link the list of files in batch, using a block to determine the new @@ -332,7 +337,7 @@ def map_mv(options={}, &block) # # This is similar to #ln, but allows for detailed control over the link names. def map_ln(options={}, &block) - map_send(:ln, options={}, &block) + map_send(:ln, options, &block) end # Soft link the list of files in batch, using a block to determine the new @@ -340,7 +345,7 @@ def map_ln(options={}, &block) # # This is similar to #ln_s, but allows for detailed control over the link names. def map_ln_s(options={}, &block) - map_send(:ln_s, options={}, &block) + map_send(:ln_s, options, &block) end # Force soft linking of the list of files in batch, using a block to @@ -350,7 +355,7 @@ def map_ln_s(options={}, &block) # This is similar to #ln_sf, but allows for detailed control over the # link names. def map_ln_sf(options={}, &block) - map_send(:ln_sf, options={}, &block) + map_send(:ln_sf, options, &block) end # Copy the list of files in batch, using a block to determine the new @@ -359,7 +364,7 @@ def map_ln_sf(options={}, &block) # This is similar to #cp, but allows for detailed control over the new # file names. def map_cp(options={}, &block) - map_send(:cp, options={}, &block) + map_send(:cp, options, &block) end # Copy the list of files recursively in batch, using a block to determine @@ -368,7 +373,7 @@ def map_cp(options={}, &block) # This is similar to #cp_r, but allows for detailed control over the new # file names. def map_cp_r(options={}, &block) - map_send(:cp_r, options={}, &block) + map_send(:cp_r, options, &block) end # # Force copy the list of files recursively in batch, using a block to @@ -378,7 +383,7 @@ def map_cp_r(options={}, &block) # # This is similar to #cp_rf, but allows for detailed control over the new # # file names. # def map_cp_rf(options={}, &block) -# map_send(:cp_rf, options={}, &block) +# map_send(:cp_rf, options, &block) # end private @@ -404,7 +409,12 @@ def map_send(method, options={}, &block) end map.each do |src, dest| - fileutils.__send__(method, src, dest, options) + fu(method, options, src, dest) do |opts| + takes = ::FileUtils.method(method).parameters.map{ |_, name| name } + opts.delete(:force) unless takes.include?(:force) + ::FileUtils.rm_f(dest) if options[:force] && !takes.include?(:force) && File.file?(dest) + ::FileUtils.__send__(method, src, dest, **opts) + end end FileList.all(*map.values) end @@ -415,7 +425,7 @@ def map_send(method, options={}, &block) # If nota file rrror is raised. def ensure_safe(map) map.each do |src, dest| - raise unless File.exist?(src) + raise Errno::ENOENT, src.to_s unless File.exist?(src) if File.directory?(src) if File.directory?(dest) new_map = {} @@ -423,7 +433,7 @@ def ensure_safe(map) next if e == '.' or e == '..' new_map[File.join(src, e)] = File.join(dest, e) end - ensure_safe_destination(new_map) + ensure_safe(new_map) else raise Errno::EISDIR, "Is a directory - #{src}" end @@ -456,23 +466,27 @@ def ensure_safe(map) # Is +path+ out-of-date in comparsion to all files in batch. def outofdate?(path) - fileutils.outofdate?(path, to_a) + path = localize(path) + return true unless File.exist?(path) + return true if list.empty? + File.mtime(path) < list.map{ |f| File.mtime(f) }.max end # Is +path+ up-to-date in comparsion to all files in batch. def uptodate?(path) - fileutils.uptodate?(path, to_a) + ::FileUtils.uptodate?(localize(path), list) end # def noop? - @options[:noop] or @options[:dryrun] + !!(@options[:noop] or @options[:nowrite] or @options[:dryrun]) end # def verbose? - @options[:verbose] or @options[:dryrun] + !!(@options[:verbose] or @options[:trace] or @options[:dryrun]) end + alias_method :trace?, :verbose? # def dryrun? @@ -481,17 +495,44 @@ def dryrun? private - # Returns FileUtils module based on mode. - def fileutils - if dryrun? - ::FileUtils::DryRun - elsif noop? - ::FileUtils::Noop - elsif verbose? - ::FileUtils::Verbose - else - ::FileUtils + # A path taken from the batch's own directory, unless it is absolute. + def localize(path) + path = path.to_s + return path if FileTest.absolute?(path) || local.to_s == '.' + File.join(local.to_s, path) + end + + # How each file operation reads in a trace. + FU_COMMANDS = { + :mkdir_p=>'mkdir -p', :rm_r=>'rm -r', :rm_f=>'rm -f', :rm_rf=>'rm -rf', + :ln_s=>'ln -s', :ln_sf=>'ln -sf', :cp_r=>'cp -r', + :chmod_R=>'chmod -R', :chown_R=>'chown -R' + } + + # Carry out a file operation in the batch's mode: report it if + # tracing, with the paths as they were given, and yield the options + # for FileUtils unless this is a noop. + def fu(name, options, *args) + opts = fu_options(options) + noop = opts.delete(:noop) + verbose = opts.delete(:verbose) + if verbose + $stderr.puts [FU_COMMANDS[name] || name.to_s, *args.flatten].join(' ') end + yield(opts) unless noop + end + + # The options given for one command, with :noop and :verbose turned + # on if the batch's mode says so. + def fu_options(options) + opts = {} + (options || {}).each{ |k, v| opts[k.to_sym] = v } + given = [:dryrun, :nowrite, :noop, :trace, :verbose].select{ |k| opts.delete(k) } + dryrun = given.include?(:dryrun) + opts[:noop] = true if noop? || dryrun || given.include?(:nowrite) || given.include?(:noop) + opts[:verbose] = true if verbose? || dryrun || given.include?(:trace) || given.include?(:verbose) + opts.delete(:safe) + opts end end diff --git a/lib/ratch/console.rb b/lib/ratch/console.rb deleted file mode 100644 index 84abaa2..0000000 --- a/lib/ratch/console.rb +++ /dev/null @@ -1,199 +0,0 @@ -module Ratch - - # Ratch Shell Console - # - # NOTE: Console class is still a work in progress. - class Console - - attr_accessor :suppress_output - - # Set up the user's environment, including a pure binding into which - # env.rb and commands.rb are mixed. - def initialize - require 'readline' - #root = Rush::Dir.new('/') - #home = Rush::Dir.new(ENV['HOME']) if ENV['HOME'] - #pwd = Rush::Dir.new(ENV['PWD']) if ENV['PWD'] - - #@config = Rush::Config.new - - @config.load_history.each do |item| - Readline::HISTORY.push(item) - end - - Readline.basic_word_break_characters = "" - Readline.completion_append_character = nil - Readline.completion_proc = completion_proc - - @shell = Ratch::Shell.new - - @pure_binding = @shell.instance_eval("binding") - - $last_res = nil - - #eval @config.load_env, @pure_binding - - #commands = @config.load_commands - #Rush::Dir.class_eval commands - #Array.class_eval commands - end - - # Run the interactive shell using readline. - def run - loop do - cmd = Readline.readline('ratch> ') - - finish if cmd.nil? or cmd == 'exit' - - next if cmd == "" - - Readline::HISTORY.push(cmd) - - execute(cmd) - end - end - - # Run a single command. - def execute(cmd) - res = eval(cmd, @pure_binding) - $last_res = res - eval("_ = $last_res", @pure_binding) - print_result(res) - #rescue Rush::Exception => e - # puts "Exception #{e.class} -> #{e.message}" - rescue ::Exception => e - puts "Exception #{e.class} -> #{e.message}" - e.backtrace.each do |t| - puts " #{::File.expand_path(t)}" - end - end - - # Save history to ~/.config/ratch/history when the shell exists. - def finish - @config.save_history(Readline::HISTORY.to_a) - puts - exit - end - -# TODO: FIX ALL BELOW - - # Nice printing of different return types, particularly Rush::SearchResults. - def print_result(res) - return if self.suppress_output - if res.kind_of? String - puts res - elsif res.kind_of? Rush::SearchResults - widest = res.entries.map { |k| k.full_path.length }.max - res.entries_with_lines.each do |entry, lines| - print entry.full_path - print ' ' * (widest - entry.full_path.length + 2) - print "=> " - print res.colorize(lines.first.strip.head(30)) - print "..." if lines.first.strip.length > 30 - if lines.size > 1 - print " (plus #{lines.size - 1} more matches)" - end - print "\n" - end - puts "#{res.entries.size} matching files with #{res.lines.size} matching lines" - elsif res.respond_to? :each - counts = {} - res.each do |item| - puts item - counts[item.class] ||= 0 - counts[item.class] += 1 - end - if counts == {} - puts "=> (empty set)" - else - count_s = counts.map do |klass, count| - "#{count} x #{klass}" - end.join(', ') - puts "=> #{count_s}" - end - else - puts "=> #{res.inspect}" - end - end - - def path_parts(input) # :nodoc: - case input - when /((?:@{1,2}|\$|)\w+(?:\[[^\]]+\])*)([\[\/])(['"])([^\3]*)$/ - $~.to_a.slice(1, 4).push($~.pre_match) - when /((?:@{1,2}|\$|)\w+(?:\[[^\]]+\])*)(\.)(\w*)$/ - $~.to_a.slice(1, 3).push($~.pre_match) - when /((?:@{1,2}|\$|)\w+)$/ - $~.to_a.slice(1, 1).push(nil).push($~.pre_match) - else - [ nil, nil, nil ] - end - end - - def complete_method(receiver, dot, partial_name, pre) - path = eval("#{receiver}.full_path", @pure_binding) rescue nil - box = eval("#{receiver}.box", @pure_binding) rescue nil - if path and box - (box[path].methods - Object.methods).select do |e| - e.match(/^#{Regexp.escape(partial_name)}/) - end.map do |e| - (pre || '') + receiver + dot + e - end - end - end - - def complete_path(possible_var, accessor, quote, partial_path, pre) # :nodoc: - original_var, fixed_path = possible_var, '' - if /^(.+\/)([^\/]*)$/ === partial_path - fixed_path, partial_path = $~.captures - possible_var += "['#{fixed_path}']" - end - full_path = eval("#{possible_var}.full_path", @pure_binding) rescue nil - box = eval("#{possible_var}.box", @pure_binding) rescue nil - if full_path and box - Rush::Dir.new(full_path, box).entries.select do |e| - e.name.match(/^#{Regexp.escape(partial_path)}/) - end.map do |e| - (pre || '') + original_var + accessor + quote + fixed_path + e.name + (e.dir? ? "/" : "") - end - end - end - - def complete_variable(partial_name, pre) - lvars = eval('local_variables', @pure_binding) - gvars = eval('global_variables', @pure_binding) - ivars = eval('instance_variables', @pure_binding) - (lvars + gvars + ivars).select do |e| - e.match(/^#{Regexp.escape(partial_name)}/) - end.map do |e| - (pre || '') + e - end - end - - # Try to do tab completion on dir square brackets and slash accessors. - # - # Example: - # - # dir['subd # presing tab here will produce dir['subdir/ if subdir exists - # dir/'subd # presing tab here will produce dir/'subdir/ if subdir exists - # - # This isn't that cool yet, because it can't do multiple levels of subdirs. - # It does work remotely, though, which is pretty sweet. - def completion_proc - proc do |input| - receiver, accessor, *rest = path_parts(input) - if receiver - case accessor - when /^[\[\/]$/ - complete_path(receiver, accessor, *rest) - when /^\.$/ - complete_method(receiver, accessor, *rest) - when nil - complete_variable(receiver, *rest) - end - end - end - end - - end - -end diff --git a/lib/ratch/core_ext/facets.rb b/lib/ratch/core_ext/facets.rb index 77f5702..a38d1c7 100644 --- a/lib/ratch/core_ext/facets.rb +++ b/lib/ratch/core_ext/facets.rb @@ -13,3 +13,4 @@ require 'facets/pathname' require 'facets/filetest' require 'facets/fileutils' +require 'facets/hash/rekey' diff --git a/lib/ratch/core_ext/to_console.rb b/lib/ratch/core_ext/to_console.rb index d7a9734..bcbb749 100644 --- a/lib/ratch/core_ext/to_console.rb +++ b/lib/ratch/core_ext/to_console.rb @@ -8,10 +8,8 @@ class Array #:nodoc: # method arguments --ie. [arg1, arg2, ..., hash] def to_console - #flags = (Hash===last ? pop : {}) - #flags = flags.to_console - #flags + ' ' + join(" ") - to_argv.join(' ') + require 'shellwords' + Shellwords.join(to_argv) end # TODO: DEPRECATE @@ -19,9 +17,9 @@ def to_console # def to_argv - flags = (Hash===last ? pop : {}) - flags = flags.to_argv - flags + self + args = dup + flags = (Hash===args.last ? args.pop : {}) + flags.to_argv + args.map{ |a| a.to_s } end # def to_console @@ -50,10 +48,12 @@ class Hash # The array is accepted in the format of Ruby # method arguments --ie. [arg1, arg2, ..., hash] def to_console - to_argv.join(' ') + require 'shellwords' + Shellwords.join(to_argv) end - # Convert a Hash into command line parameters. + # Convert a Hash into command line parameters, one string per + # parameter, as a program receives them (so with no quoting). # The array is accepted in the format of Ruby # method arguments --ie. [arg1, arg2, ..., hash] def to_argv @@ -62,13 +62,13 @@ def to_argv m = f.to_s.size == 1 ? '-' : '--' case v when Array - v.each{ |e| flags << "#{m}#{f}='#{e}'" } + v.each{ |e| flags << (m == '-' ? "-#{f}#{e}" : "--#{f}=#{e}") } when true flags << "#{m}#{f}" when false, nil # nothing else - flags << "#{m}#{f}='#{v}'" + flags << (m == '-' ? "-#{f}#{v}" : "--#{f}=#{v}") end end flags diff --git a/lib/ratch/file_list.rb b/lib/ratch/file_list.rb index 4a2ecf6..427a009 100644 --- a/lib/ratch/file_list.rb +++ b/lib/ratch/file_list.rb @@ -265,26 +265,17 @@ def gsub!(pat, rep) self end - # Apply the pathmap spec to each of the included file names, returning a - # new file list with the modified paths. (See String#pathmap for - # details.) - def pathmap(spec=nil) - collect { |fn| fn.pathmap(spec) } - end - - # Return a new FileList with String#ext method applied to - # each member of the array. + # Return a new FileList with the extension of each file name changed + # to +newext+, or removed if none is given. # - # This method is a shortcut for: + # FileList['a.c', 'b.c'].ext('o') #=> ['a.o', 'b.o'] # - # array.collect { |item| item.ext(newext) } - # - # +ext+ is a user added method for the Array class. def ext(newext='') - collect { |fn| fn.ext(newext) } + newext = newext.to_s + newext = '.' + newext unless newext.empty? || newext.start_with?('.') + collect { |fn| fn.chomp(File.extname(fn)) + newext } end - # Grep each of the files in the filelist using the given pattern. If a # block is given, call the block on each matching line, passing the file # name, line number, and the matching line of text. If no block is given, diff --git a/lib/ratch/script.rb b/lib/ratch/script.rb index bcf398c..6f74881 100644 --- a/lib/ratch/script.rb +++ b/lib/ratch/script.rb @@ -92,7 +92,7 @@ def trace(message) # Pass-thru to singleton class. def define_method(name, &block) - (class << self; self; end).__send__(:define_method, &block) + (class << self; self; end).__send__(:define_method, name, &block) end ## If method is missing, try the singleton class. This allows the script diff --git a/lib/ratch/shell.rb b/lib/ratch/shell.rb index 256e96e..7342a13 100644 --- a/lib/ratch/shell.rb +++ b/lib/ratch/shell.rb @@ -1,107 +1,106 @@ -require 'thread' -#require 'rbconfig' +require 'pathname' +require 'fileutils' require 'ratch/core_ext' require 'ratch/batch' module Ratch - # TODO: Better base class? + # Raised when a path that has to exist doesn't. class FileNotFound < StandardError end # = Shell Prompt class # - # Ratch Shell object provides a limited file system shell in code. - # It is similar to having a shell prompt available to you in Ruby. + # A Shell object is a file system shell in code: it stands at a + # directory, and paths given to its methods are taken from there, much + # as they are at a shell prompt. + # + # shell = Ratch::Shell.new('project') + # + # shell.file?('README.md') + # shell.mkdir_p('tmp/cache') + # shell.cp('README.md', 'tmp') + # shell.sh('git status') + # + # The process's own working directory is left alone, so shells at + # different directories can be used side by side, and from different + # threads. + # + # A shell can be put in a mode in which it only pretends: + # + # shell = Ratch::Shell.new('project', :dryrun=>true) + # shell.rm_r('tmp') # prints "rm -r tmp" and removes nothing + # + # NOTE: We use the term *trace* in place of *verbose* for the option + # that reports each step. Ruby's FileUtils calls it *verbose*, but that + # word is often wanted for a command's own purposes. # - # NOTE: We have used the term *trace* in place of *verbose* for command - # line options. Even though Ruby itself uses the term *verbose* with respect - # to FileUtils, the term is commonly used for command specific needs, so we - # want to leave it open for such cases. class Shell # - def self.[](path) - new(path) + def self.[](*path) + new(*path) end - # New Shell object. + # New Shell object. The path can be given in parts. Without one, the + # shell stands at the present working directory. # # Shell.new(:noop=>true) # Shell.new('..', :quiet=>true) # - def initialize(*args) - path, opts = parse_arguments(*args) - - opts.rekey!(&:to_sym) + # Options: + # + # :quiet print nothing; commands run with #sh have their output dropped + # :noop change nothing on disk and run no commands (also :nowrite) + # :trace report each step (also :verbose) + # :dryrun both :noop and :trace + # + def initialize(*path) + opts = (Hash === path.last ? path.pop : {}) + opts = opts.each_with_object({}){ |(k, v), h| h[k.to_sym] = v } set_options(opts) - if path.empty? - path = Dir.pwd - else - path = File.join(*path) - end + path = path.empty? ? Dir.pwd : File.join(*path.map{ |part| part.to_s }) - raise FileNotFound, "#{path}" unless ::File.exist?(path) raise FileNotFound, "#{path}" unless ::File.directory?(path) @_work = Pathname.new(path).expand_path end - private + private # - def parse_arguments(*args) - opts = (Hash===args.last ? args.pop : {}) - return args, opts + def set_options(opts) + @_quiet = !!(opts[:quiet] || opts[:silent]) + @_nowrite = !!(opts[:nowrite] || opts[:noop] || opts[:dryrun]) + @_trace = !!(opts[:trace] || opts[:verbose] || opts[:dryrun]) end - # - def set_options(opts) - @_quiet = opts[:quiet] || options[:silent] - @_nowrite = opts[:nowrite] || options[:noop] || opts[:dryrun] - @_trace = opts[:trace] || options[:verbose] || opts[:dryrun] - #@_force = opts[:force] + # The options a new shell needs to be in the same mode as this one. + def mode_options + {:quiet=>quiet?, :noop=>noop?, :trace=>trace?} end - # - def mutex - @mutex ||= Mutex.new - end - - public - - # Opertaton mode. This can be :noop, :verbose or :dryrun. - # The later is the same as the first two combined. - #def mode(opts=nil) - # return @mode unless opts - # opts.each do |key, val| - # next unless val - # case key - # when :noop - # @mode = (@mode == :verbose ? :dryrun : :noop) - # when :verbose - # @mode = (@mode == :noop ? :dryrun : :verbose) - # when :dryrun - # @mode = :dryrun - # end - # end - #end + public def quiet? ; @_quiet ; end def trace? ; @_trace ; end def nowrite? ; @_nowrite ; end - #def force? ; @_force ; end def dryrun? ; nowrite? && trace? ; end - alias verbose? trace? - alias noop? nowrite + alias_method :verbose?, :trace? + alias_method :noop?, :nowrite? # String representation is work directory path. def to_s ; work.to_s ; end + # + def inspect + "#<#{self.class} #{work}>" + end + # Two Shell's are equal if they have the same working path. def ==(other) return false unless other.is_a?(self.class) @@ -117,110 +116,83 @@ def eql?(other) true end + # + def hash + [self.class, work, noop?].hash + end + # Provides convenient starting points in the file system. # # root #=> # # home #=> # # work #=> # # - - # Current root path. - #def root(*args) - # Pathname['/', *args] - #end - - # Current home path. - #def home(*args) - # Pathname['~', *args].expand_path - #end - - # Current working path. - #def work(*args) - # Pathname['.', *args] - #end - - # TODO: Should these take *args? + # Each takes path parts to add, and the result must be a directory. # Root location. - def root(*args) - dir('/', *args) + def root(*parts) + dir(File.join('/', *parts.map{ |part| part.to_s })) end # Current home path. - def home(*args) - dir(File.expand_path('~'), *args) + def home(*parts) + dir(File.join(File.expand_path('~'), *parts.map{ |part| part.to_s })) end # Current working path. - def work(*args) - return @_work if args.empty? - return dir(@_work, *args) + def work(*parts) + return @_work if parts.empty? + dir(File.join(*parts.map{ |part| part.to_s })) end - # Alias for #work. - #alias_method :pwd, :work - - # Return a new prompt with the same location. - # NOTE: Use #dup or #clone ? - #def new ; Shell.new(work) ; end + # Present working directory, as a String. + def pwd + work.to_s + end + # The directory above the working path. def parent - dir('..') + work.parent end - # - #def [](name) - # #FileObject[localize(name)] - # #Pathname.new(localize(path)) - # Pathlist.new(localize(path)) - #end - # Returns a Batch of file +patterns+. def batch(*patterns) - Batch.new patterns.map{|pattern| localize(pattern)} + Batch.new(work, *patterns, mode_options) end # Returns a Batch of file +patterns+, without any exclusions. def batch_all(*patterns) - Batch.all patterns.map{|pattern| localize(pattern)} + Batch.all(work, *patterns, mode_options) end - # + # A Pathname for a path, which need not exist. def path(path) Pathname.new(localize(path)) end alias_method :pathname, :path - # + # A Pathname for a file, which must exist. def file(path) - #FileObject[name] path = localize(path) - raise FileNotFound unless File.file?(path) + raise FileNotFound, path unless File.file?(path) Pathname.new(path) end - #def doc(name) - # Document.new(name) - #end - - # + # A Pathname for a directory, which must exist. def dir(path) - #Directory.new(name) path = localize(path) - raise FileNotFound unless File.directory?(path) + raise FileNotFound, path unless File.directory?(path) Pathname.new(path) end - # Lists all entries. + # Lists all entries, as Dir.entries does, but as Pathnames. def entries work.entries end - #alias_method :ls, :entries - # Lists directory entries. def directory_entries - entries.select{ |d| d.directory? } + entries.select{ |d| (work + d).directory? } end # @@ -228,232 +200,355 @@ def directory_entries # Lists file entries. def file_entries - entries.select{ |f| f.file? } + entries.select{ |f| (work + f).file? } end - # Likes entries but omits '.' and '..' paths. + # Like #entries but omits the '.' and '..' paths. def pathnames - work.entries - %w{. ..}.map{|f|Pathname.new(f)} + work.children(false) end # Returns list of directories. def directories - pathnames.select{ |f| f.directory? } + pathnames.select{ |d| (work + d).directory? } end alias_method :dirs, :directories alias_method :folders, :directories # Returns list of files. def files - pathnames.select{ |f| f.file? } + pathnames.select{ |f| (work + f).file? } end - # Join paths. - #-- - # TODO: Should this return a new directory object? - # Or should it change directories? - #++ + # A new shell at a directory under this one, in the same mode. + # + # lib = shell / 'lib' + # def /(path) - #@_work += dir # did not work, why? - @_work = dir(localize(path)) - self + self.class.new(dir(path), mode_options) end # Alias for #/. - alias_method '+', '/' - - #-- - # TODO: Tie system into the System class (?) - #++ - def system(cmd) - locally do - super(cmd) - end + alias_method :+, :/ + + # Run a command from the working directory, as Kernel#system does, + # whatever the mode. + def system(*cmd) + opts = (Hash === cmd.last ? cmd.pop.dup : {}) + opts[:chdir] ||= work.to_s + ::Kernel.system(*cmd, **opts) end - # Shell runner. - def sh(cmd) - #puts "--> system call: #{cmd}" if trace? - puts cmd if trace? + # Shell runner. Runs a command from the working directory and returns + # true if it succeeded. In trace mode the command is printed first; in + # noop mode it is not run; in quiet mode its output is dropped. + # + # shell.sh 'make install' + # shell.sh 'git', 'commit', '-m', message + # + def sh(*cmd) + $stderr.puts cmd.join(' ') if trace? return true if noop? - #locally do - if quiet? - silently{ system(cmd) } - else - system(cmd) - end - #end - end - - # Shell runner. - #def sh(cmd) - # if dryrun? - # puts cmd - # true - # else - # puts "--> system call: #{cmd}" if trace? - # if quiet? - # silently{ system(cmd) } - # else - # system(cmd) - # end - # end - #end + if quiet? + system(*cmd, :out=>File::NULL, :err=>File::NULL) + else + system(*cmd) + end + end # Change working directory. # - # TODO: Make thread safe. + # With a block, the shell stands at +path+ for the length of the block + # and then returns to where it was. The process's working directory is + # changed too for that time, so that code in the block which doesn't + # go through the shell sees the same directory. Ruby allows only one + # such block at a time across threads. # def cd(path, &block) if block work_old = @_work begin - @_work = dir(localize(path)) - locally(&block) - #mutex.synchronize do - # Dir.chdir(@_work){ block.call } - #end + @_work = dir(path) + Dir.chdir(@_work.to_s){ block.call(self) } ensure @_work = work_old end else - @_work = dir(localize(path)) + @_work = dir(path) end end # alias_method :chdir, :cd - # Bonus FileUtils features. - #def cd(*a,&b) - # puts "cd #{a}" if dryrun? or trace? - # fileutils.chdir(*a,&b) - #end + # -- FileTest -- - # Methods that can simply be localized via their first argument. - - LOCALIZABLE_METHODS = %w{ - size size? directory? dir? readable? symlink? chardev? exist? exists? - zero? pipe? file? stticky? blockdev? grpowned? setgid? setuid? - socket? owned? writable? executable? safe? readable_real? - writeable_real? executable_real? + # File tests, which take one path. + FILE_TESTS = %w{ + size size? directory? symlink? readable? chardev? exist? + zero? pipe? file? sticky? blockdev? grpowned? setgid? setuid? + socket? owned? writable? executable? readable_real? + writable_real? executable_real? world_readable? world_writable? } - LOCALIZABLE_METHODS.each do |name| - module_eval %{ + FILE_TESTS.each do |name| + module_eval <<-EOS, __FILE__, __LINE__ + 1 def #{name}(path) - shellutils.#{name}(localize(path)) + ::FileTest.#{name}(localize(path)) end - } - end - - def relative?(path); shellutils.relative?(path); end - def absolute?(path); shellutils.absolute?(path); end - - def identical?(path, other) - shellutils.indentical?(localize(path), localize(other)) + EOS end - alias_method :cmp, :identical? + alias_method :dir?, :directory? - #alias_method :directory?, :dir? #; module_function :directory? + # Ruby dropped +exists?+ in 3.2; it is kept here. + alias_method :exists?, :exist? + # Is the path safe from the meddling of others? + def safe?(path) + ::FileTest.safe?(localize(path)) + end - # Methods that are wrapped in a locally chdir block. + def relative?(path); ::FileTest.relative?(path.to_s); end + def absolute?(path); ::FileTest.absolute?(path.to_s); end - LOCALLY_METHODS = %w{ - mkdir mkdir_p mkpath rmdir ln ln_s ln_sf link symlink - cp cp_r copy mv move rm rm_r rm_f rm_rf remove - install chmod chmod_r chmod_R chown chown_r chown_R touch - stage amass uptodate? outofdate? - ctime atime mtime utime - read write append glob - multiglob multiglob_r - } + # Are the two paths the same file? + def identical?(path, other) + ::FileTest.identical?(localize(path), localize(other)) + end - LOCALLY_METHODS.each do |name| - module_eval %{ - def #{name}(*args) - locally do - super(*args) - end - end - } + # Do the two files have the same content? + def cmp(path, other) + ::FileUtils.compare_file(localize(path), localize(other)) end + alias_method :compare_file, :cmp - # These low-level Fileutils methods have omitted. + # -- FileUtils -- + # + # Each takes the options of its FileUtils namesake. The shell's mode + # sets :noop and :verbose. + # + # These low-level FileUtils methods have been omitted. # # * getwd -> pwd - # * compare_file -> cmp # * remove_file -> rm # * copy_file -> cp # * remove_dir -> rmdir # * safe_unlink -> rm_f - # * makedirs -> mkdir_p - # * rmtree -> rm_rf # * copy_stream # * remove_entry # * copy_entry # * remove_entry_secure # * compare_stream - # Present working directory. - def pwd - work.to_s + # Methods taking a path or a list of paths. + %w{mkdir mkdir_p rmdir rm rm_r rm_f rm_rf touch}.each do |name| + module_eval <<-EOS, __FILE__, __LINE__ + 1 + def #{name}(list, options={}) + fu(:#{name}, options, list){ |opts| ::FileUtils.#{name}(localize(list), **opts) } + end + EOS + end + + alias_method :mkpath, :mkdir_p + alias_method :makedirs, :mkdir_p + alias_method :remove, :rm + alias_method :rmtree, :rm_rf + + # Methods taking a source, or a list of them, and a destination. + %w{ln ln_s ln_sf cp cp_r mv}.each do |name| + module_eval <<-EOS, __FILE__, __LINE__ + 1 + def #{name}(src, dest, options={}) + fu(:#{name}, options, src, dest){ |opts| ::FileUtils.#{name}(localize(src), localize(dest), **opts) } + end + EOS + end + + alias_method :link, :ln + alias_method :symlink, :ln_s + alias_method :copy, :cp + alias_method :move, :mv + + # Copy +src+ to +dest+, setting its mode. The mode can be given as the + # third argument or as the :mode option. + def install(src, dest, mode=nil, options={}) + options, mode = mode, nil if Hash === mode + options = options.merge(:mode=>mode) if mode + fu(:install, options, src, dest){ |opts| ::FileUtils.install(localize(src), localize(dest), **opts) } + end + + # + def chmod(mode, list, options={}) + fu(:chmod, options, (Integer === mode ? '%o' % mode : mode), list){ |opts| ::FileUtils.chmod(mode, localize(list), **opts) } + end + + # + def chmod_R(mode, list, options={}) + fu(:chmod_R, options, (Integer === mode ? '%o' % mode : mode), list){ |opts| ::FileUtils.chmod_R(mode, localize(list), **opts) } + end + alias_method :chmod_r, :chmod_R + + # + def chown(user, group, list, options={}) + fu(:chown, options, [user, group].compact.join(':'), list){ |opts| ::FileUtils.chown(user, group, localize(list), **opts) } + end + + # + def chown_R(user, group, list, options={}) + fu(:chown_R, options, [user, group].compact.join(':'), list){ |opts| ::FileUtils.chown_R(user, group, localize(list), **opts) } + end + alias_method :chown_r, :chown_R + + # Is +path+ newer than all of +sources+? + def uptodate?(path, *sources) + ::FileUtils.uptodate?(localize(path), localize(sources.flatten)) + end + + # Does +path+ need updating, going by +sources+, which can be globs? + # True if it doesn't exist or is older than any of them. + def outofdate?(path, *sources) + path = localize(path) + return true unless File.exist?(path) + mtimes = glob(*sources.flatten).map{ |file| File.mtime(localize(file)) } + return true if mtimes.empty? + File.mtime(path) < mtimes.max + end + + # Hard link +files+, which are relative to the working directory, into + # a staging directory, making it afresh. + def stage(stage_dir, files, options={}) + rm_r(stage_dir, options) if directory?(stage_dir) + mkdir_p(stage_dir, options) + [files].flatten.each do |file| + dest = File.join(stage_dir.to_s, file.to_s) + if directory?(file) + mkdir_p(dest, options) + else + mkdir_p(File.dirname(dest), options) unless directory?(File.dirname(dest)) + ln(file, dest, options) + end + end + path(stage_dir) end + # A glob-like method that takes a set of include globs, exclude globs + # and ignore globs and gives the paths that are left. A directory + # stands for everything in it. # - # TODO: should this have SOURCE diectory? - # stage(directory, source_dir, files) + # The ignore globs differ from the exclude globs in that they are + # matched against the base name of a path, not the whole of it. # - def stage(stage_dir, files) - #dir = localize(directory) - #files = localize(files) - locally do - fileutils.stage(stage_dir, work, files) + def amass(include_globs, exclude_globs=[], ignore_globs=[]) + expand = lambda do |globs| + [globs].flatten.map{ |g| directory?(g) ? [g, File.join(g.to_s, '**/*')] : g }.flatten + end + files = glob(*expand.call(include_globs)) - glob(*expand.call(exclude_globs)) + files = files.uniq + files.reject do |f| + [ignore_globs].flatten.any?{ |x| File.fnmatch?(x, File.basename(f)) } + end + end + + # -- File -- + + # Get creation timestamp. + def ctime(path) + File.ctime(localize(path)) + end + + # Get, or with a time set, the last access timestamp. + def atime(path, time=nil, options={}) + options, time = time, nil if Hash === time + return File.atime(localize(path)) unless time + utime(time, File.mtime(localize(path)), path, options) + end + + # Get, or with a time set, the last modification timestamp. + def mtime(path, time=nil, options={}) + options, time = time, nil if Hash === time + return File.mtime(localize(path)) unless time + utime(File.atime(localize(path)), time, path, options) + end + + # Set the access and modification timestamps of files. + def utime(atime, mtime, *files) + opts = fu_options(Hash === files.last ? files.pop : {}) + $stderr.puts "utime #{atime} #{mtime} #{files.join(' ')}" if opts[:verbose] + File.utime(atime, mtime, *localize(files.flatten)) unless opts[:noop] + end + + # Read file. + def read(path) + File.read(localize(path)) + end + + # Write file. + def write(path, text, options={}) + opts = fu_options(options) + $stderr.puts "write #{path}" if opts[:verbose] + File.open(localize(path), 'w'){ |f| f << text } unless opts[:noop] + end + + # Append to file. + def append(path, text, options={}) + opts = fu_options(options) + $stderr.puts "append #{path}" if opts[:verbose] + File.open(localize(path), 'a'){ |f| f << text } unless opts[:noop] + end + + # -- Dir -- + + # Glob patterns. Returns the matches as strings, relative to the + # working directory unless a pattern is absolute. A trailing Integer + # is taken as File::FNM flags. + def glob(*patterns, &block) + flags = (::Integer === patterns.last ? patterns.pop : 0) + matches = [] + patterns.flatten.each do |pattern| + pattern = pattern.to_s + if absolute?(pattern) + matches.concat(Dir.glob(pattern, flags)) + else + matches.concat(Dir.glob(pattern, flags, :base=>work.to_s)) + end + end + if block + matches.each(&block) + else + matches end end private - # Returns a path local to the current working path. + # Returns a path local to the current working path. An absolute path + # is left as it is, and so is nil. Given a list, localizes each. def localize(local_path) - # some path arguments are optional - return local_path unless local_path - # case local_path + when nil + nil when Array - local_path.collect do |lp| - if absolute?(lp) - lp - else - File.expand_path(File.join(work.to_s, lp)) - end - end + local_path.map{ |lp| localize(lp) } else - # do not localize an absolute path + local_path = local_path.to_s return local_path if absolute?(local_path) File.expand_path(File.join(work.to_s, local_path)) - #(work + local_path).expand_path.to_s end end - # Change directory to the shell's work directory, - # process the +block+ and then return to user directory. + # Run a block with the process's working directory set to the shell's. + # Nothing in Shell itself needs this; it is for extensions that call + # code which only knows the process's directory. def locally(&block) if work.to_s == Dir.pwd block.call else - mutex.synchronize do - #work.chdir(&block) - Dir.chdir(work, &block) - end + Dir.chdir(work.to_s, &block) end end # TODO: Should naming policy be in a utility extension module? - # # def naming_policy(*policies) if policies.empty? @@ -463,7 +558,6 @@ def naming_policy(*policies) end end - # # def apply_naming_policy(name, ext) naming_policy.each do |policy| @@ -481,62 +575,47 @@ def apply_naming_policy(name, ext) name end - private + # How each file operation reads in a trace. + FU_COMMANDS = { + :mkdir_p=>'mkdir -p', :rm_r=>'rm -r', :rm_f=>'rm -f', :rm_rf=>'rm -rf', + :ln_s=>'ln -s', :ln_sf=>'ln -sf', :cp_r=>'cp -r', + :chmod_R=>'chmod -R', :chown_R=>'chown -R' + } - # The ShellUtils module based on current mode. - def shellutils - if dryrun? - ShellUtils::DryRun - elsif nowrite? - ShellUtils::NoWrite - elsif trace? - ShellUtils::Verbose - else - ShellUtils + # Carry out a file operation in the shell's mode: report it if + # tracing, with the paths as they were given, and yield the options + # for FileUtils unless this is a noop. + def fu(name, options, *args) + opts = fu_options(options) + noop = opts.delete(:noop) + verbose = opts.delete(:verbose) + if verbose + $stderr.puts [FU_COMMANDS[name] || name.to_s, *args.flatten].join(' ') end + yield(opts) unless noop end - # TODO: What's #util_options for? + # The options given for one command, with :noop and :verbose turned + # on if the shell's mode says so. The shell's own names for them + # (:trace, :nowrite, :dryrun) are accepted per command as well. + def fu_options(options) + opts = {} + (options || {}).each{ |k, v| opts[k.to_sym] = v } + given = [:dryrun, :nowrite, :noop, :trace, :verbose].select{ |k| opts.delete(k) } + dryrun = given.include?(:dryrun) + opts[:noop] = true if noop? || dryrun || given.include?(:nowrite) || given.include?(:noop) + opts[:verbose] = true if trace? || dryrun || given.include?(:trace) || given.include?(:verbose) + opts + end - # This may be used by script commands to allow for per command - # noop and trace options. Global options have precedence. + # This may be used by utility extensions to allow for per command + # noop and trace options. The shell's mode has precedence. Returns + # the two as a pair. def util_options(options) - noop = noop? || options[:noop] || options[:dryrun] - trace = trace? || options[:trace] || options[:dryrun] - return noop, trace - end - -# # Returns FileUtils module based on mode. -# def fileutils -# if dryrun? -# ::FileUtils::DryRun -# elsif noop? -# ::FileUtils::NoWrite -# elsif trace? -# ::FileUtils::Verbose -# else -# ::FileUtils -# end -# end - -# # Does a path need updating, based on given +sources+? -# # This compares mtimes of give paths. Returns false -# # if the path needs to be updated. -# # -# # TODO: Put this in FileTest instead? -# -# def out_of_date?(path, *sources) -# return true unless File.exist?(path) -# -# sources = sources.collect{ |source| Dir.glob(source) }.flatten -# mtimes = sources.collect{ |file| File.mtime(file) } -# -# return true if mtimes.empty? # TODO: This the way to go here? -# -# File.mtime(path) < mtimes.max -# end + opts = fu_options(options) + return !!opts[:noop], !!opts[:verbose] + end end end - diff --git a/lib/ratch/shell_utils0.rb b/lib/ratch/shell_utils0.rb deleted file mode 100644 index 7375ec9..0000000 --- a/lib/ratch/shell_utils0.rb +++ /dev/null @@ -1,203 +0,0 @@ -module Ratch - - require 'rbconfig' - - # ShellUtils provides the whole slew of FileUtils, - # FileTest and File class methods in a single module - # and modifies methods according to noop? and verbose? - # options. - module ShellUtils - - # - def verbose? - false - end - - # - def noop? - false - end - - # - def dryrun? - noop? && verbose? - end - - # - def force? - false - end - - # A path is required for shell methods to operate. - # If no path is set than the current working path is used. - def path - @path ||= Dir.pwd - end - - # Set shell path. - def path=(dir) - @path = dir - end - - attr_writer :force - attr_writer :quiet - attr_writer :trace - attr_writer :trial - attr_writer :debug - attr_writer :verbose - - def force? ; @force ; end - - def quiet? ; @quiet ; end - def trial? ; @trial ; end - - def trace? ; @trace ; end - def debug? ; @debug ; end - - def verbose? ; @verbose ; end - def noop? ; @trial ; end - def dryrun? ; verbose? && noop? ; end - - def silent? ; @quiet ; end - - # -- Shell ---------------------------------------------------------------- - - # Delegate to Ratch::Shell instance. - #def shell(path=Dir.pwd) - # @shell ||= {} - # @shell[path] ||= ( - # mode = { - # :noop => trial?, - # :verbose => trace? || (trial? && !quiet?), - # :quiet => quiet? - # } - # Ratch::Shell.new(path, mode) - # ) - #end - - # Shell runner. - def sh(cmd) - trace cmd - return true if noop? - - if quiet? - silently{ system(cmd) } - else - system(cmd) - end - end - - # Current ruby binary. - RUBY = ( - bindir = ::Config::CONFIG['bindir'] - rubyname = ::Config::CONFIG['ruby_install_name'] - File.join(bindir, rubyname}.sub(/.*\s.*/m, '"\&"') - ) - - # Shell-out to ruby. - def ruby(cmd) - sh RUBY + " " + cmd - end - -=begin - # -- Dir Methods ---------------------------------------------------------- - - # TODO: Ultimately merge #glob and #multiglob. - def multiglob(*args, &blk) - Dir.multiglob(*args, &blk) - end - - # - def multiglob_r(*args, &blk) - Dir.multiglob_r(*args, &blk) - end -=end - - # -- File Testing --------------------------------------------------------- - - def size(path) ; FileTest.size(path) ; end - def size?(path) ; FileTest.size?(path) ; end - def directory?(path) ; FileTest.directory?(path) ; end - def symlink?(path) ; FileTest.symlink?(path) ; end - def readable?(path) ; FileTest.readable?(path) ; end - def chardev?(path) ; FileTest.chardev?(path) ; end - def exist?(path) ; FileTest.exist?(path) ; end - def exists?(path) ; FileTest.exists?(path) ; end - def zero?(path) ; FileTest.zero?(path) ; end - def pipe?(path) ; FileTest.pipe?(path) ; end - def file?(path) ; FileTest.file?(path) ; end - def sticky?(path) ; FileTest.sticky?(path) ; end - def blockdev?(path) ; FileTest.blockdev?(path) ; end - def grpowned?(path) ; FileTest.grpowned?(path) ; end - def setgid?(path) ; FileTest.setgid?(path) ; end - def setuid?(path) ; FileTest.setuid?(path) ; end - def socket?(path) ; FileTest.socket?(path) ; end - def owned?(path) ; FileTest.owned?(path) ; end - def writable?(path) ; FileTest.writable?(path) ; end - def executable?(path) ; FileTest.executable?(path) ; end - - def safe?(path) ; FileTest.safe?(path) ; end - - def relative?(path) ; FileTest.relative?(path) ; end - def absolute?(path) ; FileTest.absolute?(path) ; end - - def writable_real?(path) ; FileTest.writable_real?(path) ; end - def executable_real?(path) ; FileTest.executable_real?(path) ; end - def readable_real?(path) ; FileTest.readable_real?(path) ; end - - def identical?(path, other) - FileTest.identical?(path, other) - end - - alias_method :compare_file, :identical? - - # -- File Methods --------------------------------------------------------- - - def atime(*args) ; File.ctime(*args) ; end - def ctime(*args) ; File.ctime(*args) ; end - def mtime(*args) ; File.mtime(*args) ; end - - def utime(*args) - $stderr.puts "utime #{args.join(' ')}" if verbose? - File.utime(*args) unless noop? - end - - # -- File IO Shortcuts ---------------------------------------------------- - - # Read file. - def read(path) - File.read(path) - end - - # Write file. - # - # @TODO should this be 'wb' mode? - def write(path, text) - $stderr.puts "write #{path}" if verbose? - File.open(path, 'w'){ |f| f << text } unless noop? - end - - # Append to file. - def append(path, text) - $stderr.puts "append #{path}" if verbose? - File.open(path, 'a'){ |f| f << text } unless noop? - end - - private # ----------------------------------------------------------------- - - # Returns FileUtils module based on mode. - def fileutils - if dryrun? - ::FileUtils::DryRun - elsif noop? - ::FileUtils::Noop - elsif verbose? - ::FileUtils::Verbose - else - ::FileUtils - end - end - - end - -end diff --git a/lib/ratch/shellutils.rb b/lib/ratch/shellutils.rb deleted file mode 100644 index 4338200..0000000 --- a/lib/ratch/shellutils.rb +++ /dev/null @@ -1,186 +0,0 @@ -module Ratch - - module ShellUtils - - module Verbose - include FileUtils::Verbose - include ShellUtils - extend self - end - - module NoWrite - include FileUtils::NoWrite - include ShellUtils - extend self - end - - module DryRun - include FileUtils::DryRun - include ShellUtils - extend self - end - - private - - # - def self.alias_options(name, *options) - options.each do |option| - case option - when :verbose - Verbose.module_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{name}(*args) - super(*fu_update_option(args, :verbose => true)) - end - #private :#{name} - EOS - when :noop - NoWrite.module_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{name}(*args) - super(*fu_update_option(args, :noop => true)) - end - #private :#{name} - EOS - DryRun.module_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{name}(*args) - super(*fu_update_option(args, :noop => true, :verbose => true)) - end - #private :#{name} - EOS - else - - end - end - end - - # -- FileTest Methods -- - - def size(path) ; FileTest.size(path) ; end - def size?(path) ; FileTest.size?(path) ; end - def directory?(path) ; FileTest.directory?(path) ; end - def dir?(path) ; FileTest.directory?(path) ; end - def symlink?(path) ; FileTest.symlink?(path) ; end - def readable?(path) ; FileTest.readable?(path) ; end - def chardev?(path) ; FileTest.chardev?(path) ; end - def exist?(path) ; FileTest.exist?(path) ; end - def exists?(path) ; FileTest.exists?(path) ; end - def zero?(path) ; FileTest.zero?(path) ; end - def pipe?(path) ; FileTest.pipe?(path) ; end - def file?(path) ; FileTest.file?(path) ; end - def sticky?(path) ; FileTest.sticky?(path) ; end - def blockdev?(path) ; FileTest.blockdev?(path) ; end - def grpowned?(path) ; FileTest.grpowned?(path) ; end - def setgid?(path) ; FileTest.setgid?(path) ; end - def setuid?(path) ; FileTest.setuid?(path) ; end - def socket?(path) ; FileTest.socket?(path) ; end - def owned?(path) ; FileTest.owned?(path) ; end - def writable?(path) ; FileTest.writable?(path) ; end - def executable?(path) ; FileTest.executable?(path) ; end - - def safe?(path) ; FileTest.safe?(path) ; end - - def relative?(path) ; FileTest.relative?(path) ; end - def absolute?(path) ; FileTest.absolute?(path) ; end - - def writable_real?(path) ; FileTest.writable_real?(path) ; end - def executable_real?(path) ; FileTest.executable_real?(path) ; end - def readable_real?(path) ; FileTest.readable_real?(path) ; end - - def identical?(path, other) - FileTest.identical?(path, other) - end - - alias_method :compare_file, :identical? - alias_method :cmp, :identical? - - # -- File Methods -- - - # Get creation timestamp. - def ctime(*args) - File.ctime(*args) - end - - # Get or set last access timestamp. - def atime(file, time=nil, opts={}) - opts, time = time, nil if Hash === time - if time - utime(time, file, opts) - else - File.atime(file) - end - end - - alias_options(:atime, :noop, :verbose) - - # - def mtime(file, time=nil, opts={}) - opts, time = time, nil if Hash === time - if time - utime(time, time, file, opts) - else - File.mtime(file) - end - end - - alias_options(:mtime, :noop, :verbose) - - # @TODO format atime and mtime whe printing - def utime(atime, mtime, *files) - opts = {} - opts = files.pop if Hash === files.last - $stderr.puts "utime #{atime} #{mtime} #{files.join(' ')}" if opts[:verbose] - File.utime(atime, mtime, *files) unless opts[:noop] - end - - alias_options(:utime, :noop, :verbose) - - # Read file. - def read(path) - File.read(path) - end - - # Write file. - # @TODO should this be 'wb' mode? - def write(path, text, opts={}) - $stderr.puts "write #{path}" if opts[:verbose] - File.open(path, 'w'){ |f| f << text } unless opts[:noop] - end - - alias_options(:write, :noop, :verbose) - - # Append to file. - def append(path, text, opts={}) - $stderr.puts "append #{path}" if opts[:verbose] - File.open(path, 'a'){ |f| f << text } unless opts[:noop] - end - - alias_options(:append, :noop, :verbose) - - # -- Dir -- - - # Glob pattern. Returns matches as strings. - def glob(*patterns, &block) - opts = (::Integer===patterns.last ? patterns.pop : 0) - matches = [] - patterns.each do |pattern| - matches.concat(Dir.glob(pattern, opts)) - end - if block_given? - matches.each(&block) - else - matches - end - end - - # TODO: Ultimately merge #glob and #multiglob. - def multiglob(*args, &blk) - Dir.multiglob(*args, &blk) - end - - # - def multiglob_r(*args, &blk) - Dir.multiglob_r(*args, &blk) - end - - end - -end diff --git a/lib/ratch/system.rb b/lib/ratch/system.rb deleted file mode 100644 index b6dee67..0000000 --- a/lib/ratch/system.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Ratch - - # TODO: Build it! - # - # The System class provides a robust interface for interacting with - # system commands. It is essenatially a wrapper around popen3 or popen4. - # - # Having a separate class rather integrating this into Shell (as - # Ruby's standard Shell class does) provides a better SOC. - # - class System - - end - -end diff --git a/lib/ratch/utils/config.rb b/lib/ratch/utils/config.rb index 922c10d..08c53db 100644 --- a/lib/ratch/utils/config.rb +++ b/lib/ratch/utils/config.rb @@ -36,14 +36,14 @@ def configuration(file) # Since they are YAML files, they can optionally end with '.yaml' or '.yml'. def configuration!(file) @configuration ||= {} - patt = file + "{.yml,.yaml,}" - path = Dir.glob(patt, File::FNM_CASEFOLD).find{ |f| File.file?(f) } + patt = localize(file) + "{.yml,.yaml,}" + path = Dir.glob(patt).find{ |f| File.file?(f) } if path # The || {} is in case the file is empty. - data = YAML::load(File.open(path)) || {} + data = YAML.load_file(path) || {} @configuration[file] = data else - raise LoadError, "Missing file -- #{path}" + raise LoadError, "Missing file -- #{file}" end end diff --git a/lib/ratch/utils/email.rb b/lib/ratch/utils/email.rb index ff58184..7025856 100644 --- a/lib/ratch/utils/email.rb +++ b/lib/ratch/utils/email.rb @@ -72,8 +72,7 @@ def environment_options end def new_with_environment(options={}) - environment_options.merge(options.rekey) - new(options) + new(environment_options.merge(options.rekey)) end end @@ -133,7 +132,7 @@ def initialize(options={}) # def email(options={}) - options.rekey + options = options.rekey message = options[:message] || self.message subject = options[:subject] || self.subject @@ -147,32 +146,33 @@ def email(options={}) raise ArgumentError, "missing email field -- mailto" unless mailto raise ArgumentError, "missing email field -- subject" unless subject - passwd ||= password("#{account} password:") + passwd = self.passwd mailto = [mailto].flatten.compact - msg = "" + msg = String.new msg << "From: #{from}\n" - msg << "To: #{mailto.join(';')}\n" + msg << "To: #{mailto.join(', ')}\n" msg << "Subject: #{subject}\n" - msg << "" - msg << message + msg << "\n" + msg << message.to_s #p server, port, domain, account, passwd, login, secure if verbose? begin - if Net::SMTP.respond_to?(:enable_tls) && secure - Net::SMTP.enable_tls - Net::SMTP.start(server, port, domain, account, passwd, login, secure) do |smtp| - smtp.send_message(msg, from, mailto) - end + smtp = Net::SMTP.new(server, port) + if secure + port == 465 ? smtp.enable_tls : smtp.enable_starttls + else + smtp.disable_starttls + end + if passwd.to_s.empty? + smtp.start(domain){ |s| s.send_message(msg, from, mailto) } else - Net::SMTP.start(server, port, domain, account, passwd, login) do |smtp| - smtp.send_message(msg, from, mailto) - end + smtp.start(domain, account, passwd, login){ |s| s.send_message(msg, from, mailto) } end return mailto - rescue Exception => e + rescue StandardError => e return e end end @@ -201,88 +201,11 @@ def password(msg=nil) # def require_smtp - begin - require 'facets/net/smtp_tls' - rescue LoadError - require 'net/smtp' - end + require 'net/smtp' + rescue LoadError + raise LoadError, "the `net-smtp` gem is needed to send email" end end end - - - -=begin - # Email function to easily send out an email. - # - # Settings: - # - # subject Subject of email message. - # from Message FROM address [email]. - # to Email address to send announcemnt. - # server Email server to route message. - # port Email server's port. - # domain Email server's domain name. - # account Email account name if needed. - # password Password for login.. - # login Login type: plain, cram_md5 or login [plain]. - # secure Uses TLS security, true or false? [false] - # message Mesage to send -or- - # file File that contains message. - # - def email(message, settings) - settings ||= {} - settings.rekey! - - server = settings[:server] - account = settings[:account] || ENV['EMAIL_ACCOUNT'] - passwd = settings[:password] || ENV['EMAIL_PASSWORD'] - login = settings[:login].to_sym - subject = settings[:subject] - mail_to = settings[:to] || settings[:mail_to] - mail_from = settings[:from] || settings[:mail_from] - secure = settings[:secure] - domain = settings[:domain] || server - - port ||= (secure ? 465 : 25) - account ||= mail_from - login ||= :plain - - #mail_to = nil if mail_to.empty? - - raise ArgumentError, "missing email field -- server" unless server - raise ArgumentError, "missing email field -- account" unless account - raise ArgumentError, "missing email field -- subject" unless subject - raise ArgumentError, "missing email field -- to" unless mail_to - raise ArgumentError, "missing email field -- from" unless mail_from - - passwd ||= password(account) - - mail_to = [mail_to].flatten.compact - - msg = "" - msg << "From: #{mail_from}\n" - msg << "To: #{mail_to.join(';')}\n" - msg << "Subject: #{subject}\n" - msg << "" - msg << message - - begin - Net::SMTP.enable_tls if Net::SMTP.respond_to?(:enable_tls) and secure - Net::SMTP.start(server, port, domain, account, passwd, login) do |s| - s.send_message( msg, mail_from, mail_to ) - end - puts "Email sent successfully to #{mail_to.join(';')}." - return true - rescue => e - if trace? - raise e - else - abort "Email delivery failed." - end - end - end -=end - diff --git a/lib/ratch/utils/ftp.rb b/lib/ratch/utils/ftp.rb deleted file mode 100644 index 2b02489..0000000 --- a/lib/ratch/utils/ftp.rb +++ /dev/null @@ -1,134 +0,0 @@ -module Ratch - - # FIXME: This module needs major work. Methods #ftp_files and - # ftp_stage_transfer need to either be generalized and moved to - # Shell or Script, or removed. - # - module FTPUtils - - def self.included(base) - require 'net/ftp' - require 'net/sftp' - end - - def self.extended(base) - included(base) - end - - # Use ftp to upload files. - # - def ftp(keys) - keys = upload_parameters(keys) - - # set transfer rules - if keys.stage - trans = ftp_stage_transfer(keys.stage) - else - ftp_files(keys.dir, keys.copy).each do |from| - trans << [from,from] - end - end - - # append location of publication dir to from - dir = keys.dir - trans.collect!{ |from,to| [File.join(dir,from), to] } - - if keys.dryrun - puts "ftp open #{keys.user}@#{keys.host}:#{keys.root}/" - keys.trans.each do |f, t| - puts "ftp put #{f} #{t}" - end - else - Net::FTP.open(keys.host) do |ftp| - ftp.login(keys.user) #password? - ftp.chdir(keys.root) - keys.trans.each do |f, t| - puts "ftp #{f} #{t}" unless keys.quiet - ftp.putbinaryfile( f, t, 1024 ) - end - end - end - end - - # Use sftp to upload files. - # - def sftp( keys ) - keys = upload_parameters(keys) - - # set transfer rules - if keys.stage - trans = ftp_stage_transfer(keys.stage) - else - ftp_files(keys.dir, keys.copy).each do |from| - trans << [from,from] - end - end - - # append location of publication dir to from - dir = keys.dir - trans.collect!{ |from,to| [File.join(dir,from), to] } - - if keys.dryrun - puts "sftp open #{keys.user}@#{keys.host}:#{keys.root}/" - keys.trans.each do |f,t| - puts "sftp put #{f} #{t}" - end - else - Net::SFTP.start(keys.host, keys.user, keys.pass) do |sftp| - #sftp.login( user ) - sftp.chdir(keys.root) - keys.trans.each do |f,t| - puts "sftp #{f} #{t}" unless keys.quiet - sftp.put_file(f,t) #, 1024 ) - end - end - end - end - - # Put together the list of files to copy. - def ftp_files( dir, copy ) - Dir.chdir(dir) do - del, add = copy.partition{ |f| /^[-]/ =~ f } - - # remove - and + prefixes - del.collect!{ |f| f.sub(/^[-]/,'') } - add.collect!{ |f| f.sub(/^[+]/,'') } - - #del.concat(must_exclude) - - ftp_files = [] - add.each{ |g| files += Dir.glob(g) } - del.each{ |g| files -= Dir.glob(g) } - - files.collect!{ |f| f.sub(/^\//,'') } - - return files - end - end - - # Combine three part stage list into a two part from->to list. - # - # Using the stage list of three space separated fields. - # - # fromdir file todir - # - # This is used to generate a from -> to list of the form: - # - # fromdir/file todir/file - # - def ftp_stage_transfer( list ) - trans = [] - list.each do |line| - trans << Shellwords.shellwords(line) - end - - trans.collect! do |from, base, to| - file = File.join(from,base) - to = File.join(to,base) - [from, to] - end - end - - end - -end diff --git a/lib/ratch/utils/pom.rb b/lib/ratch/utils/pom.rb deleted file mode 100644 index 07beb7e..0000000 --- a/lib/ratch/utils/pom.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Ratch - - # Methods for utilizing Ruby POM. - module POMUtils - - def self.included(base) - require 'pom' - end - - def self.extended(base) - included(base) - end - - # - def project - @project ||= ::POM::Project.new - end - - end - -end - diff --git a/lib/ratch/utils/rdoc.rb b/lib/ratch/utils/rdoc.rb index 8ca641a..6ba80cd 100644 --- a/lib/ratch/utils/rdoc.rb +++ b/lib/ratch/utils/rdoc.rb @@ -16,18 +16,15 @@ def rdoc(*files) require 'rdoc/rdoc' options = Hash===files.last ? files.pop : {} - options.rekey!(&:to_s) + options = options.rekey(&:to_s) - options['title'] ||= options.delete('T') - - options['debug'] = options['debug'] #|| debug? - options['quiet'] = options['quiet'] #|| quiet? - options['verbose'] = options['verbose'] #|| verbose? + title = options.delete('T') + options['title'] ||= title if title # apply pom (todo?) #options['title'] ||= metadata.title - options = DEFAULT_RDOC_OPTIONS.merge(options) + options = DEFAULT_RDOC_OPTIONS.rekey(&:to_s).merge(options) locally do rdoc = RDoc::RDoc.new diff --git a/lib/ratch/utils/tar.rb b/lib/ratch/utils/tar.rb index fcc2696..11750ce 100644 --- a/lib/ratch/utils/tar.rb +++ b/lib/ratch/utils/tar.rb @@ -2,87 +2,131 @@ module Ratch - # Utility methods for working with tarballs archives. - #-- - # TODO: Add compress support ? - # TODO: Add bzip support ? - #++ + # Utility methods for working with tar archives. They use the tar + # reader and writer that come with RubyGems, so nothing else is needed. + # + # Regular files and directories are archived; links and special files + # are skipped. module TarUtils - # When included include GZipUtils too. + # When included, include ZlibUtils too. def self.included(base) - #require 'zlib' - include ZLibUtils - require 'archive/tar/minitar' + require 'rubygems/package' + base.__send__(:include, ZlibUtils) end # def self.extended(base) - included(base) + require 'rubygems/package' + base.extend(ZlibUtils) end - # Tar + # Archive a folder as FOLDER.tar, or as +file+. Returns the archive's + # path. def tar(folder, file=nil, options={}) + options, file = file, nil if Hash === file noop, verbose = *util_options(options) - file ||= File.basename(File.expand_path(folder)) + '.tar' - cmd = "tar -cf #{file} #{folder}" - puts cmd if verbose - unless noop - locally do - gzIO = File.open(file, 'wb') - Archive::Tar::Minitar.pack(folder, gzIO) - end - end + + file ||= File.basename(localize(folder)) + '.tar' + + $stderr.puts "tar -cf #{file} #{folder}" if verbose + + File.open(localize(file), 'wb'){ |io| tar_pack(folder, io) } unless noop + path(file) end - # Untar + # Unpack a tar archive into the working directory. Returns the paths + # unpacked. def untar(file, options={}) noop, verbose = *util_options(options) - #file ||= File.basename(File.expand_path(folder)) + '.tar' - cmd = "untar #{file}" - puts cmd if verbose - unless noop - locally do - gzIO = File.open(file, 'wb') - Archive::Tar::Minitar.unpack(gzIO) - end - end - path(file) + + $stderr.puts "tar -xf #{file}" if verbose + + return [] if noop + + File.open(localize(file), 'rb'){ |io| tar_unpack(io) } end - # Tar Gzip + # Archive a folder as FOLDER.tar.gz, or as +file+. Returns the + # archive's path. def tar_gzip(folder, file=nil, options={}) + options, file = file, nil if Hash === file noop, verbose = *util_options(options) - file ||= File.basename(File.expand_path(folder)) + '.tar.gz' # '.tgz' which ? - cmd = "tar --gzip -czf #{file} #{folder}" - puts cmd if verbose - unless noop - locally do #folder, file = localize(folder), localize(file) - gzIO = Zlib::GzipWriter.new(File.open(file, 'wb')) - Archive::Tar::Minitar.pack(folder, gzIO) - end - end + + file ||= File.basename(localize(folder)) + '.tar.gz' + + $stderr.puts "tar -czf #{file} #{folder}" if verbose + + Zlib::GzipWriter.open(localize(file)){ |gz| tar_pack(folder, gz) } unless noop + path(file) end alias_method :tar_z, :tar_gzip - # Untar Gzip - # - # FIXME: Write unified untar_gzip function. + # Unpack a gzipped tar archive into the working directory. Returns + # the paths unpacked. def untar_gzip(file, options={}) - untar(ungzip(file, options), options) + noop, verbose = *util_options(options) + + $stderr.puts "tar -xzf #{file}" if verbose + + return [] if noop + + Zlib::GzipReader.open(localize(file)){ |gz| tar_unpack(gz) } end alias_method :untar_z, :untar_gzip - #def tgz(folder, file=nil, options={}) - # file ||= File.basename(File.expand_path(folder)) + '.tgz' - # tar_gzip(folder, file, options) - #end + private + + # Write the folder and all in it to +io+ as a tar archive, with paths + # as given, relative to the working directory. + def tar_pack(folder, io) + folder = folder.to_s.chomp('/') + Gem::Package::TarWriter.new(io) do |tar| + ([folder] + glob(File.join(folder, '**/*'), File::FNM_DOTMATCH)).uniq.each do |entry| + next if entry =~ /(\A|\/)\.\.?\z/ + real = localize(entry) + stat = File.lstat(real) + if stat.directory? + tar.mkdir(entry, stat.mode & 0777) + elsif stat.file? + tar.add_file_simple(entry, stat.mode & 0777, stat.size) do |out| + File.open(real, 'rb'){ |f| IO.copy_stream(f, out) } + end + end + end + end + end + + # Unpack the tar archive read from +io+ into the working directory. + # An entry that would land outside it is refused. + def tar_unpack(io) + paths = [] + Gem::Package::TarReader.new(io) do |tar| + tar.each do |entry| + name = entry.full_name + dest = File.expand_path(File.join(work.to_s, name)) + unless dest == work.to_s || dest.start_with?(work.to_s + '/') + raise ArgumentError, "tar entry outside of the directory -- #{name}" + end + if entry.directory? + ::FileUtils.mkdir_p(dest) + elsif entry.file? + ::FileUtils.mkdir_p(File.dirname(dest)) + File.open(dest, 'wb'){ |f| IO.copy_stream(entry, f) } + File.chmod(entry.header.mode & 0777, dest) + else + next + end + paths << name + end + end + paths + end end end - diff --git a/lib/ratch/utils/xdg.rb b/lib/ratch/utils/xdg.rb index d9132e9..e8e0b60 100644 --- a/lib/ratch/utils/xdg.rb +++ b/lib/ratch/utils/xdg.rb @@ -15,9 +15,8 @@ module XDGUtils def self.included(base) begin require 'xdg' - rescue - $stderr << "The `xdg` gem is needed to use the XDGUtils module." - exit -1 + rescue LoadError + raise LoadError, "the `xdg` gem is needed to use the XDGUtils module" end end diff --git a/lib/ratch/utils/zlib.rb b/lib/ratch/utils/zlib.rb index 8da9b0e..dcc1e20 100644 --- a/lib/ratch/utils/zlib.rb +++ b/lib/ratch/utils/zlib.rb @@ -14,11 +14,12 @@ def self.extended(base) # Create a gzip file. def gzip(file, tofile=nil, options={}) + options, tofile = tofile, nil if Hash === tofile noop, verbose = *util_options(options) - tofile ||= File.basename(file) + '.gz' + tofile ||= file.to_s + '.gz' - puts "gzip #{file}" if verbose + $stderr.puts "gzip #{file}" if verbose file = localize(file) tofile = localize(tofile) @@ -34,9 +35,9 @@ def gzip(file, tofile=nil, options={}) def ungzip(file, options={}) noop, verbose = *util_options(options) - fname = File.basename(file).chomp(File.extname(file)) + fname = file.to_s.chomp(File.extname(file.to_s)) - puts "ungzip #{file}" if verbose + $stderr.puts "ungzip #{file}" if verbose fname = localize(fname) file = localize(file) diff --git a/lib/ratch/version.rb b/lib/ratch/version.rb new file mode 100644 index 0000000..3db8885 --- /dev/null +++ b/lib/ratch/version.rb @@ -0,0 +1,3 @@ +module Ratch + VERSION = '2.0.0' +end diff --git a/man/ratch.1 b/man/ratch.1 deleted file mode 100644 index 7b2e78a..0000000 --- a/man/ratch.1 +++ /dev/null @@ -1,28 +0,0 @@ -.\" NAME -.\" ratch - ruby-based batch files -.\" -.\" SYNOPSIS -.\" reap [-n] [-h] [file] -.\" -.\" DESCRIPTION -.\" Ratch is batch file system using a Ruby=based DSL. -.\" -.\" OPTIONS -.\" -h help This option displays help. -.\" -n dryrun Dry-run/no-harm mode. -.\" -.\" ENVIRONMENT -.\" PAGER name of paging command, usually more(1), or less(1). If not set -.\" falls back to more(1). -.\" -.\" EXAMPLES -.\" Try this command to format this text itself: -.\" -.\" $ txt2man -h 2>&1 | txt2man -T -.\" -.\" SEE ALSO: -.\" ruby(1). -.\" -.\" AUTHOR: -.\" 7rans - diff --git a/ratch.gemspec b/ratch.gemspec new file mode 100644 index 0000000..e78f114 --- /dev/null +++ b/ratch.gemspec @@ -0,0 +1,47 @@ +require_relative 'lib/ratch/version' + +Gem::Specification.new do |s| + s.name = 'ratch' + s.version = Ratch::VERSION + s.summary = 'A file system shell in code, and batch scripts in Ruby' + s.description = 'Ratch provides a Shell object that stands at a directory and works from there, ' \ + 'as a shell prompt does: file tests, file operations, globbing and system commands, ' \ + 'with dry-run and trace modes. Batch does the same over a list of files, and the ' \ + 'ratch command runs a Ruby script inside a Shell.' + + s.authors = ['Trans'] + s.email = ['transfire@gmail.com'] + s.homepage = 'https://github.com/rubyworks/ratch' + s.license = 'Apache-2.0' + + s.metadata = { + 'homepage_uri' => s.homepage, + 'source_code_uri' => 'https://github.com/rubyworks/ratch', + 'bug_tracker_uri' => 'https://github.com/rubyworks/ratch/issues', + 'changelog_uri' => 'https://github.com/rubyworks/ratch/blob/master/HISTORY.rdoc', + 'documentation_uri' => 'https://rubydoc.info/gems/ratch' + } + + s.required_ruby_version = '>= 3.1' + + s.files = Dir[ + 'lib/**/*.rb', 'bin/*', + 'README.rdoc', 'HISTORY.rdoc', 'LICENSE.txt' + ] + s.bindir = 'bin' + s.executables = ['ratch', 'ludo'] + s.require_paths = ['lib'] + s.extra_rdoc_files = ['README.rdoc', 'HISTORY.rdoc', 'LICENSE.txt'] + + s.add_dependency 'facets', '>= 4.0' + + # For EmailUtils; a bundled gem, not a default one, since Ruby 3.1. + s.add_development_dependency 'net-smtp' + # For RDocUtils; a bundled gem since Ruby 4.0. + s.add_development_dependency 'rdoc' + + 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 diff --git a/spec/01_shell.rdoc b/spec/01_shell.rdoc deleted file mode 100644 index 7c683ac..0000000 --- a/spec/01_shell.rdoc +++ /dev/null @@ -1,198 +0,0 @@ -= Ratch::Shell - -The Shell class mimics a basic shell command line prompt. - - require 'ratch/shell' - -The demonstration sets up sample directory consisting of the following -entires in the tmp/qed directory: - - foo.txt - zoo/ - zoo/bar.txt - -== Initial Path - -When no path argument is provided to the initializer, the present working path -is used. The path is stored as a Pathname object. - - shell = Ratch::Shell.new - shell.work.assert = Pathname.new(Dir.pwd).expand_path - -Otherwise the path given is used. - - shell = Ratch::Shell.new('.') - shell.work.assert = Pathname.new('.').expand_path - - shell = Ratch::Shell.new('..') - shell.work.assert = Pathname.new('..').expand_path - -An error is raise if the path does not exist. - - expect Ratch::FileNotFound do - Ratch::Shell.new('not_a_path') - end - -== Processing Options - -The +initialize+ method accepts a few options. The +quiet+ option supresses -all output to stdout. - - shell = Ratch::Shell.new(:quiet=>true) - shell.assert.quiet? - -The +noop+ option prevents any actual writing to disk --the process will -simply pretend that it has done so. - - shell = Ratch::Shell.new(:noop=>true) - shell.assert.noop? - -The +trace+ option provides step by step feedback on what is taking place. - - shell = Ratch::Shell.new(:trace=>true) - shell.assert.trace? - -The +dryrun+ option is simply a compbination of +noop+ and +trace+. - - shell = Ratch::Shell.new(:dryrun=>true) - shell.assert.noop? - shell.assert.trace? - shell.assert.dryrun? - -== Equality - -For two Shell objects to be considered equal, via #==, they must both -be instances of Ratch::Shell (or subclass) and have the same working -path. - - shell1 = Ratch::Shell.new('.') - shell2 = Ratch::Shell.new('.') - shell1.assert = shell2 - - shell1 = Ratch::Shell.new('.') - shell2 = Ratch::Shell.new('..') - shell1.refute = shell2 - -The more strict #eql? method also ensures that the +noop+ option is the same. - - shell1 = Ratch::Shell.new('.', :noop=>true) - shell2 = Ratch::Shell.new('.', :noop=>true) - shell1.assert.eql? shell2 - - shell1 = Ratch::Shell.new('.', :noop=>true) - shell2 = Ratch::Shell.new('.', :noop=>false) - shell1.refute.eql? shell2 - -== File System Locations - -The Shell class provides a few convenient methods for accessing common -locations in the file system, namely #work, #home, #parent and #root. - - shell = Ratch::Shell.new - - shell.work.assert == Pathname.new('.').expand_path - shell.parent.assert == Pathname.new('..').expand_path - -The current user's home directoryis accessible via the #home method. - - shell.home.assert == Pathname.new('~').expand_path - -The system's root folder can be accessed via #root method. - - shell.root.assert == Pathname.new('/').expand_path - -In addition the Shell class provides methods for accessing pathnames -relative to the current shell directory. The #path (or #pathname) method -returns a Pathname object with the given path. - - shell.path('foo') - -This will work regardless if the path actually exists or not. On the other hand, -the #file and #dir methods will do the same, but will raise an error if the path -given is not an existing file or a directory, respectively. - - shell.file('foo.txt') - - expect Ratch::FileNotFound do - shell.file('not.txt') - end - - shell.dir('zoo') - - expect Ratch::FileNotFound do - shell.dir('not') - end - -== Entries - -Shell#entries works just like Dir.entries except that each path is returned -as a Pathname object. - - shell = Ratch::Shell.new - - shell.entries.assert == ['foo.txt', '.', '..', 'zoo'].map{|f| Pathname.new(f)} - -The #file_entries method limits the list to files only. - - shell.file_entries.assert == ['foo.txt'].map{|f| Pathname.new(f)} - -Whereas #directory_entries (or #dir_entries) limits the list to directories. - - shell.directory_entries.assert == ['.', '..', 'zoo'].map{|f| Pathname.new(f)} - -Of course, having to deal with the '.' and '..' is annoying most of the time -so Shell provides more convenient methods. Like #entries, #pathnames -provides a list of entries less the dot paths. - - shell.pathnames.assert == ['foo.txt', 'zoo'].map{|f| Pathname.new(f)} - -The #directories (also #folders) method limits this list to directories only. - - shell.directories.assert == ['zoo'].map{|f| Pathname.new(f)} - -And #files works out to be the same as #file_entires. - - shell.files.assert == ['foo.txt'].map{|f| Pathname.new(f)} - -== Globbing - - shell = Ratch::Shell.new - - shell.glob('*').assert == ['foo.txt', 'zoo'] - -== File Testing - -Shell provides an interface to most of FileTest's functions. - - shell.assert.exist?('foo.txt') - shell.assert.file?('foo.txt') - shell.refute.directory?('foo.txt') - shell.assert.directory?('zoo') - -== File IO - -Shell can be used to easily read the contents of a file. - - shell = Ratch::Shell.new - - shell.read('foo.txt').assert == 'SAMPLE FOO.TXT' - -As well as write a new file. - - shell.write('baz.txt', 'BAZ TEXT') - shell.read('baz.txt').assert == 'BAZ TEXT' - -Or append to an existing file. - - shell.append('baz.txt', ' 2') - shell.read('baz.txt').assert == 'BAZ TEXT 2' - -The shell command supports many file methods, including #rm. - - shell.rm('baz.txt') - -== System Calls - -The Shell class can also call out to system commands. This is handled -by the Ratch::System class. See the system.rdoc file for details. - diff --git a/spec/02_script.rdoc b/spec/02_script.rdoc deleted file mode 100644 index 075e84a..0000000 --- a/spec/02_script.rdoc +++ /dev/null @@ -1,34 +0,0 @@ -= Ratch::Script - -The Ratch::Script class is the context used for evaluating Ratch-based -batch files, aka shell scripts. - - require 'ratch/script' - -In most every respect the Script class behaves like Ratch::Shell, except that -its initializer takes a file name to be evaluated. - -Let's say we have a Ratch script called 'foo.ratch': - - #!/usr/bin/env ratch - - @test_message = "Hello World!" - -We can load the script via Ratch::Script.new. - - script = Ratch::Script.new('foo.ratch') - -The file name can be accessed from the script using #script_file. - - script.script_file.assert == 'foo.ratch' - -To execute a script, use the `#execute!` method, or it's alias `#run!`. - - script.execute! - -We can see that the script did indeed execute by plubming for the instance -variable it set. - - msg = script.instance_variable_get('@test_message') - msg.assert == "Hello World!" - diff --git a/spec/03_batch.rdoc b/spec/03_batch.rdoc deleted file mode 100644 index 3956d31..0000000 --- a/spec/03_batch.rdoc +++ /dev/null @@ -1,71 +0,0 @@ -= Ratch::Batch - -The Batch class makes makes it possible to work with multiple files -at once as easily as one would work with a single file. - - require 'ratch/batch' - -The demonstration sets up a sample directory consisting of the following -entires in the temporary working directory: - - foo.txt - bar.txt - zoo/ - zoo/one.txt - zoo/two.txt - -To create a new Batch instance, pass the the base directory and any -inclusion patterns to the initializer. - - batch = Ratch::Batch.new('.', '*.txt') - -In this example we will get every `.txt` file at the toplevel of the base -directory. - - batch.to_a.assert = ['foo.txt', 'bar.txt'].to_pathnames - -To get a list of files relative to the base directory, use #entries. - - batch.entries.assert = ['foo.txt', 'bar.txt'].to_pathnames - -Internally a Batch instance tracks the files selected via a Ratch::FileList -object. This can be directly accessed via the #list method. - - batch.file_list.assert.is_a?(Ratch::FileList) - - batch.file_list.to_a.assert = ['foo.txt', 'bar.txt'] - -As with the delegated FileTest methods of the Shell class, Batch can test -the set of files in agregate. For example, to ensure all the entries -are files we can use the #file? method. - - batch.assert.file? - -Likewise to enusre none the entires are directories we can use the #directory? -method. - - batch.refute.directory? - -The Batch list can be reduced to just files or just directories via the #file! -and #directory! methods. - - batch = Ratch::Batch.new('.', '*') - batch.file! - batch.list.assert = ['foo.txt', 'bar.txt'] - - batch = Ratch::Batch.new('.', '*') - batch.directory! - batch.list.assert = ['zoo'] - -The Batch class is enumerable, both #each and #size are defined. - - batch = Ratch::Batch.new('.', '*.txt') - - batch.each do |pathname| - pathname.assert.is_a?(Pathname) - end - - batch.size.assert = 2 - -Any enumerable method is likewise applicable. - diff --git a/spec/04_system.rdoc b/spec/04_system.rdoc deleted file mode 100644 index d74413b..0000000 --- a/spec/04_system.rdoc +++ /dev/null @@ -1,3 +0,0 @@ -= Ratch::System - - diff --git a/spec/applique/array.rb b/spec/applique/array.rb deleted file mode 100644 index 0c7c01f..0000000 --- a/spec/applique/array.rb +++ /dev/null @@ -1,8 +0,0 @@ -class ::Array - - # Helper extension for comparison tests. - def to_pathnames - map{ |f| Pathname.new(f) } - end - -end diff --git a/spec/applique/setup.rb b/spec/applique/setup.rb deleted file mode 100644 index 97515de..0000000 --- a/spec/applique/setup.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'fileutils' - -Before :demo do - clear_working_directory! -end - -When "consisting of the following entires" do |text| - text.split(/\s+/).each do |file| - if /\/$/ =~ file - FileUtils.mkdir_p(file) unless File.directory?(file) - else - File.open(file, 'w+'){ |f| f << "SAMPLE #{file}".upcase } - end - end -end - -When "Let's say we have a Ratch script called '(((.*?)))'" do |file, text| - File.open(file, 'w'){ |f| f << text } -end - diff --git a/task/test.watchr b/task/test.watchr deleted file mode 100644 index 3a4fb6e..0000000 --- a/task/test.watchr +++ /dev/null @@ -1,41 +0,0 @@ -# Run me with: -# $ watchr task/test.watchr - -# -------------------------------------------------- -# Rules -# -------------------------------------------------- -watch('^test.*/case_.*\.rb') { |m| ko m[0] } - -watch( '^lib/(.*)\.rb') do |m| - dir, file = File.split(m[1]) - dir = '' if dir == '.' - ko File.join('test', dir, "case_#{file}.rb") -end - -#watch( '^test/helper\.rb' ) { ko tests } - -# -------------------------------------------------- -# Signal Handling -# -------------------------------------------------- -Signal.trap('QUIT') { ko tests } # Ctrl-\ -Signal.trap('INT' ) { abort("\n") } # Ctrl-C - -# -------------------------------------------------- -# Helpers -# -------------------------------------------------- -def ko(*paths) - run "ko #{gem_opt} -Ilib:test #{paths.flatten.join(' ')}" -end - -def tests - Dir['test/**/*_case.rb'] -end - -def run( cmd ) - puts cmd - system cmd -end - -def gem_opt - defined?(Gem) ? "-rubygems" : "" -end diff --git a/test/case_batch.rb b/test/case_batch.rb index e5f1128..443204f 100644 --- a/test/case_batch.rb +++ b/test/case_batch.rb @@ -1,63 +1,264 @@ -require 'ratch/batch' +testcase Ratch::Batch do -KO.case Ratch::Batch do + # Run the block from inside the sample directory. + def in_sample + sample_dir do |dir| + Dir.chdir(dir){ yield dir } + end + end - def initialize - stage_clear - stage_fake %w{a.txt b.txt d/x.txt d/y.txt} + context "the list" do - @batch1 = Ratch::Batch.new('.') - @batch2 = Ratch::Batch.new('.', '*') - @batch3 = Ratch::Batch.new('.', '**/*') - end + test "files are taken by pattern under the batch's directory" do + in_sample do + batch = Ratch::Batch.new('.', '*.txt') + batch.local.assert == Pathname.new('.') + batch.to_a.sort.assert == pathnames('bar.txt', 'foo.txt') + batch.list.sort.assert == %w{bar.txt foo.txt} + batch.file_list.assert.is_a?(Ratch::FileList) + batch.size.assert == 2 + end + end - test :local do - @batch1.local == Pathname.new('.') - end + test "a batch of another directory lists full paths, and #entries the local ones" do + sample_dir do |dir| + batch = Ratch::Batch.new(dir, '**/*.txt') + batch.list.sort.assert == %w{bar.txt foo.txt zoo/one.txt zoo/two.txt}.map{ |f| File.join(dir, f) } + batch.entries.sort.assert == pathnames('bar.txt', 'foo.txt', 'zoo/one.txt', 'zoo/two.txt') + end + end - test :list do - @batch1.list.is_a?(Array) - end + test "it is enumerable, over Pathnames" do + in_sample do + batch = Ratch::Batch.new('.', '*.txt') + batch.each{ |pn| pn.assert.is_a?(Pathname) } + batch.map{ |pn| pn.extname }.assert == %w{.txt .txt} + end + end + + test "#file! and #directory! narrow the list" do + in_sample do + batch = Ratch::Batch.new('.', '*') + batch.file! + batch.list.sort.assert == %w{bar.txt foo.txt} + + batch = Ratch::Batch.new('.', '*') + batch.directory! + batch.list.assert == %w{zoo} + + batch = Ratch::Batch.new('.', '*') + batch.select!{ |f| f =~ /^f/ } + batch.list.assert == %w{foo.txt} + end + end + + test "backup files are left out, unless all are wanted" do + in_sample do + File.write('foo.txt~', '') + File.write('foo.bak', '') + Ratch::Batch.new('.', '*').list.sort.assert == %w{bar.txt foo.txt zoo} + Ratch::Batch.all('.', '*').list.sort.assert == %w{bar.txt foo.bak foo.txt foo.txt~ zoo} + end + end - test :file_list do - @batch1.file_list.is_a?(Ratch::FileList) end - test :each do - r = [] - @batch2.each{ |pn| r << pn } - r.map(&:to_s).sort == %w{a.txt b.txt d} + context "file tests" do + + test "a test holds if it holds for every file" do + in_sample do + batch = Ratch::Batch.new('.', '*.txt') + batch.assert.file? + batch.assert.exist? + batch.assert.exists? + batch.assert.readable? + batch.refute.directory? + Ratch::Batch.new('.', '*').refute.file? + Ratch::Batch.new('.', 'zoo').assert.directory? + end + end + + test "#byte_size adds up" do + in_sample do + Ratch::Batch.new('.', '*.txt').byte_size.assert == 28 + end + end + + test "#outofdate? and #uptodate?" do + in_sample do + old = Time.now - 100 + File.utime(old, old, 'foo.txt') + batch = Ratch::Batch.new('.', 'zoo/*') + batch.assert.outofdate?('foo.txt') + batch.refute.uptodate?('foo.txt') + batch.assert.outofdate?('nothing') + File.utime(old - 100, old - 100, 'zoo/one.txt', 'zoo/two.txt') + batch.refute.outofdate?('foo.txt') + batch.assert.uptodate?('foo.txt') + end + end + end - test "passes #each thru to Enumerable methods" do - @batch2.all?{ |pn| pn.is_a? Pathname } + context "file operations" do + + test "#cp and #mv into a directory" do + in_sample do + Dir.mkdir('out') + Ratch::Batch.new('.', '*.txt').cp('out') + Dir.children('out').sort.assert == %w{bar.txt foo.txt} + Ratch::Batch.new('.', 'zoo/*').mv('out') + Dir.children('out').sort.assert == %w{bar.txt foo.txt one.txt two.txt} + Dir.children('zoo').assert == [] + end + end + + test "the destination is taken from the batch's directory" do + sample_dir do |dir| + Ratch::Batch.new(dir, '*.txt').cp('zoo') + Dir.children(File.join(dir, 'zoo')).sort.assert == %w{bar.txt foo.txt one.txt two.txt} + end + end + + test "#rm, #touch and #chmod" do + in_sample do + Ratch::Batch.new('.', '*.txt').chmod(0600) + (File.stat('foo.txt').mode & 0777).assert == 0600 + old = Time.now - 100 + File.utime(old, old, 'foo.txt') + Ratch::Batch.new('.', '*.txt').touch + (File.mtime('foo.txt') > old).assert == true + Ratch::Batch.new('.', '*.txt').rm + Dir.children('.').assert == %w{zoo} + Ratch::Batch.new('.', 'zoo').rm_r + Dir.children('.').assert == [] + end + end + + test "#mkdir_p makes a directory for every entry" do + in_sample do + Ratch::Batch.new('.', 'a/b', 'c').mkdir_p + File.assert.directory?('a/b') + File.assert.directory?('c') + Errno::EEXIST.assert.raised?{ Ratch::Batch.new('.', 'foo.txt').mkdir_p } + end + end + + test "#ln_s and #install" do + in_sample do + Dir.mkdir('out') + Ratch::Batch.new('.', 'zoo/*').ln_s('out') + File.assert.symlink?('out/one.txt') + Dir.mkdir('bin') + Ratch::Batch.new('.', '*.txt').install('bin', 0755) + (File.stat('bin/foo.txt').mode & 0777).assert == 0755 + end + end + + test "#stage hard links each file at its local path" do + sample_dir do |dir| + Ratch::Batch.new(dir, '**/*.txt').stage('stage') + Dir.glob('**/*', base: File.join(dir, 'stage')).sort.assert == %w{bar.txt foo.txt zoo zoo/one.txt zoo/two.txt} + File.assert.identical?(File.join(dir, 'foo.txt'), File.join(dir, 'stage/foo.txt')) + end + end + + test "#rename moves each file to the name the block gives" do + in_sample do + batch = Ratch::Batch.new('.', '*.txt') + batch.rename{ |f| f.sub('.txt', '.text') } + Dir.children('.').sort.assert == %w{bar.text foo.text zoo} + batch.list.sort.assert == %w{bar.text foo.text} + end + end + + test "#rename leaves alone a file the block gives nil for" do + in_sample do + Ratch::Batch.new('.', '*.txt').rename{ |f| f =~ /foo/ ? 'FOO' : nil } + Dir.children('.').sort.assert == %w{FOO bar.txt zoo} + end + end + + test "#map_cp refuses to copy over an existing file" do + in_sample do + Errno::EEXIST.assert.raised? do + Ratch::Batch.new('.', 'foo.txt').map_cp{ |f| 'bar.txt' } + end + File.read('bar.txt').assert == 'SAMPLE BAR.TXT' + Ratch::Batch.new('.', 'foo.txt').map_cp(:force=>true){ |f| 'bar.txt' } + File.read('bar.txt').assert == 'SAMPLE FOO.TXT' + end + end + end - test :size do - batch = Ratch::Batch.new('.', '*') - batch.size == 3 + context "modes" do + + test "noop changes nothing" do + in_sample do + batch = Ratch::Batch.new('.', '*.txt', :noop=>true) + batch.assert.noop? + batch.rm + batch.mv('zoo') + batch.rename{ |f| f + '.x' } + Dir.children('.').sort.assert == %w{bar.txt foo.txt zoo} + end + end + + test "dryrun reports and does nothing" do + in_sample do + batch = Ratch::Batch.new('.', '*.txt', :dryrun=>true) + batch.assert.dryrun? + out = capture_stderr{ batch.rm } + out.assert.include?('rm ') + out.assert.include?('foo.txt') + File.assert.exist?('foo.txt') + end + end + + test "a mode can be given for one command" do + in_sample do + Ratch::Batch.new('.', '*.txt').rm(:noop=>true) + File.assert.exist?('foo.txt') + end + end + end - test :directory? do - batch = Ratch::Batch.new('.', '*') - not batch.directory? +end + +testcase Ratch::FileList do + + test "it is lazy, and resolves its patterns when read" do + sample_dir do |dir| + Dir.chdir(dir) do + list = Ratch::FileList['*.txt'] + File.write('new.txt', '') + list.sort.assert == %w{bar.txt foo.txt new.txt} + end + end end - test :file? do - not @batch2.file? + test "#include and #exclude" do + sample_dir do |dir| + Dir.chdir(dir) do + list = Ratch::FileList.new('*.txt') + list.include('zoo/*') + list.exclude(/one/) + list.exclude('bar.*') + list.sort.assert == %w{foo.txt zoo/two.txt} + end + end end - test :directory! do - batch = Ratch::Batch.new('.', '*') - batch.directory! - batch.filenames == %w{d} + test "#ext and #sub" do + Ratch::FileList['a.c', 'b.c'].ext('o').assert == %w{a.o b.o} + Ratch::FileList['a.c', 'b.c'].sub(/\.c$/, '.h').assert == %w{a.h b.h} end - test :file! do - batch = Ratch::Batch.new('.', '*') - batch.file! - batch.filenames.sort == %w{a.txt b.txt} + test "it compares with an Array" do + (Ratch::FileList['a', 'b'] == %w{a b}).assert == true + Ratch::FileList['a', 'b'].to_a.assert.is_a?(Array) end end - diff --git a/test/case_script.rb b/test/case_script.rb new file mode 100644 index 0000000..8cb9d64 --- /dev/null +++ b/test/case_script.rb @@ -0,0 +1,91 @@ +testcase Ratch::Script do + + # Run a command of Ratch's own, from +dir+, and return its output and status. + def run_bin(name, dir, *args) + lib = File.expand_path('lib') + bin = File.expand_path("bin/#{name}") + out = IO.popen([RbConfig.ruby, "-I#{lib}", bin, *args, :chdir=>dir, :err=>[:child, :out]]){ |io| io.read } + [out, $?.exitstatus] + end + + test "a script is run inside a shell" do + sample_dir do |dir| + File.write(File.join(dir, 'foo.ratch'), "@message = read('foo.txt')\nmkdir 'made'\n") + script = Ratch::Script.new(File.join(dir, 'foo.ratch'), dir) + script.script_file.assert == File.join(dir, 'foo.ratch') + script.execute! + script.instance_variable_get('@message').assert == 'SAMPLE FOO.TXT' + File.assert.directory?(File.join(dir, 'made')) + end + end + + test "$0 is the script while it runs" do + sample_dir do |dir| + file = File.join(dir, 'foo.ratch') + File.write(file, "@zero = $0\n") + script = Ratch::Script.new(file, dir) + old = $0 + script.run! + script.instance_variable_get('@zero').assert == file + $0.assert == old + end + end + + test "#define_method adds a method to the script" do + sample_dir do |dir| + file = File.join(dir, 'foo.ratch') + File.write(file, "define_method(:okay){ 'okay' }\n@said = okay\n") + script = Ratch::Script.new(file, dir) + script.execute! + script.instance_variable_get('@said').assert == 'okay' + end + end + + test "the ratch command runs a script in the present directory" do + sample_dir do |dir| + File.write(File.join(dir, 'foo.ratch'), "puts glob('*.txt').sort.join(' ')\np arguments\n") + out, status = run_bin('ratch', dir, 'foo.ratch', 'a', 'b') + out.assert == "bar.txt foo.txt\n[\"a\", \"b\"]\n" + status.assert == 0 + end + end + + test "the ratch command takes the shell's modes as options" do + sample_dir do |dir| + File.write(File.join(dir, 'foo.ratch'), "rm 'foo.txt'\n") + out, status = run_bin('ratch', dir, 'foo.ratch', '--dryrun') + out.assert == "rm foo.txt\n" + File.assert.exist?(File.join(dir, 'foo.txt')) + end + end + + context "ludo" do + + test "it runs a script found in a directory above, from that directory, with the arguments" do + sample_dir do |dir| + File.write(File.join(dir, 'hello'), "#!/bin/sh\necho \"in $(pwd) with $*\"\nexit 3\n") + File.chmod(0755, File.join(dir, 'hello')) + out, status = run_bin('ludo', File.join(dir, 'zoo'), 'hello', 'x', 'y') + out.assert == "in #{dir} with x y\n" + status.assert == 3 + end + end + + test "it says so when there is no such script" do + sample_dir do |dir| + out, status = run_bin('ludo', dir, 'no-such-script-anywhere') + out.assert == "ludo: script not found -- no-such-script-anywhere\n" + status.assert == 1 + end + end + + test "a file that is not executable is passed over" do + sample_dir do |dir| + out, status = run_bin('ludo', File.join(dir, 'zoo'), 'foo.txt') + status.assert == 1 + end + end + + end + +end diff --git a/test/case_shell.rb b/test/case_shell.rb index 47896b4..100f1e0 100644 --- a/test/case_shell.rb +++ b/test/case_shell.rb @@ -1,46 +1,436 @@ -require 'ratch/shell' +testcase Ratch::Shell do -KO.case 'Shell' do + context "location" do + + test "with no path the present working directory is used" do + Ratch::Shell.new.work.assert == Pathname.new(Dir.pwd) + end + + test "a path can be given in parts" do + sample_dir do |dir| + Ratch::Shell.new(dir, 'zoo').work.assert == Pathname.new(dir) + 'zoo' + end + end + + test "a path that is not a directory is refused" do + Ratch::FileNotFound.assert.raised? do + Ratch::Shell.new('not_a_path') + end + end + + test "the process's working directory is left alone" do + sample_dir do |dir| + here = Dir.pwd + shell = Ratch::Shell.new(dir) + shell.touch('new.txt') + shell.cd('zoo') + Dir.pwd.assert == here + shell.pwd.assert == File.join(dir, 'zoo') + end + end + + test "#parent, #home and #root" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir, 'zoo') + shell.parent.assert == Pathname.new(dir) + shell.home.assert == Pathname.new(File.expand_path('~')) + shell.root.assert == Pathname.new('/') + end + end + + test "#path, #file and #dir" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.path('nothing').assert == Pathname.new(dir) + 'nothing' + shell.file('foo.txt').assert == Pathname.new(dir) + 'foo.txt' + shell.dir('zoo').assert == Pathname.new(dir) + 'zoo' + Ratch::FileNotFound.assert.raised?{ shell.file('zoo') } + Ratch::FileNotFound.assert.raised?{ shell.dir('foo.txt') } + end + end + + test "#/ gives a shell at a sub-directory, in the same mode" do + sample_dir do |dir| + zoo = Ratch::Shell.new(dir, :noop=>true) / 'zoo' + zoo.assert.is_a?(Ratch::Shell) + zoo.pwd.assert == File.join(dir, 'zoo') + zoo.assert.noop? + end + end + + test "#cd moves the shell" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.cd('zoo') + shell.glob('*').sort.assert == %w{one.txt two.txt} + shell.cd('..') + shell.pwd.assert == dir + end + end + + test "#cd with a block moves the shell, and the process, for the block only" do + sample_dir do |dir| + here = Dir.pwd + shell = Ratch::Shell.new(dir) + seen = nil + shell.cd('zoo') do + seen = [shell.pwd, Dir.pwd] + end + seen.assert == [File.join(dir, 'zoo')] * 2 + shell.pwd.assert == dir + Dir.pwd.assert == here + end + end + + test "#cd to a missing directory is refused" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + Ratch::FileNotFound.assert.raised?{ shell.cd('nowhere') } + shell.pwd.assert == dir + end + end - test 'with no path given current working directory is used' do - sh = Ratch::Shell.new - sh.work == Pathname.new(Dir.pwd) end - test :quiet? do |options| - o = Hash[*options] - sh = Ratch::Shell.new(o) - sh.quiet? + context "modes" do + + test "the options" do + Ratch::Shell.new(:quiet=>true).assert.quiet? + Ratch::Shell.new(:noop=>true).assert.noop? + Ratch::Shell.new(:nowrite=>true).assert.noop? + Ratch::Shell.new(:trace=>true).assert.trace? + Ratch::Shell.new(:verbose=>true).assert.trace? + Ratch::Shell.new('noop'=>true).assert.noop? + Ratch::Shell.new.refute.noop? + Ratch::Shell.new.refute.trace? + end + + test "dryrun is noop and trace together" do + shell = Ratch::Shell.new(:dryrun=>true) + shell.assert.noop? + shell.assert.trace? + shell.assert.dryrun? + Ratch::Shell.new(:noop=>true, :trace=>true).assert.dryrun? + Ratch::Shell.new(:noop=>true).refute.dryrun? + end + + test "noop changes nothing" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir, :noop=>true) + out = capture_stderr do + shell.rm('foo.txt') + shell.rm_r('zoo') + shell.mkdir('new') + shell.write('bar.txt', 'CHANGED') + shell.append('bar.txt', 'MORE') + shell.mv('bar.txt', 'baz.txt') + shell.sh('touch made-by-sh') + end + out.assert == '' + Dir.children(dir).sort.assert == %w{bar.txt foo.txt zoo} + File.read(File.join(dir, 'bar.txt')).assert == 'SAMPLE BAR.TXT' + end + end + + test "trace reports each step and does it" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir, :trace=>true) + out = capture_stderr do + shell.rm('foo.txt') + shell.sh('true') + end + out.assert.include?('rm ') + out.assert.include?('foo.txt') + out.assert.include?("true\n") + File.refute.exist?(File.join(dir, 'foo.txt')) + end + end + + test "dryrun reports each step and does nothing" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir, :dryrun=>true) + out = capture_stderr{ shell.rm_r('zoo') } + out.assert.include?('rm -r') + File.assert.directory?(File.join(dir, 'zoo')) + end + end + + test "a mode can be given for one command" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.rm('foo.txt', :noop=>true) + File.assert.exist?(File.join(dir, 'foo.txt')) + out = capture_stderr{ shell.rm('foo.txt', :dryrun=>true) } + out.assert.include?('rm ') + File.assert.exist?(File.join(dir, 'foo.txt')) + end + end + end - ok [:quiet, true] + context "equality" do + + test "#== goes by class and working path" do + Ratch::Shell.new('.').assert == Ratch::Shell.new('.') + Ratch::Shell.new('.').refute == Ratch::Shell.new('..') + Ratch::Shell.new('.').refute == '.' + end + + test "#eql? also wants the same noop" do + a = Ratch::Shell.new('.', :noop=>true) + a.assert.eql?(Ratch::Shell.new('.', :noop=>true)) + a.refute.eql?(Ratch::Shell.new('.', :noop=>false)) + ({a => 1}[Ratch::Shell.new('.', :noop=>true)]).assert == 1 + end - test :trace? do |options| - o = Hash[*options] - sh = Ratch::Shell.new(o) - sh.trace? end - ok [:trace, true] + context "listing" do + + test "#entries is Dir.entries as Pathnames" do + sample_dir do |dir| + Ratch::Shell.new(dir).entries.sort.assert == pathnames('.', '..', 'bar.txt', 'foo.txt', 'zoo') + end + end + + test "#file_entries and #directory_entries" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.file_entries.sort.assert == pathnames('bar.txt', 'foo.txt') + shell.directory_entries.sort.assert == pathnames('.', '..', 'zoo') + shell.dir_entries.sort.assert == pathnames('.', '..', 'zoo') + end + end + + test "#pathnames, #files and #directories leave out the dot paths" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.pathnames.sort.assert == pathnames('bar.txt', 'foo.txt', 'zoo') + shell.files.sort.assert == pathnames('bar.txt', 'foo.txt') + shell.directories.assert == pathnames('zoo') + shell.folders.assert == pathnames('zoo') + end + end + + test "listing goes by the shell's directory, not the process's" do + sample_dir do |dir| + (Ratch::Shell.new(dir) / 'zoo').files.sort.assert == pathnames('one.txt', 'two.txt') + end + end + + test "#glob gives paths relative to the shell" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.glob('*').sort.assert == %w{bar.txt foo.txt zoo} + shell.glob('zoo/*', '*.txt').sort.assert == %w{bar.txt foo.txt zoo/one.txt zoo/two.txt} + shell.glob('**/ONE.TXT', File::FNM_CASEFOLD).assert == [] unless File.exist?(File.join(dir, 'FOO.TXT')) + shell.glob(File.join(dir, '*.txt')).sort.assert == [File.join(dir, 'bar.txt'), File.join(dir, 'foo.txt')] + end + end + + test "#glob takes a block" do + sample_dir do |dir| + seen = [] + Ratch::Shell.new(dir).glob('*.txt'){ |f| seen << f } + seen.sort.assert == %w{bar.txt foo.txt} + end + end + + test "#amass includes, excludes and ignores" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.amass(['zoo']).sort.assert == %w{zoo zoo/one.txt zoo/two.txt} + shell.amass(['*.txt', 'zoo'], ['bar.txt'], ['two.*']).sort.assert == %w{foo.txt zoo zoo/one.txt} + end + end + + end + + context "file tests" do + + test "the FileTest methods" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.assert.exist?('foo.txt') + shell.assert.exists?('foo.txt') + shell.refute.exist?('nothing') + shell.assert.file?('foo.txt') + shell.refute.directory?('foo.txt') + shell.assert.directory?('zoo') + shell.assert.dir?('zoo') + shell.assert.readable?('foo.txt') + shell.refute.symlink?('foo.txt') + shell.refute.zero?('foo.txt') + shell.size('foo.txt').assert == 14 + shell.assert.absolute?('/tmp') + shell.assert.relative?('tmp') + end + end + + test "#identical? and #cmp" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.cp('foo.txt', 'copy.txt') + shell.ln('foo.txt', 'link.txt') + shell.assert.identical?('foo.txt', 'link.txt') + shell.refute.identical?('foo.txt', 'copy.txt') + shell.assert.cmp('foo.txt', 'copy.txt') + shell.refute.cmp('foo.txt', 'bar.txt') + end + end + + test "#uptodate? and #outofdate?" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.mtime('foo.txt', Time.now - 100) + shell.assert.outofdate?('foo.txt', 'zoo/*') + shell.refute.outofdate?('bar.txt', 'foo.txt') + shell.assert.outofdate?('nothing', 'foo.txt') + shell.assert.uptodate?('bar.txt', 'foo.txt') + shell.refute.uptodate?('foo.txt', 'bar.txt') + end + end - test :noop? do |options| - o = Hash[*options] - sh = Ratch::Shell.new(o) - sh.noop? end - ok [:noop, true] + context "reading and writing" do + + test "#read, #write and #append" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.read('foo.txt').assert == 'SAMPLE FOO.TXT' + shell.write('baz.txt', 'BAZ TEXT') + shell.read('baz.txt').assert == 'BAZ TEXT' + shell.append('baz.txt', ' 2') + File.read(File.join(dir, 'baz.txt')).assert == 'BAZ TEXT 2' + end + end + + test "#mtime and #atime get and set" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + time = Time.at(1_000_000_000) + shell.mtime('foo.txt', time) + shell.mtime('foo.txt').assert == time + shell.atime('foo.txt', time + 60) + shell.atime('foo.txt').assert == time + 60 + shell.mtime('foo.txt').assert == time + shell.mtime('foo.txt', time + 5, :noop=>true) + shell.mtime('foo.txt').assert == time + end + end - test :dryrun? do |options| - o = Hash[*options] - sh = Ratch::Shell.new(o) - sh.dryrun? end - ok [:noop, true, :trace, true] - ok [:dryrun, true] + context "file operations" do + + test "making and removing" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.mkdir('a') + shell.mkdir_p('b/c/d') + shell.touch('b/c/d/t.txt') + shell.touch(['x.txt', 'y.txt']) + shell.assert.file?('b/c/d/t.txt') + shell.assert.file?('y.txt') + shell.rmdir('a') + shell.rm(['x.txt', 'y.txt']) + shell.rm_f('nothing') + shell.rm_r('b') + shell.rm_rf('zoo') + Dir.children(dir).sort.assert == %w{bar.txt foo.txt} + end + end + + test "copying, moving and linking" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.cp('foo.txt', 'zoo') + shell.cp_r('zoo', 'zoo2') + shell.mv('bar.txt', 'baz.txt') + shell.mv(['foo.txt', 'baz.txt'], 'zoo2') + shell.ln_s('zoo/one.txt', 'one') + shell.ln_sf('zoo/two.txt', 'one') + shell.glob('zoo2/*').sort.assert == %w{zoo2/baz.txt zoo2/foo.txt zoo2/one.txt zoo2/two.txt} + shell.assert.symlink?('one') + shell.read('one').assert == 'TWO' + Dir.children(dir).sort.assert == %w{one zoo zoo2} + end + end - no [:noop, true] - no [:verbose, true] + test "#install and #chmod" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.install('foo.txt', 'zoo/foo', 0755) + (File.stat(File.join(dir, 'zoo/foo')).mode & 0777).assert == 0755 + shell.install('foo.txt', 'zoo/foo2', :mode=>0600) + (File.stat(File.join(dir, 'zoo/foo2')).mode & 0777).assert == 0600 + shell.chmod(0640, 'foo.txt') + (File.stat(File.join(dir, 'foo.txt')).mode & 0777).assert == 0640 + shell.chmod_r(0700, 'zoo') + (File.stat(File.join(dir, 'zoo/one.txt')).mode & 0777).assert == 0700 + end + end + + test "#stage hard links files into a fresh directory" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.mkdir_p('stage/old') + shell.stage('stage', %w{foo.txt zoo/one.txt}) + shell.glob('stage/**/*').sort.assert == %w{stage/foo.txt stage/zoo stage/zoo/one.txt} + shell.assert.identical?('foo.txt', 'stage/foo.txt') + end + end + + end + + context "commands" do + + test "#sh runs from the shell's directory and says whether it worked" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir, 'zoo') + shell.sh('pwd > where.txt').assert == true + shell.read('where.txt').strip.assert == File.join(dir, 'zoo') + shell.sh('false').assert == false + end + end + + test "#sh takes a command in parts" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir) + shell.sh('touch', 'a b.txt').assert == true + shell.assert.file?('a b.txt') + end + end + + test "#sh in quiet mode drops the output" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir, :quiet=>true) + out = IO.popen([RbConfig.ruby, '-Ilib', '-rratch/shell', '-e', + "Ratch::Shell.new(#{dir.inspect}, :quiet=>true).sh('echo LOUD; echo LOUDER >&2')", + :err=>[:child, :out]]){ |io| io.read } + out.assert == '' + shell.assert.quiet? + end + end + + test "#system runs even in noop mode" do + sample_dir do |dir| + shell = Ratch::Shell.new(dir, :noop=>true) + shell.system('touch made.txt').assert == true + shell.assert.file?('made.txt') + end + end + + test "#batch gives a Batch of the shell's files, in its mode" do + sample_dir do |dir| + batch = Ratch::Shell.new(dir, :noop=>true).batch('*.txt') + batch.assert.is_a?(Ratch::Batch) + batch.entries.map(&:to_s).sort.assert == %w{bar.txt foo.txt} + batch.assert.noop? + end + end + + end end diff --git a/test/case_utils.rb b/test/case_utils.rb new file mode 100644 index 0000000..6351fc2 --- /dev/null +++ b/test/case_utils.rb @@ -0,0 +1,173 @@ +testcase "Utilities" do + + class UtilShell < Ratch::Shell + include Ratch::ConfigUtils + include Ratch::ZlibUtils + include Ratch::TarUtils + include Ratch::RDocUtils + include Ratch::EmailUtils + end + + context Ratch::ZlibUtils do + + test "#gzip and #ungzip" do + sample_dir do |dir| + shell = UtilShell.new(dir) + shell.gzip('foo.txt') + shell.assert.file?('foo.txt.gz') + shell.rm('foo.txt') + shell.ungzip('foo.txt.gz') + shell.read('foo.txt').assert == 'SAMPLE FOO.TXT' + end + end + + test "#gzip to a named file, under a directory" do + sample_dir do |dir| + shell = UtilShell.new(dir) + shell.gzip('zoo/one.txt', 'one.gz') + Zlib::GzipReader.open(File.join(dir, 'one.gz')){ |gz| gz.read }.assert == 'ONE' + shell.gzip('zoo/two.txt') + shell.assert.file?('zoo/two.txt.gz') + end + end + + test "noop makes nothing" do + sample_dir do |dir| + UtilShell.new(dir, :noop=>true).gzip('foo.txt') + File.refute.exist?(File.join(dir, 'foo.txt.gz')) + UtilShell.new(dir).gzip('foo.txt', :noop=>true) + File.refute.exist?(File.join(dir, 'foo.txt.gz')) + end + end + + end + + context Ratch::TarUtils do + + test "#tar and #untar" do + sample_dir do |dir| + shell = UtilShell.new(dir) + File.chmod(0755, File.join(dir, 'zoo/one.txt')) + shell.tar('zoo').assert == Pathname.new(dir) + 'zoo.tar' + shell.rm_r('zoo') + shell.untar('zoo.tar').sort.assert == %w{zoo zoo/one.txt zoo/two.txt} + shell.read('zoo/two.txt').assert == 'TWO' + (File.stat(File.join(dir, 'zoo/one.txt')).mode & 0777).assert == 0755 + end + end + + test "the archive is one the tar command reads" do + sample_dir do |dir| + shell = UtilShell.new(dir) + shell.tar_gzip('zoo') + out = IO.popen(['tar', '-tzf', File.join(dir, 'zoo.tar.gz')]){ |io| io.read } + out.split("\n").map{ |l| l.chomp('/') }.sort.assert == %w{zoo zoo/one.txt zoo/two.txt} + end + end + + test "#tar_gzip and #untar_gzip" do + sample_dir do |dir| + shell = UtilShell.new(dir) + shell.tar_gzip('zoo', 'z.tgz') + shell.rm_r('zoo') + shell.untar_gzip('z.tgz') + shell.read('zoo/one.txt').assert == 'ONE' + end + end + + test "an entry that would land outside the directory is refused" do + sample_dir do |dir| + File.open(File.join(dir, 'bad.tar'), 'wb') do |io| + Gem::Package::TarWriter.new(io){ |tar| tar.add_file_simple('../escaped.txt', 0644, 1){ |o| o.write('x') } } + end + ArgumentError.assert.raised?{ UtilShell.new(dir).untar('bad.tar') } + File.refute.exist?(File.join(File.dirname(dir), 'escaped.txt')) + end + end + + test "noop makes nothing" do + sample_dir do |dir| + UtilShell.new(dir, :noop=>true).tar('zoo') + File.refute.exist?(File.join(dir, 'zoo.tar')) + end + end + + end + + context Ratch::ConfigUtils do + + test "#configuration loads a YAML file, with or without its extension" do + sample_dir do |dir| + File.write(File.join(dir, 'settings.yml'), "name: ratch\n") + shell = UtilShell.new(dir) + shell.configuration('settings').assert == {'name'=>'ratch'} + shell.configuration('settings.yml').assert == {'name'=>'ratch'} + end + end + + test "a missing file gives an empty configuration, or an error from the bang method" do + sample_dir do |dir| + shell = UtilShell.new(dir) + shell.configuration('nothing').assert == {} + LoadError.assert.raised?{ shell.configuration!('nothing') } + end + end + + end + + context Ratch::RDocUtils do + + test "#rdoc documents files into a directory" do + sample_dir do |dir| + File.write(File.join(dir, 'thing.rb'), "# A thing.\nclass Thing; end\n") + UtilShell.new(dir).rdoc('thing.rb', :op=>'doc', :title=>'Things') + File.assert.file?(File.join(dir, 'doc/Thing.html')) + File.read(File.join(dir, 'doc/index.html')).assert.include?('Things') + end + end + + end + + context Ratch::EmailUtils do + + test "an Emailer takes its settings from options" do + mail = Ratch::Emailer.new(:server=>'mail.example.com', :from=>'a@example.com', :to=>'b@example.com', + :subject=>'Hi', :message=>'Hello', :secure=>true) + mail.port.assert == 465 + mail.account.assert == 'a@example.com' + mail.login.assert == :plain + mail.domain.assert == 'mail.example.com' + end + + test "a missing field is an error" do + mail = Ratch::Emailer.new(:server=>'mail.example.com', :from=>'a@example.com') + ArgumentError.assert.raised?{ mail.email } + end + + test "a failed delivery returns the error" do + mail = Ratch::Emailer.new(:server=>'127.0.0.1', :port=>9, :from=>'a@example.com', :to=>'b@example.com', + :subject=>'Hi', :message=>'Hello') + mail.email.assert.is_a?(StandardError) + end + + end + + context "core extensions" do + + test "#to_list" do + 'a:b,c'.to_list.assert == %w{a b c} + %w{a b}.to_list.assert == %w{a b} + nil.to_list.assert == [] + end + + test "#to_argv and #to_console" do + args = ['file', {:op=>'my doc', :q=>true, :no=>false, :I=>%w{a b}}] + args.to_argv.assert == ['--op=my doc', '-q', '-Ia', '-Ib', 'file'] + args.size.assert == 2 + Shellwords.split(args.to_console).assert == args.to_argv + ['file', {:quiet=>true}].to_console.assert == '--quiet file' + end + + end + +end diff --git a/test/core_ext/case_pathname.rb b/test/core_ext/case_pathname.rb deleted file mode 100644 index a3b93a9..0000000 --- a/test/core_ext/case_pathname.rb +++ /dev/null @@ -1,361 +0,0 @@ -require 'ratch/core_ext' - -# Test the Pathname extensions. -KO.case 'Pathname' do - - # Test some standard pathname features to ensure nothing is screwed up. - - test :initialize do - p1 = Pathname.new('a') - p2 = Pathname.new(p1) - p1 == p2 && 'a' == p1.to_s - end - - test :== do |obj2| - obj1 = Pathname.new("a") - obj2 = Pathname.new("a") - obj1 == obj2 - end - - test :=== do - obj1 = Pathname.new("a") - obj2 = Pathname.new("a") - obj1 === obj2 - end - - test :eql? do - obj1 = Pathname.new("a") - obj2 = Pathname.new("a") - obj1.eql?(obj2) - end - - - class AnotherStringLike # :nodoc: - def initialize(s) @s = s end - def to_str() @s end - def ==(other) @s == other end - end - - test 'equality' do - obj = Pathname.new("a") - str = "a" - sym = :a - ano = AnotherStringLike.new("a") - return false if obj == str - return false if str == obj - return false if obj == ano - return false if ano == obj - return false if obj == sym - return false if sym == obj - return true - end - - test :hash do - h = {} - h[Pathname.new("a")] = 1 - h[Pathname.new("a")] = 2 - h.size == 1 - end - - test :<=> do |e, s1, s2| - p1 = Pathname.new(s1) - p2 = Pathname.new(s2) - e == (p1 <=> p2) - end - - ok 0, "a", "a" - ok 1, "b", "a" - ok -1, "a", "b" - - ok -1, "a", "a/" - ok -1, "a/", "a/b" - ok -1, "a/b", "a." - ok -1, "a.", "a0" - - test :<=> do - (Pathname.new("a") <=> "a").nil? && - ("a" <=> Pathname.new("a")).nil? - end - - test :root do |a| - Pathname.new(a).root? - end - - ok '/' - ok '//' - ok '///' - - no '' - no 'a' - - test :to_s do |a,b| - a == Pathname.new(b).to_s - end - - ok '/' , '/' - ok 'a/', 'a/' - ok '/a', '/a' - ok '.' , '.' - ok '..', '..' - - test :cleanpath do |a,b| - a == Pathname.new(b).cleanpath(true).to_s - end - - ok '/' , '/' - ok '/' , '//' - ok '/' , '/.' - ok '/' , '/..' - ok '/', '/./..' - ok '/', '/../.' - ok '/', '/./../' - ok '/', '/.././' - - ok '.' , '.' - ok '.' , './' - - ok '..', '..' - ok '..', '../' - ok '..', './..' - ok '..', '../.' - ok '..', './../' - ok '..', '.././' - - ok 'a' , 'a' - ok 'a/' , 'a/' - ok 'a/.' , 'a/.' - ok 'a/.' , 'a/./' - ok 'a/..', 'a/../' - ok 'a/..', 'a/../.' - - ok '/a' , '/a' - ok '/a/.', '/a/.' - - ok 'a/b' , 'a//b' - ok 'a/b/c', 'a/b/c' - ok 'b/c' , './b/c' - ok 'a/c' , 'a/./c' - ok 'a/b/.', 'a/b/.' - - ok '/a', '/../.././../a' - ok 'a/b/../../../../c/../d', 'a/b/../../../../c/../d' - -=begin - def test_cleanpath_no_symlink - assert_equal('/', Pathname.new('/').cleanpath.to_s) - assert_equal('/', Pathname.new('//').cleanpath.to_s) - assert_equal('', Pathname.new('').cleanpath.to_s) - - assert_equal('.', Pathname.new('.').cleanpath.to_s) - assert_equal('..', Pathname.new('..').cleanpath.to_s) - assert_equal('a', Pathname.new('a').cleanpath.to_s) - assert_equal('/', Pathname.new('/.').cleanpath.to_s) - assert_equal('/', Pathname.new('/..').cleanpath.to_s) - assert_equal('/a', Pathname.new('/a').cleanpath.to_s) - assert_equal('.', Pathname.new('./').cleanpath.to_s) - assert_equal('..', Pathname.new('../').cleanpath.to_s) - assert_equal('a', Pathname.new('a/').cleanpath.to_s) - - assert_equal('a/b', Pathname.new('a//b').cleanpath.to_s) - assert_equal('a', Pathname.new('a/.').cleanpath.to_s) - assert_equal('a', Pathname.new('a/./').cleanpath.to_s) - assert_equal('.', Pathname.new('a/../').cleanpath.to_s) - assert_equal('/a', Pathname.new('/a/.').cleanpath.to_s) - assert_equal('..', Pathname.new('./..').cleanpath.to_s) - assert_equal('..', Pathname.new('../.').cleanpath.to_s) - assert_equal('..', Pathname.new('./../').cleanpath.to_s) - assert_equal('..', Pathname.new('.././').cleanpath.to_s) - assert_equal('/', Pathname.new('/./..').cleanpath.to_s) - assert_equal('/', Pathname.new('/../.').cleanpath.to_s) - assert_equal('/', Pathname.new('/./../').cleanpath.to_s) - assert_equal('/', Pathname.new('/.././').cleanpath.to_s) - return false unless obj.equal? obj.taint - assert_equal('a/b/c', Pathname.new('a/b/c').cleanpath.to_s) - assert_equal('b/c', Pathname.new('./b/c').cleanpath.to_s) - assert_equal('a/c', Pathname.new('a/./c').cleanpath.to_s) - assert_equal('a/b', Pathname.new('a/b/.').cleanpath.to_s) - assert_equal('.', Pathname.new('a/../.').cleanpath.to_s) - - assert_equal('/a', Pathname.new('/../.././../a').cleanpath.to_s) - assert_equal('../../d', Pathname.new('a/b/../../../../c/../d').cleanpath.to_s) - end -=end - -=begin - def test_destructive_update - path = Pathname.new("a") - path.to_s.replace "b" - assert_equal(Pathname.new("a"), path) - end -=end - - #def test_null_character - # assert_raise(ArgumentError) { Pathname.new("\0") } - #end - - test :relative_path_from do |result, dest, base| - Pathname.new(result) == Pathname.new(dest).relative_path_from(Pathname.new(base)) - end - - ok "../a", "a", "b" - ok "../a", "a", "b/" - ok "../a", "a/", "b" - ok "../a", "a/", "b/" - ok "../a", "/a", "/b" - ok "../a", "/a", "/b/" - ok "../a", "/a/", "/b" - ok "../a", "/a/", "/b/" - - ok "../b", "a/b", "a/c" - ok "../a", "../a", "../b" - - ok "a", "a", "." - ok "..", ".", "a" - - ok ".", ".", "." - ok ".", "..", ".." - ok "..", "..", "." - - ok "c/d", "/a/b/c/d", "/a/b" - ok "../..", "/a/b", "/a/b/c/d" - ok "../../../../e", "/e", "/a/b/c/d" - ok "../b/c", "a/b/c", "a/d" - - ok "../a", "/../a", "/b" - ok "../../a", "../a", "b" - ok ".", "/a/../../b", "/b" - ok "..", "a/..", "a" - ok ".", "a/../b", "b" - - ok "a", "a", "b/.." - ok "b/c", "b/c", "b/.." - - test :relative_path_from do |dest, base| - ArgumentError.raised? { - Pathname.new(dest).relative_path_from(Pathname.new(base)) - } - end - - ok "/", "." - ok ".", "/" - ok "a", ".." - ok ".", ".." - - test :+ do |a, b, c| - a = Pathname.new(a) - b = Pathname.new(b) - c = Pathname.new(c) - a == b + c - end - - ok 'a/b', 'a', 'b' - ok 'a', 'a', '.' - ok 'b', '.', 'b' - ok '.', '.', '.' - - ok '/', '/', '..' - ok '.', 'a', '..' - ok 'a', 'a/b', '..' - ok '../..', '..', '..' - ok '/c', '/', '../c' - ok 'c', 'a', '../c' - ok 'a/c', 'a/b', '../c' - ok '../../c', '..', '../c' - - # TODO: Is this really what we want? - ok '/b', 'a', '/b' - - test :taint do - obj = Pathname.new("a") - obj.equal? obj.taint - end - - test :untaint do - obj = Pathname.new("a") - obj.equal? obj.untaint - end - - test :tainted? do - return false if Pathname.new("a").tainted? - return false if Pathname.new("a").to_s.tainted? - true - end - - test :tainted? do - Pathname.new("a" ).taint.tainted? && - Pathname.new("a" ).taint.to_s.tainted? && - Pathname.new("a".taint) .tainted? && - Pathname.new("a".taint) .to_s.tainted? && - Pathname.new("a".taint).taint .tainted? && - Pathname.new("a".taint).taint.to_s.tainted? - end - - test :tainted? do - str = "a" - path = Pathname.new(str) - str.taint - return false if path.tainted? - return false if path.to_s.tainted? - return true - end - - test :tainted? do - !Pathname.new("a").taint.untaint .tainted? && - !Pathname.new("a").taint.untaint.to_s.tainted? - end - - test :tainted? do - str = "a".taint - path = Pathname.new(str) - str.untaint - path.tainted? && path.to_s.tainted? - end - - test :freeze do - obj = Pathname.new("a") - obj.equal? obj.freeze - end - - test :freeze do - Pathname.new("a" ).freeze.frozen? && - Pathname.new("a".freeze).freeze.frozen? - end - - test :freeze do - not ( - Pathname.new("a" ) .frozen? && - Pathname.new("a".freeze) .frozen? && - Pathname.new("a" ) .to_s.frozen? && - Pathname.new("a".freeze) .to_s.frozen? && - Pathname.new("a" ).freeze.to_s.frozen? && - Pathname.new("a".freeze).freeze.to_s.frozen? - ) - end - - test :to_s do - str = "a" - obj = Pathname.new(str) - str == obj.to_s && - !str.equal?(obj.to_s) && - !obj.to_s.equal?(obj.to_s) - end - -=begin - test "kernel open" do - count = 0 - stat1 = File.stat(__FILE__) - result = Kernel.open(Pathname.new(__FILE__)) do |f| - stat2 = f.stat - assert_equal(stat1.dev, stat2.dev) - assert_equal(stat1.ino, stat2.ino) - assert_equal(stat1.size, stat2.size) - count += 1 - 2 - end - assert_equal(1, count) - assert_equal(2, result) - end -=end - -end - diff --git a/test/helper.rb b/test/helper.rb index f60ab3f..a8d0182 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -1,4 +1,43 @@ -puts "Ruby v#{RUBY_VERSION}" +require 'assay/ae' +require 'rbconfig' +require 'tmpdir' +require 'fileutils' +require 'stringio' +require 'ratch' -$LOAD_PATH.unshift(File.dirname('__FILE__') + '/../lib') +module Spectrum::World + # Make a sample directory, run the block with its path, and remove it. + # + # foo.txt + # bar.txt + # zoo/ + # zoo/one.txt + # zoo/two.txt + # + def sample_dir + Dir.mktmpdir('ratch') do |dir| + dir = File.realpath(dir) + File.write(File.join(dir, 'foo.txt'), 'SAMPLE FOO.TXT') + File.write(File.join(dir, 'bar.txt'), 'SAMPLE BAR.TXT') + Dir.mkdir(File.join(dir, 'zoo')) + File.write(File.join(dir, 'zoo/one.txt'), 'ONE') + File.write(File.join(dir, 'zoo/two.txt'), 'TWO') + yield dir + end + end + + # What a block writes to standard error. + def capture_stderr + old, $stderr = $stderr, StringIO.new + yield + $stderr.string + ensure + $stderr = old + end + + def pathnames(*names) + names.map{ |n| Pathname.new(n) } + end + +end diff --git a/test/utils/case_cli.rb b/test/utils/case_cli.rb deleted file mode 100644 index ba58388..0000000 --- a/test/utils/case_cli.rb +++ /dev/null @@ -1,6 +0,0 @@ -# TODO - -KO.case "Ratch::CLI" do - -end - diff --git a/test/utils/case_config.rb b/test/utils/case_config.rb deleted file mode 100644 index f6f4d9e..0000000 --- a/test/utils/case_config.rb +++ /dev/null @@ -1,12 +0,0 @@ -# TODO - -KO.case "Ratch::ConfigUtils" do - - #test "#configuration" do - #end - - #test "configuration!" do - #end - -end - diff --git a/test/utils/case_email.rb b/test/utils/case_email.rb deleted file mode 100644 index ab4cc65..0000000 --- a/test/utils/case_email.rb +++ /dev/null @@ -1,10 +0,0 @@ -# TODO - -KO.case "Ratch::EMailUtils" do - - setup do - #p Dir.pwd - end - -end - diff --git a/test/utils/case_ftp.rb b/test/utils/case_ftp.rb deleted file mode 100644 index 64a01f7..0000000 --- a/test/utils/case_ftp.rb +++ /dev/null @@ -1,6 +0,0 @@ -# TODO - -KO.case "Ratch::FTPUtils" do - -end - diff --git a/test/utils/case_pom.rb b/test/utils/case_pom.rb deleted file mode 100644 index 3be6479..0000000 --- a/test/utils/case_pom.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'ratch' - -KO.case "Ratch::POMUtils" do - - def initialize - stage_copy 'fixtures/pom_sample' - - @shell = Ratch::Shell.new - @shell.extend(Ratch::POMUtils) - end - - test :project do - @shell.project.is_a?(::POM::Project) - end - -end - diff --git a/test/utils/case_rdoc.rb b/test/utils/case_rdoc.rb deleted file mode 100644 index e7d482d..0000000 --- a/test/utils/case_rdoc.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'ratch' - -KO.case "Ratch::RDocUtils" do - - def initialize #before :all do - @shell = Ratch::Shell.new - @shell.extend(Ratch::RDocUtils) - end - - setup do - stage_copy 'fixtures/rdoc_sample' - end - - test "#rdoc" do - @shell.rdoc('README.rdoc', 'lib') - File.directory?('doc') && - File.directory?('doc/classes') && - File.directory?('doc/files') && - File.file?('doc/classes/RDocSample.html') - end - -end - diff --git a/test/utils/case_tar.rb b/test/utils/case_tar.rb deleted file mode 100644 index e1cc525..0000000 --- a/test/utils/case_tar.rb +++ /dev/null @@ -1,6 +0,0 @@ -# TODO - -KO.case "Ratch::TarUtils" do - -end - diff --git a/test/utils/case_zlib.rb b/test/utils/case_zlib.rb deleted file mode 100644 index df154c4..0000000 --- a/test/utils/case_zlib.rb +++ /dev/null @@ -1,11 +0,0 @@ -# TODO - -KO.case "Ratch::RDocUtils" do - - test "foo" do |val| - val - end - - ok true -end - diff --git a/test/utils/fixtures/pom_sample/Profile b/test/utils/fixtures/pom_sample/Profile deleted file mode 100644 index 59bd2d1..0000000 --- a/test/utils/fixtures/pom_sample/Profile +++ /dev/null @@ -1,4 +0,0 @@ ---- -name : pom_sample -title : POM Sample -version : 1.0 diff --git a/test/utils/fixtures/rdoc_sample/README.rdoc b/test/utils/fixtures/rdoc_sample/README.rdoc deleted file mode 100644 index 92677c1..0000000 --- a/test/utils/fixtures/rdoc_sample/README.rdoc +++ /dev/null @@ -1,4 +0,0 @@ -= RDOC Sample - -This is a sample RDoc document used to test the RDoc utility. - diff --git a/test/utils/fixtures/rdoc_sample/lib/rdoc_sample/rdoc_sample.rb b/test/utils/fixtures/rdoc_sample/lib/rdoc_sample/rdoc_sample.rb deleted file mode 100644 index 29cb838..0000000 --- a/test/utils/fixtures/rdoc_sample/lib/rdoc_sample/rdoc_sample.rb +++ /dev/null @@ -1,9 +0,0 @@ -# This is dummy module for testing the rdoc utility. -module RDocSample - - # This is a dummy method for testing the rdoc utility. - def self.hello_world - puts "Hello World" - end - -end diff --git a/try/tryme1.ratch b/try/tryme1.ratch index 263b74e..f123065 100755 --- a/try/tryme1.ratch +++ b/try/tryme1.ratch @@ -4,7 +4,6 @@ puts "Hello World" p arguments p quiet? -p debug? define_method :okay do "okay"