Class: Namer

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

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Namer

Returns a new instance of Namer.



5
6
7
8
9
10
11
12
13
14
# File 'lib/namer.rb', line 5

def initialize(args)
  path = Dir.pwd
  args.each do |arg|
    next unless arg.include?(':')
    @from, @to  = arg.split(':')
    rename        unless args.include?('--no-rename')
    replace       unless args.include?('--no-replace')
    rename_remote unless args.include?('--no-remote')
  end
end

Instance Method Details

#dir(pattern) ⇒ Object



16
17
18
19
20
# File 'lib/namer.rb', line 16

def dir(pattern)
  files =  Dir.glob(pattern, File::FNM_DOTMATCH)
  files -= %w[. ..]
  files.reject { |f| f =~ /^.git/ }
end

#from_regexObject



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

def from_regex
  /([^a-zA-Z]|^)#{@from}([^a-zA-Z]|$)/
end

#gsub(str) ⇒ Object



26
27
28
# File 'lib/namer.rb', line 26

def gsub(str)
  str.gsub(from_regex, "\\1#{@to}\\2")
end

#remoteObject



49
50
51
# File 'lib/namer.rb', line 49

def remote
  `git remote show -n origin`.match(/Push\s+URL:\s+(\S+)/)[1] rescue nil
end

#renameObject



38
39
40
41
42
43
44
45
46
47
# File 'lib/namer.rb', line 38

def rename
  files = dir("**/#{@from}*")
  begin
    if a = files.pop
      b = a.split('/')
      b[-1] = gsub(b[-1])
      FileUtils.mv(a, b.join('/'))
    end
  end while files.length > 0
end

#rename_remoteObject



30
31
32
33
34
35
36
# File 'lib/namer.rb', line 30

def rename_remote
  url = remote
  new_url = gsub(url)
  return if url == new_url
  `git remote rm origin`
  `git remote add origin #{new_url}`
end

#replaceObject



53
54
55
56
57
58
59
60
# File 'lib/namer.rb', line 53

def replace
  dir("**/*").each do |path|
    next unless File.file?(path)
    text = File.read(path)
    next unless (text =~ from_regex rescue nil)
    File.open(path, 'w') { |f| f.write(gsub(text)) }
  end
end