Class: BowerRails::Performer

Inherits:
Object
  • Object
show all
Includes:
FileUtils
Defined in:
lib/bower-rails/performer.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.perform(*args, &block) ⇒ Object



10
11
12
# File 'lib/bower-rails/performer.rb', line 10

def self.perform(*args, &block)
  new.perform(*args, &block)
end

Instance Method Details

#dslObject



42
43
44
# File 'lib/bower-rails/performer.rb', line 42

def dsl
  @dsl ||= BowerRails::Dsl.evalute(root_path, "Bowerfile")
end

#dsl_perform_command(remove_components = true, &block) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/bower-rails/performer.rb', line 46

def dsl_perform_command(remove_components = true, &block)
  if remove_components
    dsl.write_bower_json
    dsl.write_dotbowerrc
    puts "bower.js files generated"
  end

  if block_given?
    dsl.directories.each do |dir|
      Dir.chdir(dir) do
        yield
      end
    end
  end
end

#find_command(cmd, paths = []) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/bower-rails/performer.rb', line 185

def find_command(cmd, paths = [])
  exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
  paths += ENV['PATH'].split(File::PATH_SEPARATOR)
  paths.each do |path|
    exts.each do |ext|
      exe = File.join(path, "#{cmd}#{ext}")
      if (File.executable?(exe) && File.file?(exe))
        return Shellwords.escape exe
      end
    end
  end
  nil
end

#perform(remove_components = true, &block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/bower-rails/performer.rb', line 18

def perform(remove_components = true, &block)
  npm_path = File.join(root_path, 'node_modules', '.bin')
  bower = find_command('bower', [npm_path])

  if bower.nil?
    $stderr.puts ["Bower not found! You can install Bower using Node and npm:",
    "$ npm install bower -g",
    "For more info see http://bower.io/"].join("\n")
    exit 127
  end

  if entries.include?('Bowerfile')
    dsl_perform_command remove_components do
      instance_exec(bower, &block) if block_given?
    end
  elsif entries.include?('bower.json')
    perform_command remove_components do
      instance_exec(bower, &block) if block_given?
    end
  else
    raise LoadError, "No Bowerfile or bower.json file found. Make sure you have it at the root of your project"
  end
end

#perform_command(remove_components = true, &block) ⇒ Object

run the passed bower block in appropriate folders



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/bower-rails/performer.rb', line 63

def perform_command(remove_components = true, &block)
  # Load in bower json file
  txt  = File.read(File.join(root_path, "bower.json"))
  json = JSON.parse(txt)


  # Load and merge root .bowerrc
  dot_bowerrc = JSON.parse(File.read(File.join(root_path, '.bowerrc'))) rescue {}
  dot_bowerrc["directory"] = components_directory

  if json.reject{ |key| ['lib', 'vendor'].include? key }.empty?
    folders = json.keys
  else
    raise "Assuming a standard bower package but cannot find the required 'name' key" unless !!json['name']
    folders = ['vendor']
  end

  folders.each do |dir|
    data = json[dir]

    # Assume using standard bower.json if folder name is not found
    data = json if data.nil?

    # Check folder existence and create?
    dir = File.join(root_path, dir, "assets")
    FileUtils.mkdir_p dir unless File.directory? dir
    # Go in to dir to act
    Dir.chdir(dir) do

      # Remove old components
      FileUtils.rm_rf("#{components_directory}/*") if remove_components

      # Create bower.json
      File.open("bower.json", "w") do |f|
        f.write(data.to_json)
      end

      # Create .bowerrc
      File.open(".bowerrc", "w") do |f|
        f.write(JSON.pretty_generate(dot_bowerrc))
      end

      # Run command
      yield  if block_given?

      # Remove bower.json
      FileUtils.rm("bower.json")

      # Remove .bowerrc
      FileUtils.rm(".bowerrc")
    end if data && !data["dependencies"].empty?
  end
end

#remove_extra_filesObject



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
# File 'lib/bower-rails/performer.rb', line 146

def remove_extra_files
  puts "\nAttempting to remove all but main files as specified by bower\n"

  Dir["#{components_directory}/*"].each do |component_dir|
    component_name = component_dir.split('/').last
    next if clean_should_skip_component? component_name

    if File.exists?(File.join(component_dir, 'bower.json'))
      bower_file = File.read(File.join(component_dir, 'bower.json'))
    elsif File.exists?(File.join(component_dir, '.bower.json'))
      bower_file = File.read(File.join(component_dir, '.bower.json'))
    else
      next
    end

    # Parse bower.json
    bower_json = JSON.parse(bower_file)
    main_files = Array(bower_json['main']) + main_files_for_component(component_name)
    next if main_files.empty?

    # Remove "./" relative path from main file strings
    main_files.map! { |file| File.join(component_dir, file.gsub(/^\.\//, '')) }

    # Make Regexp to handle wildcards
    main_files.map! { |file| Regexp.new("\\A" + file.gsub(/\*/, '.*') + "\\Z") }

    # Delete all files that are not in main
    Find.find(component_dir).reverse_each do |file_or_dir|
      next if main_files.any? { |pattern| file_or_dir =~ pattern }
      if File.directory?(file_or_dir)
        Dir.rmdir(file_or_dir) if (Dir.entries(file_or_dir) - %w[ . .. ]).empty?
      else
        FileUtils.rm(file_or_dir)
      end
    end
  end
end

#resolve_asset_paths(root_directory = components_directory) ⇒ Object



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
# File 'lib/bower-rails/performer.rb', line 117

def resolve_asset_paths(root_directory = components_directory)
  # Resolve relative paths in CSS
  Dir["#{components_directory}/**/*.css"].each do |filename|
    contents = File.read(filename) if FileTest.file?(filename)
    # http://www.w3.org/TR/CSS2/syndata.html#uri
    url_regex = /url\((?!\#)\s*['"]?((?![a-z]+:)([^'"\)]*?)([?#][^'"\)]*)?)['"]?\s*\)/

    # Resolve paths in CSS file if it contains a url
    if contents =~ url_regex
      directory_path = Pathname.new(File.dirname(filename))
      .relative_path_from(Pathname.new(root_directory))

      # Replace relative paths in URLs with Rails asset_path helper
      new_contents = contents.gsub(url_regex) do |match|
        relative_path = $2
        params = $3
        image_path = directory_path.join(relative_path).cleanpath
        puts "#{match} => #{image_path} #{params}"

        "url(<%= asset_path '#{image_path}' %>#{params})"
      end

      # Replace CSS with ERB CSS file with resolved asset paths
      FileUtils.rm(filename)
      File.write(filename + '.erb', new_contents)
    end
  end
end

#root_pathObject



14
15
16
# File 'lib/bower-rails/performer.rb', line 14

def root_path
  BowerRails.root_path
end