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.



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

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



18
19
20
21
22
# File 'lib/namer.rb', line 18

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

#from_regexObject



24
25
26
# File 'lib/namer.rb', line 24

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

#gsub(str) ⇒ Object



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

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

#inline_gsub(str) ⇒ Object



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

def inline_gsub(str)
  return str unless split_str = str.split(/# -- replace\n/)[1]
  split_str.gsub(/^\s*#\s?/, '')
end

#remoteObject



56
57
58
# File 'lib/namer.rb', line 56

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

#renameObject



45
46
47
48
49
50
51
52
53
54
# File 'lib/namer.rb', line 45

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



37
38
39
40
41
42
43
# File 'lib/namer.rb', line 37

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



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/namer.rb', line 60

def replace
  dir("**/*").each do |path|
    next unless File.file?(path)
    text = File.read(path)
    begin
      text = gsub(text)
      text = inline_gsub(text)
    rescue Exception => e
    ensure
      File.open(path, 'w') { |f| f.write(text) }
    end
  end
end