Permalink
Browse files

clear existing encoding comments and code cleanup

  • Loading branch information...
1 parent f611853 commit ad96f59ccbb38f7e281c6912893b3e45ed8c089e Manuel Ryan committed Aug 3, 2010
Showing with 39 additions and 25 deletions.
  1. +3 −8 bin/magic_encoding
  2. +35 −16 lib/magic_encoding.rb
  3. +1 −1 magic_encoding.gemspec
View
@@ -1,12 +1,7 @@
#!/usr/bin/env ruby
+# A simple tool to prepend magic comments for encoding to multiple ".rb" files
+
require 'magic_encoding'
-case ARGV.count
-when 0
- AddMagicComment.process
-when 1
- AddMagicComment.process(ARGV[0])
-when 2
- AddMagicComment.process(ARGV[0], ARGV[1])
-end
+AddMagicComment.process(ARGV)
View
@@ -1,33 +1,52 @@
-# -*- encoding : utf-8 -*-~
+# -*- encoding : utf-8 -*-
-# A simple library to prepend the encoding magic comment introduced with ruby 1.9 to
-# multiple ".rb" files
+# A simple library to prepend magic comments for encoding to multiple ".rb" files
-class AddMagicComment
+module AddMagicComment
+ # Options :
+ # 1 : Encoding
+ # 2 : Path
# TODO : check that the encoding specified is a valid encoding
- def self.process(encoding = "utf-8", directory = Dir.pwd)
+ def self.process(*options)
- # TODO : add support for other formats of magic comment (coding instead of encoding, emacs style magic comment, etc..)
- prefix = "# -*- encoding : #{encoding} -*-~\n"
+ # defaults
+ encoding = options[1] | "utf-8"
+ directory = options[2] | Dir.pwd
+
+ prefix = "# -*- encoding : #{encoding} -*-"
# TODO : add options for recursivity (and application of the script to a single file)
rbfiles = File.join(directory ,"**", "*.rb")
Dir.glob(rbfiles).each do |filename|
file = File.new(filename, "r+")
- file_data = file.read
- prefix_match = file_data[0..prefix.length-1]
-
- # go back to top
- file.pos = 0
+ lines = file.readlines
- # TODO : detect when to replace current encoding
- if prefix_match and prefix_match != prefix
- file.puts(prefix+file_data)
+ i = 0
+ # remove current encoding comment(s)
+ while lines[i].starts_with? "# encoding" |
+ lines[i].starts_with? "# coding" |
+ lines[i].starts_with? "# -*- encoding" |
+ lines.shift
end
+
+ # set current encoding
+ lines.insert(0,prefix)
+
+ file.pos = 0
+ file.puts(lines.join("\n"))
file.close
end
- p "Encoding magic comment set for #{Dir.glob(rbfiles).count} source files"
+ p "Magic comments set for #{Dir.glob(rbfiles).count} source files"
end
+
+end
+
+class String
+
+ def starts_with?(s)
+ self[0..s.length-1] == s
+ end
+
end
View
@@ -10,7 +10,7 @@ Gem::Specification.new do |s|
s.default_executable = %q{magic_encoding}
s.email = ["ryan@shamu.ch"]
s.executables = ["magic_encoding"]
- s.files = Dir.glob("{bin,lib}/**/*") + %w(README.rdoc CHANGELOG)
+ s.files = Dir.glob("{bin,lib}/**/*") + %w(README.rdoc CHANGELOG LICENCE)
s.homepage = %q{http://github.com/m-ryan/magic_encoding}
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}

0 comments on commit ad96f59

Please sign in to comment.