Class: Regex::Replacer

Inherits:
Object
  • Object
show all
Defined in:
lib/regex/replacer.rb

Defined Under Namespace

Classes: Matcher

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Replacer

Returns a new instance of Replacer.



34
35
36
37
38
39
# File 'lib/regex/replacer.rb', line 34

def initialize(options={})
  @rules = []
  options.each do |k,v|
    __send__("#{k}=", v)
  end
end

Instance Attribute Details

#backupObject

Make backups of files when they change.



28
29
30
# File 'lib/regex/replacer.rb', line 28

def backup
  @backup
end

#escapeObject

Make all patterns exact string matchers.



16
17
18
# File 'lib/regex/replacer.rb', line 16

def escape
  @escape
end

#globalObject

Make all patterns global matchers.



19
20
21
# File 'lib/regex/replacer.rb', line 19

def global
  @global
end

#insensitiveObject

Make all patterns case-insenstive matchers.



22
23
24
# File 'lib/regex/replacer.rb', line 22

def insensitive
  @insensitive
end

#interactiveObject

Interactive replacement.



31
32
33
# File 'lib/regex/replacer.rb', line 31

def interactive
  @interactive
end

#multilineObject

Make all patterns multi-line matchers.



25
26
27
# File 'lib/regex/replacer.rb', line 25

def multiline
  @multiline
end

#recursiveObject

Is this a recursive search?



13
14
15
# File 'lib/regex/replacer.rb', line 13

def recursive
  @recursive
end

#rulesObject (readonly)

Array of [search, replace] rules.



10
11
12
# File 'lib/regex/replacer.rb', line 10

def rules
  @rules
end

Class Method Details

.cli(argv = ARGV) ⇒ Object (private)



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/regex/replacer.rb', line 115

def self.cli(argv=ARGV)
  searches = []
  replaces = []
  options = {}
  parser = OptionParser.new do |opt|
    opt.on('--search', '-s PATTERN', 'search portion of substitution') do |search|
      searches << search
    end
    opt.on('--template', '-t NAME', 'search for built-in regular expression') do |name|
      searches << "$#{name}"
    end
    opt.on('--replace', '-r STRING', 'replacement string of substitution') do |replace|
      replaces << replace
    end
    opt.on('--recursive', '-R', 'search recursively though subdirectories') do
      options[:recursive] = true
    end
    opt.on('--escape', '-e', 'make all patterns verbatim string matchers') do
      options[:escape] = true
    end
    opt.on('--insensitive', '-i', 'make all patterns case-insensitive matchers') do
      options[:insensitive] = true
    end
    #opt.on('--unxml', '-x', 'ignore XML/HTML tags') do
    #  options[:unxml] = true
    #end
    opt.on('--global', '-g', 'make all patterns global matchers') do
      options[:global] = true
    end
    opt.on('--multiline', '-m', 'make all patterns multi-line matchers') do
      options[:multiline] = true
    end
    opt.on('-b', '--backup', 'backup any files that are changed') do
      options[:backup] = true
    end
    opt.on('-i', '--interactive', 'interactive mode') do
      options[:interactive] = true
    end
     opt.on_tail('--debug', 'run in debug mode') do
      $DEBUG = true
    end
    opt.on_tail('--help', '-h', 'display this lovely help message') do
      puts opt
      exit 0
    end
  end
  parser.parse!(argv)

  files = []

  argv.each{ |file|
    raise "file does not exist -- #{file}" unless File.exist?(file)
    if File.directory?(file)
      if options[:recursive] 
        files.concat Dir[File.join(file, '**')].reject{ |d| File.directory?(d) }
      end
    else
      files << file
    end
  }

  targets = files.empty? ? [ARGF] : files.map{ |f| File.new(f) }

  unless searches.size == replaces.size
    raise "search replace mismatch -- #{searches.size} to #{replaces.size}"
  end
  rules = searches.zip(replaces)

  replacer = new(options)
  rules.each do |search, replace|
    replacer.rule(search, replace)
  end
  replacer.apply(*targets)
end

Instance Method Details

#apply(*ios) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/regex/replacer.rb', line 47

def apply(*ios)
  ios.each do |io|
    original = (IO === io || StringIO === io ? io.read : io.to_s)
    generate = original.to_s
    rules.each do |(pattern, replacement)|
      begin
        if pattern.global
          generate = generate.gsub(pattern.to_re, replacement)
        else
          generate = generate.sub(pattern.to_re, replacement)
        end
      rescue => err
        warn(io.inspect + ' ' + err.to_s) if $VERBOSE
      end
    end
    if original != generate
      write(io, generate)
    end
  end
end

#interactive_gsub(string, pattern, replacement) ⇒ Object

TODO: interactive mode needs to handle 1 style substitutions.



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/regex/replacer.rb', line 70

def interactive_gsub(string, pattern, replacement)
  copy = string.dup
  string.scan(pattern) do |match|
    print "#{match} ? (Y/n)"
    case ask
    when 'y', 'Y', ''
      copy[$~.begin(0)..$~.end(0)] = replacement
    else
    end
  end
end

#re(pattern) ⇒ Object (private)

Parse pattern matcher.



85
86
87
88
89
90
91
92
93
# File 'lib/regex/replacer.rb', line 85

def re(pattern)
  Matcher.new(
    pattern,
    :global=>global,
    :escape=>escape,
    :multiline=>multiline,
    :insensitive=>insensitive
  )
end

#rule(pattern, replacement) ⇒ Object



42
43
44
# File 'lib/regex/replacer.rb', line 42

def rule(pattern, replacement)
  @rules << [re(pattern), replacement]
end

#write(io, text) ⇒ Object (private)



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/regex/replacer.rb', line 96

def write(io, text)
  case io
  when File
    if backup
      backup_file = io.path + '.bak'
      File.open(backup_file, 'w'){ |f| f << File.read(io.path) }
    end
    File.open(io.path, 'w'){ |w| w << text }
  when StringIO
    io.string = text
  when IO
    # TODO: How to handle general IO object?
    io.write(text)
  else
    io.replace(text)
  end
end