Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial commit of scrobbler gem

git-svn-id: http://svn.addictedtonew.com/public/gems/scrobbler@61 fe7eae16-9a24-0410-a59d-9e59979e88be
  • Loading branch information...
commit c13cb006675998dec6b13c90d9a1479b64bb7573 0 parents
jnunemaker authored
Showing with 4,658 additions and 0 deletions.
  1. +1 −0  History.txt
  2. +58 −0 Manifest.txt
  3. +71 −0 README.txt
  4. +89 −0 Rakefile
  5. +18 −0 examples/album.rb
  6. +14 −0 examples/artist.rb
  7. +12 −0 examples/tag.rb
  8. +7 −0 examples/track.rb
  9. +15 −0 examples/user.rb
  10. +13 −0 lib/scrobbler.rb
  11. +143 −0 lib/scrobbler/album.rb
  12. +127 −0 lib/scrobbler/artist.rb
  13. +29 −0 lib/scrobbler/base.rb
  14. +31 −0 lib/scrobbler/chart.rb
  15. +47 −0 lib/scrobbler/rest.rb
  16. +104 −0 lib/scrobbler/tag.rb
  17. +96 −0 lib/scrobbler/track.rb
  18. +192 −0 lib/scrobbler/user.rb
  19. +9 −0 lib/scrobbler/version.rb
  20. +1,585 −0 setup.rb
  21. +70 −0 test/fixtures/xml/album/info.xml
  22. +18 −0 test/fixtures/xml/artist/fans.xml
  23. +39 −0 test/fixtures/xml/artist/similar.xml
  24. +36 −0 test/fixtures/xml/artist/topalbums.xml
  25. +18 −0 test/fixtures/xml/artist/toptags.xml
  26. +27 −0 test/fixtures/xml/artist/toptracks.xml
  27. +39 −0 test/fixtures/xml/tag/topalbums.xml
  28. +39 −0 test/fixtures/xml/tag/topartists.xml
  29. +252 −0 test/fixtures/xml/tag/toptags.xml
  30. +30 −0 test/fixtures/xml/tag/toptracks.xml
  31. +28 −0 test/fixtures/xml/track/fans.xml
  32. +33 −0 test/fixtures/xml/track/toptags.xml
  33. +21 −0 test/fixtures/xml/user/friends.xml
  34. +18 −0 test/fixtures/xml/user/neighbours.xml
  35. +12 −0 test/fixtures/xml/user/profile.xml
  36. +24 −0 test/fixtures/xml/user/recentbannedtracks.xml
  37. +24 −0 test/fixtures/xml/user/recentlovedtracks.xml
  38. +27 −0 test/fixtures/xml/user/recenttracks.xml
  39. +18 −0 test/fixtures/xml/user/systemrecs.xml
  40. +42 −0 test/fixtures/xml/user/topalbums.xml
  41. +30 −0 test/fixtures/xml/user/topartists.xml
  42. +18 −0 test/fixtures/xml/user/toptags.xml
  43. +27 −0 test/fixtures/xml/user/toptracks.xml
  44. +35 −0 test/fixtures/xml/user/weeklyalbumchart.xml
  45. +35 −0 test/fixtures/xml/user/weeklyalbumchart_from_1138536002_to_1139140802.xml
  46. +38 −0 test/fixtures/xml/user/weeklyartistchart.xml
  47. +59 −0 test/fixtures/xml/user/weeklyartistchart_from_1138536002_to_1139140802.xml
  48. +74 −0 test/fixtures/xml/user/weeklychartlist.xml
  49. +35 −0 test/fixtures/xml/user/weeklytrackchart.xml
  50. +35 −0 test/fixtures/xml/user/weeklytrackchart_from_1138536002_to_1139140802.xml
  51. +26 −0 test/mocks/rest.rb
  52. +17 −0 test/test_helper.rb
  53. +86 −0 test/unit/album_test.rb
  54. +82 −0 test/unit/artist_test.rb
  55. +34 −0 test/unit/chart_test.rb
  56. +65 −0 test/unit/tag_test.rb
  57. +42 −0 test/unit/track_test.rb
  58. +291 −0 test/unit/user_test.rb
  59. +47 −0 website/css/common.css
  60. +106 −0 website/index.html
1  History.txt
@@ -0,0 +1 @@
+* v 0.1.0: initial release
58 Manifest.txt
@@ -0,0 +1,58 @@
+History.txt
+Manifest.txt
+README.txt
+Rakefile
+setup.rb
+examples/album.rb
+examples/artist.rb
+examples/tag.rb
+examples/track.rb
+examples/user.rb
+lib/scrobbler.rb
+lib/scrobbler/album.rb
+lib/scrobbler/artist.rb
+lib/scrobbler/base.rb
+lib/scrobbler/chart.rb
+lib/scrobbler/rest.rb
+lib/scrobbler/tag.rb
+lib/scrobbler/track.rb
+lib/scrobbler/user.rb
+lib/scrobbler/version.rb
+test/test_helper.rb
+test/fixtures/xml/album/info.xml
+test/fixtures/xml/artist/fans.xml
+test/fixtures/xml/artist/similar.xml
+test/fixtures/xml/artist/topalbums.xml
+test/fixtures/xml/artist/toptags.xml
+test/fixtures/xml/artist/toptracks.xml
+test/fixtures/xml/tag/topalbums.xml
+test/fixtures/xml/tag/topartists.xml
+test/fixtures/xml/tag/toptags.xml
+test/fixtures/xml/tag/toptracks.xml
+test/fixtures/xml/track/fans.xml
+test/fixtures/xml/track/toptags.xml
+test/fixtures/xml/user/friends.xml
+test/fixtures/xml/user/neighbours.xml
+test/fixtures/xml/user/profile.xml
+test/fixtures/xml/user/recentbannedtracks.xml
+test/fixtures/xml/user/recentlovedtracks.xml
+test/fixtures/xml/user/recenttracks.xml
+test/fixtures/xml/user/systemrecs.xml
+test/fixtures/xml/user/topalbums.xml
+test/fixtures/xml/user/topartists.xml
+test/fixtures/xml/user/toptags.xml
+test/fixtures/xml/user/toptracks.xml
+test/fixtures/xml/user/weeklyalbumchart.xml
+test/fixtures/xml/user/weeklyalbumchart_from_1138536002_to_1139140802.xml
+test/fixtures/xml/user/weeklyartistchart.xml
+test/fixtures/xml/user/weeklyartistchart_from_1138536002_to_1139140802.xml
+test/fixtures/xml/user/weeklychartlist.xml
+test/fixtures/xml/user/weeklytrackchart.xml
+test/fixtures/xml/user/weeklytrackchart_from_1138536002_to_1139140802.xml
+test/mocks/rest.rb
+test/unit/album_test.rb
+test/unit/artist_test.rb
+test/unit/chart_test.rb
+test/unit/tag_test.rb
+test/unit/track_test.rb
+test/unit/user_test.rb
71 README.txt
@@ -0,0 +1,71 @@
+=Scrobbler
+
+Scrobbler is a wrapper for the audioscrobbler web services (http://www.audioscrobbler.net/data/webservices/).
+
+Below is just a sampling of how easy this lib is to use.
+
+== Users
+
+ user = Scrobbler::User.new('jnunemaker')
+
+ puts "#{user.username}'s Recent Tracks"
+ puts "=" * (user.username.length + 16)
+ user.recent_tracks.each { |t| puts t.name }
+
+ puts
+ puts
+
+ puts "#{user.username}'s Top Tracks"
+ puts "=" * (user.username.length + 13)
+ user.top_tracks.each { |t| puts "(#{t.playcount}) #{t.name}" }
+
+== Albums
+
+ album = Scrobbler::Album.new('Carrie Underwood', 'Some Hearts', :include_info => true)
+
+ puts "Album: #{album.name}"
+ puts "Artist: #{album.artist}"
+ puts "Reach: #{album.reach}"
+ puts "URL: #{album.url}"
+ puts "Release Date: #{album.release_date.strftime('%m/%d/%Y')}"
+
+ puts
+ puts
+
+ puts "Tracks"
+ longest_track_name = album.tracks.collect(&:name).sort { |x, y| y.length <=> x.length }.first.length
+ puts "=" * longest_track_name
+ album.tracks.each { |t| puts t.name }
+
+==Artists
+
+ artist = Scrobbler::Artist.new('Carrie Underwood')
+
+ puts 'Top Tracks'
+ puts "=" * 10
+ artist.top_tracks.each { |t| puts "(#{t.reach}) #{t.name}" }
+
+ puts
+
+ puts 'Similar Artists'
+ puts "=" * 15
+ artist.similar.each { |a| puts "(#{a.match}%) #{a.name}" }
+
+==Tags
+
+ tag = Scrobbler::Tag.new('country')
+
+ puts 'Top Albums'
+ tag.top_albums.each { |a| puts "(#{a.count}) #{a.name} by #{a.artist}" }
+
+ puts
+
+ puts 'Top Tracks'
+ tag.top_tracks.each { |t| puts "(#{t.count}) #{t.name} by #{t.artist}" }
+
+==Tracks
+
+ track = Scrobbler::Track.new('Carrie Underwood', 'Before He Cheats')
+ puts 'Fans'
+ puts "=" * 4
+ track.fans.each { |u| puts "(#{u.weight}) #{u.username}" }
89 Rakefile
@@ -0,0 +1,89 @@
+require 'rubygems'
+require 'rake'
+require 'rake/clean'
+require 'rake/testtask'
+require 'rake/packagetask'
+require 'rake/gempackagetask'
+require 'rake/rdoctask'
+require 'rake/contrib/rubyforgepublisher'
+require 'fileutils'
+require 'hoe'
+include FileUtils
+require File.join(File.dirname(__FILE__), 'lib', 'scrobbler', 'version')
+
+AUTHOR = 'nunemaker' # can also be an array of Authors
+EMAIL = "nunemaker@gmail.com"
+DESCRIPTION = "wrapper for audioscrobbler (last.fm) web services"
+GEM_NAME = 'scrobbler' # what ppl will type to install your gem
+RUBYFORGE_PROJECT = 'scrobbler' # The unix name for your project
+HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
+DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
+
+NAME = "scrobbler"
+REV = nil # UNCOMMENT IF REQUIRED: File.read(".svn/entries")[/committed-rev="(d+)"/, 1] rescue nil
+VERS = Scrobbler::VERSION::STRING + (REV ? ".#{REV}" : "")
+CLEAN.include ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store']
+RDOC_OPTS = ['--quiet', '--title', 'scrobbler documentation',
+ "--opname", "index.html",
+ "--line-numbers",
+ "--main", "README",
+ "--inline-source"]
+
+class Hoe
+ def extra_deps
+ @extra_deps.reject { |x| Array(x).first == 'hoe' }
+ end
+end
+
+# Generate all the Rake tasks
+# Run 'rake -T' to see list of generated tasks (from gem root directory)
+hoe = Hoe.new(GEM_NAME, VERS) do |p|
+ p.author = AUTHOR
+ p.description = DESCRIPTION
+ p.email = EMAIL
+ p.summary = DESCRIPTION
+ p.url = HOMEPATH
+ p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
+ p.test_globs = ["test/**/test_*.rb"]
+ p.clean_globs = CLEAN #An array of file patterns to delete on clean.
+
+ # == Optional
+ p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
+ p.extra_deps = [['hpricot', '>=0.4.86'], ['activesupport', '>=1.4.2']] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ]
+ #p.spec_extras = {} # A hash of extra values to set in the gemspec.
+end
+
+
+desc 'Generate website files'
+task :website_generate do
+ Dir['website/**/*.txt'].each do |txt|
+ sh %{ ruby scripts/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} }
+ end
+end
+
+desc 'Upload website files to rubyforge'
+task :website_upload do
+ config = YAML.load(File.read(File.expand_path("~/.rubyforge/user-config.yml")))
+ host = "#{config["username"]}@rubyforge.org"
+ remote_dir = "/var/www/gforge-projects/#{RUBYFORGE_PROJECT}/"
+ # remote_dir = "/var/www/gforge-projects/#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
+ local_dir = 'website'
+ sh %{rsync -av #{local_dir}/ #{host}:#{remote_dir}}
+end
+
+desc 'Generate and upload website files'
+task :website => [:website_generate, :website_upload]
+
+desc 'Release the website and new gem version'
+task :deploy => [:check_version, :website, :release]
+
+task :check_version do
+ unless ENV['VERSION']
+ puts 'Must pass a VERSION=x.y.z release version'
+ exit
+ end
+ unless ENV['VERSION'] == VERS
+ puts "Please update your version.rb to match the release version, currently #{VERS}"
+ exit
+ end
+end
18 examples/album.rb
@@ -0,0 +1,18 @@
+require 'rubygems'
+require 'scrobbler'
+
+album = Scrobbler::Album.new('Carrie Underwood', 'Some Hearts', :include_info => true)
+
+puts "Album: #{album.name}"
+puts "Artist: #{album.artist}"
+puts "Reach: #{album.reach}"
+puts "URL: #{album.url}"
+puts "Release Date: #{album.release_date.strftime('%m/%d/%Y')}"
+
+puts
+puts
+
+puts "Tracks"
+longest_track_name = album.tracks.collect(&:name).sort { |x, y| y.length <=> x.length }.first.length
+puts "=" * longest_track_name
+album.tracks.each { |t| puts t.name }
14 examples/artist.rb
@@ -0,0 +1,14 @@
+require 'rubygems'
+require 'scrobbler'
+
+artist = Scrobbler::Artist.new('Carrie Underwood')
+
+puts 'Top Tracks'
+puts "=" * 10
+artist.top_tracks.each { |t| puts "(#{t.reach}) #{t.name}" }
+
+puts
+
+puts 'Similar Artists'
+puts "=" * 15
+artist.similar.each { |a| puts "(#{a.match}%) #{a.name}" }
12 examples/tag.rb
@@ -0,0 +1,12 @@
+require 'rubygems'
+require 'scrobbler'
+
+tag = Scrobbler::Tag.new('country')
+
+puts 'Top Albums'
+tag.top_albums.each { |a| puts "(#{a.count}) #{a.name} by #{a.artist}" }
+
+puts
+
+puts 'Top Tracks'
+tag.top_tracks.each { |t| puts "(#{t.count}) #{t.name} by #{t.artist}" }
7 examples/track.rb
@@ -0,0 +1,7 @@
+require 'rubygems'
+require 'scrobbler'
+
+track = Scrobbler::Track.new('Carrie Underwood', 'Before He Cheats')
+puts 'Fans'
+puts "=" * 4
+track.fans.each { |u| puts "(#{u.weight}) #{u.username}" }
15 examples/user.rb
@@ -0,0 +1,15 @@
+require 'rubygems'
+require 'scrobbler'
+
+user = Scrobbler::User.new('jnunemaker')
+
+puts "#{user.username}'s Recent Tracks"
+puts "=" * (user.username.length + 16)
+user.recent_tracks.each { |t| puts t.name }
+
+puts
+puts
+
+puts "#{user.username}'s Top Tracks"
+puts "=" * (user.username.length + 13)
+user.top_tracks.each { |t| puts "(#{t.playcount}) #{t.name}" }
13 lib/scrobbler.rb
@@ -0,0 +1,13 @@
+%w{cgi rubygems hpricot active_support}.each { |x| require x }
+
+require 'scrobbler/base'
+
+require 'scrobbler/album'
+require 'scrobbler/artist'
+require 'scrobbler/chart'
+require 'scrobbler/user'
+require 'scrobbler/tag'
+require 'scrobbler/track'
+
+require 'scrobbler/rest'
+require 'scrobbler/version'
143 lib/scrobbler/album.rb
@@ -0,0 +1,143 @@
+# Getting information about an album such as release date and the tracks on it is very easy.
+#
+# album = Scrobbler::Album.new('Carrie Underwood', 'Some Hearts', :include_info => true)
+#
+# puts "Album: #{album.name}"
+# puts "Artist: #{album.artist}"
+# puts "Reach: #{album.reach}"
+# puts "URL: #{album.url}"
+# puts "Release Date: #{album.release_date.strftime('%m/%d/%Y')}"
+#
+# puts
+# puts
+#
+# puts "Tracks"
+# longest_track_name = album.tracks.collect(&:name).sort { |x, y| y.length <=> x.length }.first.length
+# puts "=" * longest_track_name
+# album.tracks.each { |t| puts t.name }
+#
+# Would output:
+#
+# Album: Some Hearts
+# Artist: Carrie Underwood
+# Reach: 18729
+# URL: http://www.last.fm/music/Carrie+Underwood/Some+Hearts
+# Release Date: 11/15/2005
+#
+#
+# Tracks
+# ===============================
+# Wasted
+# Don't Forget to Remember Me
+# Some Hearts
+# Jesus, Take the Wheel
+# The Night Before (Life Goes On)
+# Lessons Learned
+# Before He Cheats
+# Starts With Goodbye
+# I Just Can't Live a Lie
+# We're Young and Beautiful
+# That's Where It Is
+# Whenever You Remember
+# I Ain't in Checotah Anymore
+# Inside Your Heaven
+module Scrobbler
+ class Album < Base
+ attr_accessor :artist, :artist_mbid, :name, :mbid, :playcount, :rank, :url, :reach, :release_date
+ attr_accessor :image_large, :image_medium, :image_small
+ attr_writer :tracks
+
+ # needed on top albums for tag
+ attr_accessor :count, :streamable
+
+ # needed for weekly album charts
+ attr_accessor :chartposition
+
+ class << self
+ def find(artist, name, o={})
+ new(artist, name, o)
+ end
+
+ def new_from_xml(xml, doc=nil)
+ name = (xml).at(:name).inner_html if (xml).at(:name)
+ name = xml['name'] if name.nil? && xml['name']
+ artist = (xml).at(:artist)['name'] if (xml).at(:artist) && (xml).at(:artist)['name']
+ artist = (xml).at(:artist).inner_html if artist.nil? && (xml).at(:artist)
+ artist = doc.root['artist'] if artist.nil? && doc.root['artist']
+ a = Album.new(artist, name)
+ a.artist_mbid = (xml).at(:artist)['mbid'] if (xml).at(:artist) && (xml).at(:artist)['mbid']
+ a.artist_mbid = (xml).at(:artist).at(:mbid).inner_html if a.artist_mbid.nil? && (xml).at(:artist) && (xml).at(:artist).at(:mbid)
+ a.mbid = (xml).at(:mbid).inner_html if (xml).at(:mbid)
+ a.playcount = (xml).at(:playcount).inner_html if (xml).at(:playcount)
+ a.chartposition = (xml).at(:chartposition).inner_html if (xml).at(:chartposition)
+ a.rank = (xml).at(:rank).inner_html if (xml).at(:rank)
+ a.url = (xml/:url).last.inner_html if (xml/:url).size > 1
+ a.url = (xml).at(:url).inner_html if a.url.nil? && (xml).at(:url)
+ a.reach = (xml).at(:reach).inner_html if (xml).at(:reach)
+ a.image_large = (xml).at(:image).at(:large).inner_html if (xml).at(:image) && (xml).at(:image).at(:large)
+ a.image_medium = (xml).at(:image).at(:medium).inner_html if (xml).at(:image) && (xml).at(:image).at(:medium)
+ a.image_small = (xml).at(:image).at(:small).inner_html if (xml).at(:image) && (xml).at(:image).at(:small)
+
+ # coverart element used on top albums for tag
+ a.image_large = (xml).at(:coverart).at(:large).inner_html if a.image_large.nil? && (xml).at(:coverart) && (xml).at(:coverart).at(:large)
+ a.image_medium = (xml).at(:coverart).at(:medium).inner_html if a.image_medium.nil? && (xml).at(:coverart) && (xml).at(:coverart).at(:medium)
+ a.image_small = (xml).at(:coverart).at(:small).inner_html if a.image_small.nil? && (xml).at(:coverart) && (xml).at(:coverart).at(:small)
+
+ # needed on top albums for tag
+ a.count = xml['count'] if xml['count']
+ a.streamable = xml['streamable'] if xml['streamable']
+ a
+ end
+ end
+
+ def initialize(artist, name, o={})
+ raise ArgumentError, "Artist is required" if artist.blank?
+ raise ArgumentError, "Name is required" if name.blank?
+ @artist = artist
+ @name = name
+ options = {:include_info => false}.merge(o)
+ load_info() if options[:include_info]
+ end
+
+ def api_path
+ "/#{API_VERSION}/album/#{CGI::escape(artist)}/#{CGI::escape(name)}"
+ end
+
+ def load_info
+ doc = self.class.fetch_and_parse("#{api_path}/info.xml")
+ @reach = (doc).at(:reach).inner_html
+ @url = (doc).at(:url).inner_html
+ @release_date = Time.parse((doc).at(:releasedate).inner_html.strip)
+ @image_large = (doc).at(:coverart).at(:large).inner_html
+ @image_medium = (doc).at(:coverart).at(:medium).inner_html
+ @image_small = (doc).at(:coverart).at(:small).inner_html
+ @mbid = (doc).at(:mbid).inner_html
+ @tracks = (doc/:track).inject([]) do |tracks, track|
+ t = Track.new(artist, track['title'])
+ t.artist_mbid = artist_mbid
+ t.album = name
+ t.album_mbid = mbid
+ t.url = (track).at(:url).inner_html
+ t.reach = (track).at(:reach).inner_html
+ tracks << t
+ tracks
+ end
+ end
+
+ def tracks
+ load_info if @tracks.nil?
+ @tracks
+ end
+
+ def image(which=:small)
+ which = which.to_s
+ raise ArgumentError unless ['small', 'medium', 'large'].include?(which)
+ img_url = instance_variable_get("@image_#{which}")
+ if img_url.nil?
+ load_info
+ img_url = instance_variable_get("@image_#{which}")
+ end
+ img_url
+ end
+ end
+end
127 lib/scrobbler/artist.rb
@@ -0,0 +1,127 @@
+# Below are examples of how to find an artists top tracks and similar artists.
+#
+# artist = Scrobbler::Artist.new('Carrie Underwood')
+#
+# puts 'Top Tracks'
+# puts "=" * 10
+# artist.top_tracks.each { |t| puts "(#{t.reach}) #{t.name}" }
+#
+# puts
+#
+# puts 'Similar Artists'
+# puts "=" * 15
+# artist.similar.each { |a| puts "(#{a.match}%) #{a.name}" }
+#
+# Would output something similar to:
+#
+# Top Tracks
+# ==========
+# (8797) Before He Cheats
+# (3574) Don't Forget to Remember Me
+# (3569) Wasted
+# (3246) Some Hearts
+# (3142) Jesus, Take the Wheel
+# (2600) Starts With Goodbye
+# (2511) Jesus Take The Wheel
+# (2423) Inside Your Heaven
+# (2328) Lessons Learned
+# (2040) I Just Can't Live a Lie
+# (1899) Whenever You Remember
+# (1882) We're Young and Beautiful
+# (1854) That's Where It Is
+# (1786) I Ain't in Checotah Anymore
+# (1596) The Night Before (Life Goes On)
+#
+# Similar Artists
+# ===============
+# (100%) Rascal Flatts
+# (84.985%) Keith Urban
+# (84.007%) Kellie Pickler
+# (82.694%) Katharine McPhee
+# (81.213%) Martina McBride
+# (79.397%) Faith Hill
+# (77.121%) Tim McGraw
+# (75.191%) Jessica Simpson
+# (75.182%) Sara Evans
+# (75.144%) The Wreckers
+# (73.034%) Kenny Chesney
+# (71.765%) Dixie Chicks
+# (71.084%) Kelly Clarkson
+# (69.535%) Miranda Lambert
+# (66.952%) LeAnn Rimes
+# (66.398%) Mandy Moore
+# (65.817%) Bo Bice
+# (65.279%) Diana DeGarmo
+# (65.115%) Gretchen Wilson
+# (62.982%) Clay Aiken
+# (62.436%) Ashlee Simpson
+# (62.160%) Christina Aguilera
+module Scrobbler
+ class Artist < Base
+ attr_accessor :name, :mbid, :playcount, :rank, :url, :thumbnail, :image, :reach, :count, :streamable
+ attr_accessor :chartposition
+
+ # used for similar artists
+ attr_accessor :match
+
+ class << self
+ def new_from_xml(xml, doc=nil)
+ name = (xml).at(:name).inner_html if (xml).at(:name)
+ # occasionally name can be found in root of artist element (<artist name="">) rather than as an element (<name>)
+ name = xml['name'] if name.nil? && xml['name']
+ a = Artist.new(name)
+ a.mbid = (xml).at(:mbid).inner_html if (xml).at(:mbid)
+ a.playcount = (xml).at(:playcount).inner_html if (xml).at(:playcount)
+ a.rank = (xml).at(:rank).inner_html if (xml).at(:rank)
+ a.url = (xml).at(:url).inner_html if (xml).at(:url)
+ a.thumbnail = (xml).at(:thumbnail).inner_html if (xml).at(:thumbnail)
+ a.thumbnail = (xml).at(:image_small).inner_html if a.thumbnail.nil? && (xml).at(:image_small)
+ a.image = (xml).at(:image).inner_html if (xml).at(:image)
+ a.reach = (xml).at(:reach).inner_html if (xml).at(:reach)
+ a.match = (xml).at(:match).inner_html if (xml).at(:match)
+ a.chartposition = (xml).at(:chartposition).inner_html if (xml).at(:chartposition)
+
+ # in top artists for tag
+ a.count = xml['count'] if xml['count']
+ a.streamable = xml['streamable'] if xml['streamable']
+ a.streamable = (xml).at(:streamable).inner_html == '1' ? 'yes' : 'no' if a.streamable.nil? && (xml).at(:streamable)
+ a
+ end
+ end
+
+ def initialize(name)
+ raise ArgumentError, "Name is required" if name.blank?
+ @name = name
+ end
+
+ def api_path
+ "/#{API_VERSION}/artist/#{CGI::escape(name)}"
+ end
+
+ def current_events(format=:ics)
+ format = :ics if format.to_s == 'ical'
+ raise ArgumentError unless ['ics', 'rss'].include?(format.to_s)
+ "#{API_URL.chop}#{api_path}/events.#{format}"
+ end
+
+ def similar(force=false)
+ get_instance(:similar, :similar, :artist, force)
+ end
+
+ def top_fans(force=false)
+ get_instance(:fans, :top_fans, :user, force)
+ end
+
+ def top_tracks(force=false)
+ get_instance(:toptracks, :top_tracks, :track, force)
+ end
+
+ def top_albums(force=false)
+ get_instance(:topalbums, :top_albums, :album, force)
+ end
+
+ def top_tags(force=false)
+ get_instance(:toptags, :top_tags, :tag, force)
+ end
+ end
+end
29 lib/scrobbler/base.rb
@@ -0,0 +1,29 @@
+module Scrobbler
+
+ API_URL = 'http://ws.audioscrobbler.com/'
+ API_VERSION = '1.0'
+
+ class Base
+ class << self
+ def connection
+ @connection ||= REST::Connection.new(API_URL)
+ end
+
+ def fetch_and_parse(resource)
+ Hpricot::XML(connection.get(resource))
+ end
+ end
+
+ private
+ # in order for subclass to use, it must have api_path method
+ def get_instance(api_method, instance_name, element, force=false)
+ scrobbler_class = "scrobbler/#{element.to_s}".camelize.constantize
+ if instance_variable_get("@#{instance_name}").nil? || force
+ doc = self.class.fetch_and_parse("#{api_path}/#{api_method}.xml")
+ elements = (doc/element).inject([]) { |elements, el| elements << scrobbler_class.new_from_xml(el, doc); elements }
+ instance_variable_set("@#{instance_name}", elements)
+ end
+ instance_variable_get("@#{instance_name}")
+ end
+ end
+end
31 lib/scrobbler/chart.rb
@@ -0,0 +1,31 @@
+module Scrobbler
+ class Chart < Base
+ class << self
+ def new_from_xml(xml, doc)
+ Chart.new(xml['from'], xml['to'])
+ end
+ end
+ def initialize(from, to)
+ raise ArgumentError, "From is required" if from.blank?
+ raise ArgumentError, "To is required" if to.blank?
+ @from = from
+ @to = to
+ end
+
+ def from=(value)
+ @from = value.to_i
+ end
+
+ def to=(value)
+ @to = value.to_i
+ end
+
+ def from
+ @from.to_i
+ end
+
+ def to
+ @to.to_i
+ end
+ end
+end
47 lib/scrobbler/rest.rb
@@ -0,0 +1,47 @@
+require 'net/https'
+
+module Scrobbler
+ module REST
+ class Connection
+ def initialize(base_url, args = {})
+ @base_url = base_url
+ @username = args[:username]
+ @password = args[:password]
+ end
+
+ def get(resource, args = nil)
+ request(resource, "get", args)
+ end
+
+ def post(resource, args = nil)
+ request(resource, "post", args)
+ end
+
+ def request(resource, method = "get", args = nil)
+ url = URI.join(@base_url, resource)
+
+ if args
+ # TODO: What about keys without value?
+ url.query = args.map { |k,v| "%s=%s" % [URI.encode(k), URI.encode(v)] }.join("&")
+ end
+
+ case method
+ when "get"
+ req = Net::HTTP::Get.new(url.request_uri)
+ when "post"
+ req = Net::HTTP::Post.new(url.request_uri)
+ end
+
+ if @username and @password
+ req.basic_auth(@username, @password)
+ end
+
+ http = Net::HTTP.new(url.host, url.port)
+ http.use_ssl = (url.port == 443)
+
+ res = http.start() { |conn| conn.request(req) }
+ res.body
+ end
+ end
+ end
+end
104 lib/scrobbler/tag.rb
@@ -0,0 +1,104 @@
+# Below is code samples for how to find the top albums and tracks for a tag.
+#
+# tag = Scrobbler::Tag.new('country')
+#
+# puts 'Top Albums'
+# tag.top_albums.each { |a| puts "(#{a.count}) #{a.name} by #{a.artist}" }
+#
+# puts
+#
+# puts 'Top Tracks'
+# tag.top_tracks.each { |t| puts "(#{t.count}) #{t.name} by #{t.artist}" }
+#
+# Which would output something similar to:
+#
+# Top Albums
+# (29) American IV: The Man Comes Around by Johnny Cash
+# (14) Folks Pop In at the Waterhouse by Various Artists
+# (13) Hapless by Flowers From The Man Who Shot Your Cousin
+# (9) Taking The Long Way by Dixie Chicks
+# (8) Unchained by Johnny Cash
+# (8) American III: Solitary Man by Johnny Cash
+# (8) Wide Open Spaces by Dixie Chicks
+# (7) It's Now or Later by Tangled Star
+# (7) Greatest Hits by Hank Williams
+# (7) American Recordings by Johnny Cash
+# (6) Forgotten Landscape by theNoLifeKing
+# (6) At Folsom Prison by Johnny Cash
+# (6) Fox Confessor Brings the Flood by Neko Case
+# (6) Murder by Johnny Cash
+# (5) Gloom by theNoLifeKing
+# (5) Set This Circus Down by Tim McGraw
+# (5) Blacklisted by Neko Case
+# (5) Breathe by Faith Hill
+# (5) Unearthed (disc 4: My Mother's Hymn Book) by Johnny Cash
+# (4) Home by Dixie Chicks
+#
+# Top Tracks
+# (221) Hurt by Johnny Cash
+# (152) I Walk the Line by Johnny Cash
+# (147) Ring of Fire by Johnny Cash
+# (125) Folsom Prison Blues by Johnny Cash
+# (77) The Man Comes Around by Johnny Cash
+# (67) Personal Jesus by Johnny Cash
+# (65) Not Ready To Make Nice by Dixie Chicks
+# (63) Before He Cheats by Carrie Underwood
+# (62) Give My Love to Rose by Johnny Cash
+# (49) Jackson by Johnny Cash
+# (49) What Hurts The Most by Rascal Flatts
+# (48) Big River by Johnny Cash
+# (46) Man in Black by Johnny Cash
+# (46) Jolene by Dolly Parton
+# (46) Friends in Low Places by Garth Brooks
+# (46) One by Johnny Cash
+# (44) Cocaine Blues by Johnny Cash
+# (41) Get Rhythm by Johnny Cash
+# (41) I Still Miss Someone by Johnny Cash
+# (40) The Devil Went Down to Georgia by Charlie Daniels Band
+module Scrobbler
+ class Tag < Base
+ attr_accessor :name, :count, :url
+
+ class << self
+ def new_from_xml(xml, doc=nil)
+ name = (xml).at(:name).inner_html
+ t = Tag.new(name)
+ t.count = (xml).at(:count).inner_html
+ t.url = (xml).at(:url).inner_html
+ t
+ end
+
+ def top_tags
+ doc = fetch_and_parse("/#{API_VERSION}/tag/toptags.xml")
+ @top_tags = (doc/:tag).inject([]) do |tags, tag|
+ t = Tag.new(tag['name'])
+ t.count = tag['count']
+ t.url = tag['url']
+ tags << t
+ tags
+ end
+ end
+ end
+
+ def initialize(name)
+ raise ArgumentError, "Name is required" if name.blank?
+ @name = name
+ end
+
+ def api_path
+ "/#{API_VERSION}/tag/#{CGI::escape(name)}"
+ end
+
+ def top_artists(force=false)
+ get_instance(:topartists, :top_artists, :artist, force)
+ end
+
+ def top_albums(force=false)
+ get_instance(:topalbums, :top_albums, :album, force)
+ end
+
+ def top_tracks(force=false)
+ get_instance(:toptracks, :top_tracks, :track, force)
+ end
+ end
+end
96 lib/scrobbler/track.rb
@@ -0,0 +1,96 @@
+# Below is an example of how to get the top fans for a track.
+#
+# track = Scrobbler::Track.new('Carrie Underwood', 'Before He Cheats')
+# puts 'Fans'
+# puts "=" * 4
+# track.fans.each { |u| puts u.username }
+#
+# Which would output something like:
+#
+# track = Scrobbler::Track.new('Carrie Underwood', 'Before He Cheats')
+# puts 'Fans'
+# puts "=" * 4
+# track.fans.each { |u| puts "(#{u.weight}) #{u.username}" }
+#
+# Fans
+# ====
+# (69163) PimpinRose
+# (7225) selene204
+# (7000) CelestiaLegends
+# (6817) muehllr
+# (5387) Mudley
+# (5368) ilovejohnny1984
+# (5232) MeganIAD
+# (5132) Veric
+# (5097) aeVnar
+# (3390) kristaaan
+# (3239) kelseaowns
+# (2780) syndication
+# (2735) mkumm
+# (2706) Kimmybeebee
+# (2648) skorpcroze
+# (2549) mistergreg
+# (2449) mlmjcace
+# (2302) tiNEey
+# (2169) ajsbabiegirl
+module Scrobbler
+ class Track < Base
+ attr_accessor :artist, :artist_mbid, :name, :mbid, :playcount, :rank, :url, :reach
+ attr_accessor :streamable, :album, :album_mbid, :date, :date_uts
+
+ # only seems to be used on top tracks for tag
+ attr_accessor :count, :thumbnail, :image
+
+ # for weekly top tracks
+ attr_accessor :chartposition
+
+ class << self
+ def new_from_xml(xml, doc=nil)
+ artist = (xml).at(:artist)['name'] if (xml).at(:artist) && (xml).at(:artist)['name']
+ artist = (xml).at(:artist).inner_html if artist.nil? && (xml).at(:artist)
+ artist = doc.root['artist'] if artist.nil? && doc.root['artist']
+ name = (xml).at(:name).inner_html if (xml).at(:name)
+ name = xml['name'] if name.nil? && xml['name']
+ t = Track.new(artist, name)
+ t.artist_mbid = (xml).at(:artist)['mbid'] if (xml).at(:artist) && (xml).at(:artist)['mbid']
+ t.artist_mbid = (xml).at(:artist).at(:mbid).inner_html if t.artist_mbid.nil? && (xml).at(:artist) && (xml).at(:artist).at(:mbid)
+ t.mbid = (xml).at(:mbid).inner_html if (xml).at(:mbid)
+ t.playcount = (xml).at(:playcount).inner_html if (xml).at(:playcount)
+ t.chartposition = (xml).at(:chartposition).inner_html if (xml).at(:chartposition)
+ t.rank = (xml).at(:rank).inner_html if (xml).at(:rank)
+ t.url = (xml/:url).last.inner_html if (xml/:url).size > 1
+ t.url = (xml).at(:url).inner_html if t.url.nil? && (xml).at(:url)
+ t.streamable = (xml).at(:track)['streamable'] if (xml).at(:track) && (xml).at(:track)['streamable']
+ t.streamable = xml['streamable'] if t.streamable.nil? && xml['streamable']
+ t.count = xml['count'] if xml['count']
+ t.album = (xml).at(:album).inner_html if (xml).at(:album)
+ t.album_mbid = (xml).at(:album)['mbid'] if (xml).at(:album) && (xml).at(:album)['mbid']
+ t.date = Time.parse((xml).at(:date).inner_html) if (xml).at(:date)
+ t.date_uts = (xml).at(:date)['uts'] if (xml).at(:date) && (xml).at(:date)['uts']
+ t.thumbnail = (xml).at(:thumbnail).inner_html if (xml).at(:thumbnail)
+ t.image = (xml).at(:image).inner_html if (xml).at(:image)
+ t.reach = (xml).at(:reach).inner_html if (xml).at(:reach)
+ t
+ end
+ end
+
+ def initialize(artist, name)
+ raise ArgumentError, "Artist is required" if artist.blank?
+ raise ArgumentError, "Name is required" if name.blank?
+ @artist = artist
+ @name = name
+ end
+
+ def api_path
+ "/#{API_VERSION}/track/#{CGI::escape(artist)}/#{CGI::escape(name)}"
+ end
+
+ def fans(force=false)
+ get_instance(:fans, :fans, :user, force)
+ end
+
+ def tags(force=false)
+ get_instance(:toptags, :tags, :tag, force)
+ end
+ end
+end
192 lib/scrobbler/user.rb
@@ -0,0 +1,192 @@
+# Probably the most common use of this lib would be to get your most recent tracks or your top tracks. Below are some code samples.
+# user = Scrobbler::User.new('jnunemaker')
+#
+# puts "#{user.username}'s Recent Tracks"
+# puts "=" * (user.username.length + 16)
+# user.recent_tracks.each { |t| puts t.name }
+#
+# puts
+# puts
+#
+# puts "#{user.username}'s Top Tracks"
+# puts "=" * (user.username.length + 13)
+# user.top_tracks.each { |t| puts "(#{t.playcount}) #{t.name}" }
+#
+# Which would output something like:
+#
+# jnunemaker's Recent Tracks
+# ==========================
+# Everything You Want
+# You're a God
+# Bitter Sweet Symphony [Original Version]
+# Lord I Guess I'll Never Know
+# Country Song
+# Bitter Sweet Symphony (Radio Edit)
+#
+#
+# jnunemaker's Top Tracks
+# =======================
+# (62) Probably Wouldn't Be This Way
+# (55) Not Ready To Make Nice
+# (45) Easy Silence
+# (43) Song 2
+# (40) Everybody Knows
+# (39) Before He Cheats
+# (39) Something's Gotta Give
+# (38) Hips Don't Lie (featuring Wyclef Jean)
+# (37) Unwritten
+# (37) Move Along
+# (37) Dance, Dance
+# (36) We Belong Together
+# (36) Jesus, Take the Wheel
+# (36) Black Horse and the Cherry Tree (radio version)
+# (35) Photograph
+# (35) You're Beautiful
+# (35) Walk Away
+# (34) Stickwitu
+module Scrobbler
+ class User < Base
+ # attributes needed to initialize
+ attr_reader :username
+
+ # profile attributes
+ attr_accessor :id, :cluster, :url, :realname, :mbox_sha1sum, :registered
+ attr_accessor :registered_unixtime, :age, :gender, :country, :playcount, :avatar
+
+ # neighbor attributes
+ attr_accessor :match
+
+ # track fans attributes
+ attr_accessor :weight
+
+ class << self
+ def new_from_xml(xml, doc=nil)
+ u = User.new((xml)['username'])
+ u.url = (xml).at(:url).inner_html if (xml).at(:url)
+ u.avatar = (xml).at(:image).inner_html if (xml).at(:image)
+ u.weight = (xml).at(:weight).inner_html if (xml).at(:weight)
+ u.match = (xml).at(:match).inner_html if (xml).at(:match)
+ u
+ end
+
+ def find(*args)
+ options = {:include_profile => false}
+ options.merge!(args.pop) if args.last.is_a?(Hash)
+ users = args.flatten.inject([]) { |users, u| users << User.new(u, options); users }
+ users.length == 1 ? users.pop : users
+ end
+ end
+
+ def initialize(username, o={})
+ options = {:include_profile => false}.merge(o)
+ raise ArgumentError if username.blank?
+ @username = username
+ load_profile() if options[:include_profile]
+ end
+
+ def api_path
+ "/#{API_VERSION}/user/#{CGI::escape(username)}"
+ end
+
+ def current_events(format=:ics)
+ format = :ics if format.to_s == 'ical'
+ raise ArgumentError unless ['ics', 'rss'].include?(format.to_s)
+ "#{API_URL.chop}#{api_path}/events.#{format}"
+ end
+
+ def friends_events(format=:ics)
+ format = :ics if format.to_s == 'ical'
+ raise ArgumentError unless ['ics', 'rss'].include?(format.to_s)
+ "#{API_URL.chop}#{api_path}/friendevents.#{format}"
+ end
+
+ def recommended_events(format=:ics)
+ format = :ics if format.to_s == 'ical'
+ raise ArgumentError unless ['ics', 'rss'].include?(format.to_s)
+ "#{API_URL.chop}#{api_path}/eventsysrecs.#{format}"
+ end
+
+ def load_profile
+ doc = self.class.fetch_and_parse("#{api_path}/profile.xml")
+ @id = (doc).at(:profile)['id']
+ @cluster = (doc).at(:profile)['cluster']
+ @url = (doc).at(:url).inner_html
+ @realname = (doc).at(:realname).inner_html
+ @mbox_sha1sum = (doc).at(:mbox_sha1sum).inner_html
+ @registered = (doc).at(:registered).inner_html
+ @registered_unixtime = (doc).at(:registered)['unixtime']
+ @age = (doc).at(:age).inner_html
+ @gender = (doc).at(:gender).inner_html
+ @country = (doc).at(:country).inner_html
+ @playcount = (doc).at(:playcount).inner_html
+ @avatar = (doc).at(:avatar).inner_html
+ end
+
+ def top_artists(force=false)
+ get_instance(:topartists, :top_artists, :artist, force)
+ end
+
+ def top_albums(force=false)
+ get_instance(:topalbums, :top_albums, :album, force)
+ end
+
+ def top_tracks(force=false)
+ get_instance(:toptracks, :top_tracks, :track, force)
+ end
+
+ def top_tags(force=false)
+ get_instance(:toptags, :top_tags, :tag, force)
+ end
+
+ def friends(force=false)
+ get_instance(:friends, :friends, :user, force)
+ end
+
+ def neighbours(force=false)
+ get_instance(:neighbours, :neighbours, :user, force)
+ end
+
+ def recent_tracks(force=false)
+ get_instance(:recenttracks, :recent_tracks, :track, force)
+ end
+
+ def recent_banned_tracks(force=false)
+ get_instance(:recentbannedtracks, :recent_banned_tracks, :track, force)
+ end
+
+ def recent_loved_tracks(force=false)
+ get_instance(:recentlovedtracks, :recent_loved_tracks, :track, force)
+ end
+
+ def recommendations(force=false)
+ get_instance(:systemrecs, :recommendations, :artist, force)
+ end
+
+ def charts(force=false)
+ get_instance(:weeklychartlist, :charts, :chart, force)
+ end
+
+ def weekly_artist_chart(from=nil, to=nil)
+ qs = create_query_string_from_timestamps(from, to)
+ doc = self.class.fetch_and_parse("#{api_path}/weeklyartistchart.xml#{qs}")
+ (doc/:artist).inject([]) { |elements, el| elements << Artist.new_from_xml(el); elements }
+ end
+
+ def weekly_album_chart(from=nil, to=nil)
+ qs = create_query_string_from_timestamps(from, to)
+ doc = self.class.fetch_and_parse("#{api_path}/weeklyalbumchart.xml#{qs}")
+ (doc/:album).inject([]) { |elements, el| elements << Album.new_from_xml(el); elements }
+ end
+
+ def weekly_track_chart(from=nil, to=nil)
+ qs = create_query_string_from_timestamps(from, to)
+ doc = self.class.fetch_and_parse("#{api_path}/weeklytrackchart.xml#{qs}")
+ (doc/:track).inject([]) { |elements, el| elements << Track.new_from_xml(el); elements }
+ end
+
+ private
+ def create_query_string_from_timestamps(from, to)
+ (from && to) ? "?from=#{from.to_i}&to=#{to.to_i}" : ''
+ end
+ end
+end
9 lib/scrobbler/version.rb
@@ -0,0 +1,9 @@
+module Scrobbler #:nodoc:
+ module VERSION #:nodoc:
+ MAJOR = 0
+ MINOR = 1
+ TINY = 0
+
+ STRING = [MAJOR, MINOR, TINY].join('.')
+ end
+end
1,585 setup.rb
@@ -0,0 +1,1585 @@
+#
+# setup.rb
+#
+# Copyright (c) 2000-2005 Minero Aoki
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU LGPL, Lesser General Public License version 2.1.
+#
+
+unless Enumerable.method_defined?(:map) # Ruby 1.4.6
+ module Enumerable
+ alias map collect
+ end
+end
+
+unless File.respond_to?(:read) # Ruby 1.6
+ def File.read(fname)
+ open(fname) {|f|
+ return f.read
+ }
+ end
+end
+
+unless Errno.const_defined?(:ENOTEMPTY) # Windows?
+ module Errno
+ class ENOTEMPTY
+ # We do not raise this exception, implementation is not needed.
+ end
+ end
+end
+
+def File.binread(fname)
+ open(fname, 'rb') {|f|
+ return f.read
+ }
+end
+
+# for corrupted Windows' stat(2)
+def File.dir?(path)
+ File.directory?((path[-1,1] == '/') ? path : path + '/')
+end
+
+
+class ConfigTable
+
+ include Enumerable
+
+ def initialize(rbconfig)
+ @rbconfig = rbconfig
+ @items = []
+ @table = {}
+ # options
+ @install_prefix = nil
+ @config_opt = nil
+ @verbose = true
+ @no_harm = false
+ end
+
+ attr_accessor :install_prefix
+ attr_accessor :config_opt
+
+ attr_writer :verbose
+
+ def verbose?
+ @verbose
+ end
+
+ attr_writer :no_harm
+
+ def no_harm?
+ @no_harm
+ end
+
+ def [](key)
+ lookup(key).resolve(self)
+ end
+
+ def []=(key, val)
+ lookup(key).set val
+ end
+
+ def names
+ @items.map {|i| i.name }
+ end
+
+ def each(&block)
+ @items.each(&block)
+ end
+
+ def key?(name)
+ @table.key?(name)
+ end
+
+ def lookup(name)
+ @table[name] or setup_rb_error "no such config item: #{name}"
+ end
+
+ def add(item)
+ @items.push item
+ @table[item.name] = item
+ end
+
+ def remove(name)
+ item = lookup(name)
+ @items.delete_if {|i| i.name == name }
+ @table.delete_if {|name, i| i.name == name }
+ item
+ end
+
+ def load_script(path, inst = nil)
+ if File.file?(path)
+ MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path
+ end
+ end
+
+ def savefile
+ '.config'
+ end
+
+ def load_savefile
+ begin
+ File.foreach(savefile()) do |line|
+ k, v = *line.split(/=/, 2)
+ self[k] = v.strip
+ end
+ rescue Errno::ENOENT
+ setup_rb_error $!.message + "\n#{File.basename($0)} config first"
+ end
+ end
+
+ def save
+ @items.each {|i| i.value }
+ File.open(savefile(), 'w') {|f|
+ @items.each do |i|
+ f.printf "%s=%s\n", i.name, i.value if i.value? and i.value
+ end
+ }
+ end
+
+ def load_standard_entries
+ standard_entries(@rbconfig).each do |ent|
+ add ent
+ end
+ end
+
+ def standard_entries(rbconfig)
+ c = rbconfig
+
+ rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT'])
+
+ major = c['MAJOR'].to_i
+ minor = c['MINOR'].to_i
+ teeny = c['TEENY'].to_i
+ version = "#{major}.#{minor}"
+
+ # ruby ver. >= 1.4.4?
+ newpath_p = ((major >= 2) or
+ ((major == 1) and
+ ((minor >= 5) or
+ ((minor == 4) and (teeny >= 4)))))
+
+ if c['rubylibdir']
+ # V > 1.6.3
+ libruby = "#{c['prefix']}/lib/ruby"
+ librubyver = c['rubylibdir']
+ librubyverarch = c['archdir']
+ siteruby = c['sitedir']
+ siterubyver = c['sitelibdir']
+ siterubyverarch = c['sitearchdir']
+ elsif newpath_p
+ # 1.4.4 <= V <= 1.6.3
+ libruby = "#{c['prefix']}/lib/ruby"
+ librubyver = "#{c['prefix']}/lib/ruby/#{version}"
+ librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
+ siteruby = c['sitedir']
+ siterubyver = "$siteruby/#{version}"
+ siterubyverarch = "$siterubyver/#{c['arch']}"
+ else
+ # V < 1.4.4
+ libruby = "#{c['prefix']}/lib/ruby"
+ librubyver = "#{c['prefix']}/lib/ruby/#{version}"
+ librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
+ siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby"
+ siterubyver = siteruby
+ siterubyverarch = "$siterubyver/#{c['arch']}"
+ end
+ parameterize = lambda {|path|
+ path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix')
+ }
+
+ if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg }
+ makeprog = arg.sub(/'/, '').split(/=/, 2)[1]
+ else
+ makeprog = 'make'
+ end
+
+ [
+ ExecItem.new('installdirs', 'std/site/home',
+ 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\
+ {|val, table|
+ case val
+ when 'std'
+ table['rbdir'] = '$librubyver'
+ table['sodir'] = '$librubyverarch'
+ when 'site'
+ table['rbdir'] = '$siterubyver'
+ table['sodir'] = '$siterubyverarch'
+ when 'home'
+ setup_rb_error '$HOME was not set' unless ENV['HOME']
+ table['prefix'] = ENV['HOME']
+ table['rbdir'] = '$libdir/ruby'
+ table['sodir'] = '$libdir/ruby'
+ end
+ },
+ PathItem.new('prefix', 'path', c['prefix'],
+ 'path prefix of target environment'),
+ PathItem.new('bindir', 'path', parameterize.call(c['bindir']),
+ 'the directory for commands'),
+ PathItem.new('libdir', 'path', parameterize.call(c['libdir']),
+ 'the directory for libraries'),
+ PathItem.new('datadir', 'path', parameterize.call(c['datadir']),
+ 'the directory for shared data'),
+ PathItem.new('mandir', 'path', parameterize.call(c['mandir']),
+ 'the directory for man pages'),
+ PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']),
+ 'the directory for system configuration files'),
+ PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']),
+ 'the directory for local state data'),
+ PathItem.new('libruby', 'path', libruby,
+ 'the directory for ruby libraries'),
+ PathItem.new('librubyver', 'path', librubyver,
+ 'the directory for standard ruby libraries'),
+ PathItem.new('librubyverarch', 'path', librubyverarch,
+ 'the directory for standard ruby extensions'),
+ PathItem.new('siteruby', 'path', siteruby,
+ 'the directory for version-independent aux ruby libraries'),
+ PathItem.new('siterubyver', 'path', siterubyver,
+ 'the directory for aux ruby libraries'),
+ PathItem.new('siterubyverarch', 'path', siterubyverarch,
+ 'the directory for aux ruby binaries'),
+ PathItem.new('rbdir', 'path', '$siterubyver',
+ 'the directory for ruby scripts'),
+ PathItem.new('sodir', 'path', '$siterubyverarch',
+ 'the directory for ruby extentions'),
+ PathItem.new('rubypath', 'path', rubypath,
+ 'the path to set to #! line'),
+ ProgramItem.new('rubyprog', 'name', rubypath,
+ 'the ruby program using for installation'),
+ ProgramItem.new('makeprog', 'name', makeprog,
+ 'the make program to compile ruby extentions'),
+ SelectItem.new('shebang', 'all/ruby/never', 'ruby',
+ 'shebang line (#!) editing mode'),
+ BoolItem.new('without-ext', 'yes/no', 'no',
+ 'does not compile/install ruby extentions')
+ ]
+ end
+ private :standard_entries
+
+ def load_multipackage_entries
+ multipackage_entries().each do |ent|
+ add ent
+ end
+ end
+
+ def multipackage_entries
+ [
+ PackageSelectionItem.new('with', 'name,name...', '', 'ALL',
+ 'package names that you want to install'),
+ PackageSelectionItem.new('without', 'name,name...', '', 'NONE',
+ 'package names that you do not want to install')
+ ]
+ end
+ private :multipackage_entries
+
+ ALIASES = {
+ 'std-ruby' => 'librubyver',
+ 'stdruby' => 'librubyver',
+ 'rubylibdir' => 'librubyver',
+ 'archdir' => 'librubyverarch',
+ 'site-ruby-common' => 'siteruby', # For backward compatibility
+ 'site-ruby' => 'siterubyver', # For backward compatibility
+ 'bin-dir' => 'bindir',
+ 'bin-dir' => 'bindir',
+ 'rb-dir' => 'rbdir',
+ 'so-dir' => 'sodir',
+ 'data-dir' => 'datadir',
+ 'ruby-path' => 'rubypath',
+ 'ruby-prog' => 'rubyprog',
+ 'ruby' => 'rubyprog',
+ 'make-prog' => 'makeprog',
+ 'make' => 'makeprog'
+ }
+
+ def fixup
+ ALIASES.each do |ali, name|
+ @table[ali] = @table[name]
+ end
+ @items.freeze
+ @table.freeze
+ @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/
+ end
+
+ def parse_opt(opt)
+ m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}"
+ m.to_a[1,2]
+ end
+
+ def dllext
+ @rbconfig['DLEXT']
+ end
+
+ def value_config?(name)
+ lookup(name).value?
+ end
+
+ class Item
+ def initialize(name, template, default, desc)
+ @name = name.freeze
+ @template = template
+ @value = default
+ @default = default
+ @description = desc
+ end
+
+ attr_reader :name
+ attr_reader :description
+
+ attr_accessor :default
+ alias help_default default
+
+ def help_opt
+ "--#{@name}=#{@template}"
+ end
+
+ def value?
+ true
+ end
+
+ def value
+ @value
+ end
+
+ def resolve(table)
+ @value.gsub(%r<\$([^/]+)>) { table[$1] }
+ end
+
+ def set(val)
+ @value = check(val)
+ end
+
+ private
+
+ def check(val)
+ setup_rb_error "config: --#{name} requires argument" unless val
+ val
+ end
+ end
+
+ class BoolItem < Item
+ def config_type
+ 'bool'
+ end
+
+ def help_opt
+ "--#{@name}"
+ end
+
+ private
+
+ def check(val)
+ return 'yes' unless val
+ case val
+ when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes'
+ when /\An(o)?\z/i, /\Af(alse)\z/i then 'no'
+ else
+ setup_rb_error "config: --#{@name} accepts only yes/no for argument"
+ end
+ end
+ end
+
+ class PathItem < Item
+ def config_type
+ 'path'
+ end
+
+ private
+
+ def check(path)
+ setup_rb_error "config: --#{@name} requires argument" unless path
+ path[0,1] == '$' ? path : File.expand_path(path)
+ end
+ end
+
+ class ProgramItem < Item
+ def config_type
+ 'program'
+ end
+ end
+
+ class SelectItem < Item
+ def initialize(name, selection, default, desc)
+ super
+ @ok = selection.split('/')
+ end
+
+ def config_type
+ 'select'
+ end
+
+ private
+
+ def check(val)
+ unless @ok.include?(val.strip)
+ setup_rb_error "config: use --#{@name}=#{@template} (#{val})"
+ end
+ val.strip
+ end
+ end
+
+ class ExecItem < Item
+ def initialize(name, selection, desc, &block)
+ super name, selection, nil, desc
+ @ok = selection.split('/')
+ @action = block
+ end
+
+ def config_type
+ 'exec'
+ end
+
+ def value?
+ false
+ end
+
+ def resolve(table)
+ setup_rb_error "$#{name()} wrongly used as option value"
+ end
+
+ undef set
+
+ def evaluate(val, table)
+ v = val.strip.downcase
+ unless @ok.include?(v)
+ setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})"
+ end
+ @action.call v, table
+ end
+ end
+
+ class PackageSelectionItem < Item
+ def initialize(name, template, default, help_default, desc)
+ super name, template, default, desc
+ @help_default = help_default
+ end
+
+ attr_reader :help_default
+
+ def config_type
+ 'package'
+ end
+
+ private
+
+ def check(val)
+ unless File.dir?("packages/#{val}")
+ setup_rb_error "config: no such package: #{val}"
+ end
+ val
+ end
+ end
+
+ class MetaConfigEnvironment
+ def initialize(config, installer)
+ @config = config
+ @installer = installer
+ end
+
+ def config_names
+ @config.names
+ end
+
+ def config?(name)
+ @config.key?(name)
+ end
+
+ def bool_config?(name)
+ @config.lookup(name).config_type == 'bool'
+ end
+
+ def path_config?(name)
+ @config.lookup(name).config_type == 'path'
+ end
+
+ def value_config?(name)
+ @config.lookup(name).config_type != 'exec'
+ end
+
+ def add_config(item)
+ @config.add item
+ end
+
+ def add_bool_config(name, default, desc)
+ @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc)
+ end
+
+ def add_path_config(name, default, desc)
+ @config.add PathItem.new(name, 'path', default, desc)
+ end
+
+ def set_config_default(name, default)
+ @config.lookup(name).default = default
+ end
+
+ def remove_config(name)
+ @config.remove(name)
+ end
+
+ # For only multipackage
+ def packages
+ raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer
+ @installer.packages
+ end
+
+ # For only multipackage
+ def declare_packages(list)
+ raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer
+ @installer.packages = list
+ end
+ end
+
+end # class ConfigTable
+
+
+# This module requires: #verbose?, #no_harm?
+module FileOperations
+
+ def mkdir_p(dirname, prefix = nil)
+ dirname = prefix + File.expand_path(dirname) if prefix
+ $stderr.puts "mkdir -p #{dirname}" if verbose?
+ return if no_harm?
+
+ # Does not check '/', it's too abnormal.
+ dirs = File.expand_path(dirname).split(%r<(?=/)>)
+ if /\A[a-z]:\z/i =~ dirs[0]
+ disk = dirs.shift
+ dirs[0] = disk + dirs[0]
+ end
+ dirs.each_index do |idx|
+ path = dirs[0..idx].join('')
+ Dir.mkdir path unless File.dir?(path)
+ end
+ end
+
+ def rm_f(path)
+ $stderr.puts "rm -f #{path}" if verbose?
+ return if no_harm?
+ force_remove_file path
+ end
+
+ def rm_rf(path)
+ $stderr.puts "rm -rf #{path}" if verbose?
+ return if no_harm?
+ remove_tree path
+ end
+
+ def remove_tree(path)
+ if File.symlink?(path)
+ remove_file path
+ elsif File.dir?(path)
+ remove_tree0 path
+ else
+ force_remove_file path
+ end
+ end
+
+ def remove_tree0(path)
+ Dir.foreach(path) do |ent|
+ next if ent == '.'
+ next if ent == '..'
+ entpath = "#{path}/#{ent}"
+ if File.symlink?(entpath)
+ remove_file entpath
+ elsif File.dir?(entpath)
+ remove_tree0 entpath
+ else
+ force_remove_file entpath
+ end
+ end
+ begin
+ Dir.rmdir path
+ rescue Errno::ENOTEMPTY
+ # directory may not be empty
+ end
+ end
+
+ def move_file(src, dest)
+ force_remove_file dest
+ begin
+ File.rename src, dest
+ rescue
+ File.open(dest, 'wb') {|f|
+ f.write File.binread(src)
+ }
+ File.chmod File.stat(src).mode, dest
+ File.unlink src
+ end
+ end
+
+ def force_remove_file(path)
+ begin
+ remove_file path
+ rescue
+ end
+ end
+
+ def remove_file(path)
+ File.chmod 0777, path
+ File.unlink path
+ end
+
+ def install(from, dest, mode, prefix = nil)
+ $stderr.puts "install #{from} #{dest}" if verbose?
+ return if no_harm?
+
+ realdest = prefix ? prefix + File.expand_path(dest) : dest
+ realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest)
+ str = File.binread(from)
+ if diff?(str, realdest)
+ verbose_off {
+ rm_f realdest if File.exist?(realdest)
+ }
+ File.open(realdest, 'wb') {|f|
+ f.write str
+ }
+ File.chmod mode, realdest
+
+ File.open("#{objdir_root()}/InstalledFiles", 'a') {|f|
+ if prefix
+ f.puts realdest.sub(prefix, '')
+ else
+ f.puts realdest
+ end
+ }
+ end
+ end
+
+ def diff?(new_content, path)
+ return true unless File.exist?(path)
+ new_content != File.binread(path)
+ end
+
+ def command(*args)
+ $stderr.puts args.join(' ') if verbose?
+ system(*args) or raise RuntimeError,
+ "system(#{args.map{|a| a.inspect }.join(' ')}) failed"
+ end
+
+ def ruby(*args)
+ command config('rubyprog'), *args
+ end
+
+ def make(task = nil)
+ command(*[config('makeprog'), task].compact)
+ end
+
+ def extdir?(dir)
+ File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb")
+ end
+
+ def files_of(dir)
+ Dir.open(dir) {|d|
+ return d.select {|ent| File.file?("#{dir}/#{ent}") }
+ }
+ end
+
+ DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn )
+
+ def directories_of(dir)
+ Dir.open(dir) {|d|
+ return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT
+ }
+ end
+
+end
+
+
+# This module requires: #srcdir_root, #objdir_root, #relpath
+module HookScriptAPI
+
+ def get_config(key)
+ @config[key]
+ end
+
+ alias config get_config
+
+ # obsolete: use metaconfig to change configuration
+ def set_config(key, val)
+ @config[key] = val
+ end
+
+ #
+ # srcdir/objdir (works only in the package directory)
+ #
+
+ def curr_srcdir
+ "#{srcdir_root()}/#{relpath()}"
+ end
+
+ def curr_objdir
+ "#{objdir_root()}/#{relpath()}"
+ end
+
+ def srcfile(path)
+ "#{curr_srcdir()}/#{path}"
+ end
+
+ def srcexist?(path)
+ File.exist?(srcfile(path))
+ end
+
+ def srcdirectory?(path)
+ File.dir?(srcfile(path))
+ end
+
+ def srcfile?(path)
+ File.file?(srcfile(path))
+ end
+
+ def srcentries(path = '.')
+ Dir.open("#{curr_srcdir()}/#{path}") {|d|
+ return d.to_a - %w(. ..)
+ }
+ end
+
+ def srcfiles(path = '.')
+ srcentries(path).select {|fname|
+ File.file?(File.join(curr_srcdir(), path, fname))
+ }
+ end
+
+ def srcdirectories(path = '.')
+ srcentries(path).select {|fname|
+ File.dir?(File.join(curr_srcdir(), path, fname))
+ }
+ end
+
+end
+
+
+class ToplevelInstaller
+
+ Version = '3.4.1'
+ Copyright = 'Copyright (c) 2000-2005 Minero Aoki'
+
+ TASKS = [
+ [ 'all', 'do config, setup, then install' ],
+ [ 'config', 'saves your configurations' ],
+ [ 'show', 'shows current configuration' ],
+ [ 'setup', 'compiles ruby extentions and others' ],
+ [ 'install', 'installs files' ],
+ [ 'test', 'run all tests in test/' ],
+ [ 'clean', "does `make clean' for each extention" ],
+ [ 'distclean',"does `make distclean' for each extention" ]
+ ]
+
+ def ToplevelInstaller.invoke
+ config = ConfigTable.new(load_rbconfig())
+ config.load_standard_entries
+ config.load_multipackage_entries if multipackage?
+ config.fixup
+ klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller)
+ klass.new(File.dirname($0), config).invoke
+ end
+
+ def ToplevelInstaller.multipackage?
+ File.dir?(File.dirname($0) + '/packages')
+ end
+
+ def ToplevelInstaller.load_rbconfig
+ if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg }
+ ARGV.delete(arg)
+ load File.expand_path(arg.split(/=/, 2)[1])
+ $".push 'rbconfig.rb'
+ else
+ require 'rbconfig'
+ end
+ ::Config::CONFIG
+ end
+
+ def initialize(ardir_root, config)
+ @ardir = File.expand_path(ardir_root)
+ @config = config
+ # cache
+ @valid_task_re = nil
+ end
+
+ def config(key)
+ @config[key]
+ end
+
+ def inspect
+ "#<#{self.class} #{__id__()}>"
+ end
+
+ def invoke
+ run_metaconfigs
+ case task = parsearg_global()
+ when nil, 'all'
+ parsearg_config
+ init_installers
+ exec_config
+ exec_setup
+ exec_install
+ else
+ case task
+ when 'config', 'test'
+ ;
+ when 'clean', 'distclean'
+ @config.load_savefile if File.exist?(@config.savefile)
+ else
+ @config.load_savefile
+ end
+ __send__ "parsearg_#{task}"
+ init_installers
+ __send__ "exec_#{task}"
+ end
+ end
+
+ def run_metaconfigs
+ @config.load_script "#{@ardir}/metaconfig"
+ end
+
+ def init_installers
+ @installer = Installer.new(@config, @ardir, File.expand_path('.'))
+ end
+
+ #
+ # Hook Script API bases
+ #
+
+ def srcdir_root
+ @ardir
+ end
+
+ def objdir_root
+ '.'
+ end
+
+ def relpath
+ '.'
+ end
+
+ #
+ # Option Parsing
+ #
+
+ def parsearg_global
+ while arg = ARGV.shift
+ case arg
+ when /\A\w+\z/
+ setup_rb_error "invalid task: #{arg}" unless valid_task?(arg)
+ return arg
+ when '-q', '--quiet'
+ @config.verbose = false
+ when '--verbose'
+ @config.verbose = true
+ when '--help'
+ print_usage $stdout
+ exit 0
+ when '--version'
+ puts "#{File.basename($0)} version #{Version}"
+ exit 0
+ when '--copyright'
+ puts Copyright
+ exit 0
+ else
+ setup_rb_error "unknown global option '#{arg}'"
+ end
+ end
+ nil
+ end
+
+ def valid_task?(t)
+ valid_task_re() =~ t
+ end
+
+ def valid_task_re
+ @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/
+ end
+
+ def parsearg_no_options
+ unless ARGV.empty?
+ task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1)
+ setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}"
+ end
+ end
+
+ alias parsearg_show parsearg_no_options
+ alias parsearg_setup parsearg_no_options
+ alias parsearg_test parsearg_no_options
+ alias parsearg_clean parsearg_no_options
+ alias parsearg_distclean parsearg_no_options
+
+ def parsearg_config
+ evalopt = []
+ set = []
+ @config.config_opt = []
+ while i = ARGV.shift
+ if /\A--?\z/ =~ i
+ @config.config_opt = ARGV.dup
+ break
+ end
+ name, value = *@config.parse_opt(i)
+ if @config.value_config?(name)
+ @config[name] = value
+ else
+ evalopt.push [name, value]
+ end
+ set.push name
+ end
+ evalopt.each do |name, value|
+ @config.lookup(name).evaluate value, @config
+ end
+ # Check if configuration is valid
+ set.each do |n|
+ @config[n] if @config.value_config?(n)
+ end
+ end
+
+ def parsearg_install
+ @config.no_harm = false
+ @config.install_prefix = ''
+ while a = ARGV.shift
+ case a
+ when '--no-harm'
+ @config.no_harm = true
+ when /\A--prefix=/
+ path = a.split(/=/, 2)[1]
+ path = File.expand_path(path) unless path[0,1] == '/'
+ @config.install_prefix = path
+ else
+ setup_rb_error "install: unknown option #{a}"
+ end
+ end
+ end
+
+ def print_usage(out)
+ out.puts 'Typical Installation Procedure:'
+ out.puts " $ ruby #{File.basename $0} config"
+ out.puts " $ ruby #{File.basename $0} setup"
+ out.puts " # ruby #{File.basename $0} install (may require root privilege)"
+ out.puts
+ out.puts 'Detailed Usage:'
+ out.puts " ruby #{File.basename $0} <global option>"
+ out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]"
+
+ fmt = " %-24s %s\n"
+ out.puts
+ out.puts 'Global options:'
+ out.printf fmt, '-q,--quiet', 'suppress message outputs'
+ out.printf fmt, ' --verbose', 'output messages verbosely'
+ out.printf fmt, ' --help', 'print this message'
+ out.printf fmt, ' --version', 'print version and quit'
+ out.printf fmt, ' --copyright', 'print copyright and quit'
+ out.puts
+ out.puts 'Tasks:'
+ TASKS.each do |name, desc|
+ out.printf fmt, name, desc
+ end
+
+ fmt = " %-24s %s [%s]\n"
+ out.puts
+ out.puts 'Options for CONFIG or ALL:'
+ @config.each do |item|
+ out.printf fmt, item.help_opt, item.description, item.help_default
+ end
+ out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's"
+ out.puts
+ out.puts 'Options for INSTALL:'
+ out.printf fmt, '--no-harm', 'only display what to do if given', 'off'
+ out.printf fmt, '--prefix=path', 'install path prefix', ''
+ out.puts
+ end
+
+ #
+ # Task Handlers
+ #
+
+ def exec_config
+ @installer.exec_config
+ @config.save # must be final
+ end
+
+ def exec_setup
+ @installer.exec_setup
+ end
+
+ def exec_install
+ @installer.exec_install
+ end
+
+ def exec_test
+ @installer.exec_test
+ end
+
+ def exec_show
+ @config.each do |i|
+ printf "%-20s %s\n", i.name, i.value if i.value?
+ end
+ end
+
+ def exec_clean
+ @installer.exec_clean
+ end
+
+ def exec_distclean
+ @installer.exec_distclean
+ end
+
+end # class ToplevelInstaller
+
+
+class ToplevelInstallerMulti < ToplevelInstaller
+
+ include FileOperations
+
+ def initialize(ardir_root, config)
+ super
+ @packages = directories_of("#{@ardir}/packages")
+ raise 'no package exists' if @packages.empty?
+ @root_installer = Installer.new(@config, @ardir, File.expand_path('.'))
+ end
+
+ def run_metaconfigs
+ @config.load_script "#{@ardir}/metaconfig", self
+ @packages.each do |name|
+ @config.load_script "#{@ardir}/packages/#{name}/metaconfig"
+ end
+ end
+
+ attr_reader :packages
+
+ def packages=(list)
+ raise 'package list is empty' if list.empty?
+ list.each do |name|
+ raise "directory packages/#{name} does not exist"\
+ unless File.dir?("#{@ardir}/packages/#{name}")
+ end
+ @packages = list
+ end
+
+ def init_installers
+ @installers = {}
+ @packages.each do |pack|
+ @installers[pack] = Installer.new(@config,
+ "#{@ardir}/packages/#{pack}",
+ "packages/#{pack}")
+ end
+ with = extract_selection(config('with'))
+ without = extract_selection(config('without'))
+ @selected = @installers.keys.select {|name|
+ (with.empty? or with.include?(name)) \
+ and not without.include?(name)
+ }
+ end
+
+ def extract_selection(list)
+ a = list.split(/,/)
+ a.each do |name|
+ setup_rb_error "no such package: #{name}" unless @installers.key?(name)
+ end
+ a
+ end
+
+ def print_usage(f)
+ super
+ f.puts 'Inluded packages:'
+ f.puts ' ' + @packages.sort.join(' ')
+ f.puts
+ end
+
+ #
+ # Task Handlers
+ #
+
+ def exec_config
+ run_hook 'pre-config'
+ each_selected_installers {|inst| inst.exec_config }
+ run_hook 'post-config'
+ @config.save # must be final
+ end
+
+ def exec_setup
+ run_hook 'pre-setup'
+ each_selected_installers {|inst| inst.exec_setup }
+ run_hook 'post-setup'
+ end
+
+ def exec_install
+ run_hook 'pre-install'
+ each_selected_installers {|inst| inst.exec_install }
+ run_hook 'post-install'
+ end
+
+ def exec_test
+ run_hook 'pre-test'
+ each_selected_installers {|inst| inst.exec_test }
+ run_hook 'post-test'
+ end
+
+ def exec_clean
+ rm_f @config.savefile
+ run_hook 'pre-clean'
+ each_selected_installers {|inst| inst.exec_clean }
+ run_hook 'post-clean'
+ end
+
+ def exec_distclean
+ rm_f @config.savefile
+ run_hook 'pre-distclean'
+ each_selected_installers {|inst| inst.exec_distclean }
+ run_hook 'post-distclean'
+ end
+
+ #
+ # lib
+ #
+
+ def each_selected_installers
+ Dir.mkdir 'packages' unless File.dir?('packages')
+ @selected.each do |pack|
+ $stderr.puts "Processing the package `#{pack}' ..." if verbose?
+ Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}")
+ Dir.chdir "packages/#{pack}"
+ yield @installers[pack]
+ Dir.chdir '../..'
+ end
+ end
+
+ def run_hook(id)
+ @root_installer.run_hook id
+ end
+
+ # module FileOperations requires this
+ def verbose?
+ @config.verbose?
+ end
+
+ # module FileOperations requires this
+ def no_harm?
+ @config.no_harm?
+ end
+
+end # class ToplevelInstallerMulti
+
+
+class Installer
+
+ FILETYPES = %w( bin lib ext data conf man )
+
+ include FileOperations
+ include HookScriptAPI
+
+ def initialize(config, srcroot, objroot)
+ @config = config
+ @srcdir = File.expand_path(srcroot)
+ @objdir = File.expand_path(objroot)
+ @currdir = '.'
+ end
+
+ def inspect
+ "#<#{self.class} #{File.basename(@srcdir)}>"
+ end
+
+ def noop(rel)
+ end
+
+ #
+ # Hook Script API base methods
+ #
+
+ def srcdir_root
+ @srcdir
+ end
+
+ def objdir_root
+ @objdir
+ end
+
+ def relpath
+ @currdir
+ end
+
+ #
+ # Config Access
+ #
+
+ # module FileOperations requires this
+ def verbose?
+ @config.verbose?
+ end
+
+ # module FileOperations requires this
+ def no_harm?
+ @config.no_harm?
+ end
+
+ def verbose_off
+ begin
+ save, @config.verbose = @config.verbose?, false
+ yield
+ ensure
+ @config.verbose = save
+ end
+ end
+
+ #
+ # TASK config
+ #
+
+ def exec_config
+ exec_task_traverse 'config'
+ end
+
+ alias config_dir_bin noop
+ alias config_dir_lib noop
+
+ def config_dir_ext(rel)
+ extconf if extdir?(curr_srcdir())
+ end
+
+ alias config_dir_data noop
+ alias config_dir_conf noop
+ alias config_dir_man noop
+
+ def extconf
+ ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt
+ end
+
+ #
+ # TASK setup
+ #
+
+ def exec_setup
+ exec_task_traverse 'setup'
+ end
+
+ def setup_dir_bin(rel)
+ files_of(curr_srcdir()).each do |fname|
+ update_shebang_line "#{curr_srcdir()}/#{fname}"
+ end
+ end
+
+ alias setup_dir_lib noop
+
+ def setup_dir_ext(rel)
+ make if extdir?(curr_srcdir())
+ end
+
+ alias setup_dir_data noop
+ alias setup_dir_conf noop
+ alias setup_dir_man noop
+
+ def update_shebang_line(path)
+ return if no_harm?
+ return if config('shebang') == 'never'
+ old = Shebang.load(path)
+ if old
+ $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1
+ new = new_shebang(old)
+ return if new.to_s == old.to_s
+ else
+ return unless config('shebang') == 'all'
+ new = Shebang.new(config('rubypath'))
+ end
+ $stderr.puts "updating shebang: #{File.basename(path)}" if verbose?
+ open_atomic_writer(path) {|output|
+ File.open(path, 'rb') {|f|
+ f.gets if old # discard
+ output.puts new.to_s
+ output.print f.read
+ }
+ }
+ end
+
+ def new_shebang(old)
+ if /\Aruby/ =~ File.basename(old.cmd)
+ Shebang.new(config('rubypath'), old.args)
+ elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby'
+ Shebang.new(config('rubypath'), old.args[1..-1])
+ else
+ return old unless config('shebang') == 'all'
+ Shebang.new(config('rubypath'))
+ end
+ end
+
+ def open_atomic_writer(path, &block)
+ tmpfile = File.basename(path) + '.tmp'
+ begin
+ File.open(tmpfile, 'wb', &block)
+ File.rename tmpfile, File.basename(path)
+ ensure
+ File.unlink tmpfile if File.exist?(tmpfile)
+ end