Class: ConfManager

Inherits:
Object
  • Object
show all
Includes:
Singleton, SqweezeUtils
Defined in:
lib/confManager.rb

Constant Summary

Constants included from SqweezeUtils

SqweezeUtils::EMBED_MIME_TYPES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from SqweezeUtils

#ansi_bold, #ansi_green, #ansi_nocolour, #ansi_red, #ansi_yellow, #byteweight, #compression_percentage, #encoded_contents, #find_file_in_targetdir, #mime_type, #notify, #remap_filepath, #write_file

Constructor Details

#initializeConfManager

Class constructor.

As ConfManager implements the singleton pattern, it is actually instanciated only once. The same instance might be retrieved from different places by calling the method:

ConfManager.instance()



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/confManager.rb', line 14

def initialize  
  @conf_filename='.sqweeze.yml'
  @source_dir=nil
  @target_dir=nil
  @files=[]    
  @conf={
    :suppress_info => false,
    :suppress_debug => true,
    :suppress_warn => false,
    :suppress_error => false,
    :bin_paths => {},
    :dom_documents => [],
    :include_files => [],
    :exclude_files => [],
    :compress_png  => true,
    :compress_jpeg => true,
    :compress_gif  => true,
    :compress_js  => true,
    :compress_css  => true,
    :append_scripts_to => :head,
    :default_js_compressor => :yui,
    :optimisation_strategy => :all_in_one
  }
end

Instance Attribute Details

#confObject (readonly)

Returns the value of attribute conf.



38
39
40
# File 'lib/confManager.rb', line 38

def conf
  @conf
end

#conf_filenameObject (readonly)

Returns the value of attribute conf_filename.



38
39
40
# File 'lib/confManager.rb', line 38

def conf_filename
  @conf_filename
end

#filesObject (readonly)

Returns the value of attribute files.



38
39
40
# File 'lib/confManager.rb', line 38

def files
  @files
end

#source_dirObject (readonly)

Returns the value of attribute source_dir.



38
39
40
# File 'lib/confManager.rb', line 38

def source_dir
  @source_dir
end

#target_dirObject (readonly)

Returns the value of attribute target_dir.



38
39
40
# File 'lib/confManager.rb', line 38

def target_dir
  @target_dir
end

Instance Method Details

#copy_sourceObject

Copies the source into the target directory.



90
91
92
93
94
95
# File 'lib/confManager.rb', line 90

def copy_source
  FileUtils.cp_r(@source_dir,@target_dir)
  # avoid nesting into each other multiple copies of the same directory
  nested_dir=[@target_dir,File.basename(@source_dir)].join('/')
  FileUtils.rm_r(nested_dir) if File.directory?(nested_dir)
end

#get_conf(key) ⇒ Object

Getter method for retrieving configuration values.



51
# File 'lib/confManager.rb', line 51

def get_conf(key);@conf[key.to_sym];end

#get_files(pathlist = ['**/*']) ⇒ Object

Get all the files matching an array of patterns

(Any file expansion patterns accepted ruby’s Dir[] method can be used).



190
191
192
193
194
195
196
# File 'lib/confManager.rb', line 190

def get_files(pathlist=['**/*'])
  pathlist.collect{|pattern|
 
    Dir[ mkpath(pattern)  ].
         reject{|f|File.directory?(f) or not File.exists?(f)}
  }.flatten
end

#get_target_path(infile_path) ⇒ Object

Remaps a filepath from the source to the target directory.

TODO:check if this works with relative paths (i.e. <code>../imgs/bar.png</code>)


101
102
103
# File 'lib/confManager.rb', line 101

def get_target_path(infile_path)
 infile_path.gsub( Regexp.new("^#{@source_dir}"), @target_dir)
end

#list_filesObject

Explodes the inclusion/exclusion patterns provided by the user into a list, and populates the @files attribute.



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/confManager.rb', line 166

def list_files
  # unless the user defined file inclusion list is empty, select only the files specified by the user.
  # Otherwise consider all the files in the project directory as potentially compressible.

  @files = unless get_conf(:include).empty?
             files=get_files( get_conf(:include));$log.debug("Including #{files.size} file/s from user list")
             files
           else 
             get_files
  end
 
  # always exclude files explicitly blacklisted by the use 
  exclude_files=get_files(get_conf(:exclude))
  
  
  notify("Excluding #{exclude_files.size} file/s from user list", :debug)
  @files -= exclude_files
  notify("#{@files.size} file/s found", :info)
end

#mkpath(pattern, dir = @source_dir) ⇒ Object

Generates a file pattern suitable to be expanded by ruby’s Dir[] method.



108
109
110
# File 'lib/confManager.rb', line 108

def mkpath(pattern,dir=@source_dir) 
  dir.to_a.push(pattern).join('/')
end

#parse_conf(configfile = "#{ENV['HOME']}/#{@conf_filename}") ⇒ Object

Parses configuration files and sets user-defined file inclusion/exlusion patterns.



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
# File 'lib/confManager.rb', line 132

def parse_conf(configfile="#{ENV['HOME']}/#{@conf_filename}")
  notify("Parsing configuration file: #{configfile}",:debug) 
  conf=YAML::load_file( configfile ) 
   
  bin_paths={}
  # do not select commands if their path cannot be found on disk      
  conf['bin_paths'].each do |h| 
      if File.exists?(h.values.first)
        bin_paths[h.keys.first.to_sym] = h.values.first 
      else
        $log.warn("Command #{h.keys.first} not found in #{h.values.first}")
      end
  end
  set_conf(:bin_paths,bin_paths) unless bin_paths.empty?
  
  # Expand the dom document pattern excluding the files located in the source directory.     
  if conf['dom_documents']
    
    domdoc_file_patterns = Dir[conf['dom_documents']].collect{|f| f.gsub(Regexp.new("^#{@source_dir}"),@target_dir)}
    set_conf(:dom_documents, domdoc_file_patterns)
  end
  
  # Sets the favourite js compressor ( can either be :yui or :closure, defaults on YUI)
  compressor = ( conf['default_js_compressor'] == :closure) ?  :closure : :yui
  set_conf(:default_js_compressor, compressor)
  
  # others..
  %w(include exclude).each {|k| set_conf(k, conf[k].to_a)}
  %w(optimisation_strategy append_scripts_to 
    suppress_messagess suppress_debug suppress_warnings).each{|k| set_conf(k,conf[k]) if conf[k]}
end

#prepare(source, target = nil, override_conf = {}) ⇒ Object

Sets the source directory, the target directory, and parse configuration files.

source

the source directory

target

the target directory

override_conf

a Hash which may be used to override file-based configuration.



61
62
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
# File 'lib/confManager.rb', line 61

def prepare(source,target=nil,override_conf={})
  
  @source_dir=source
  raise 'Cannot sqweeze current directory' if source == '.'

  @target_dir=unless target
    "#{File.basename(source)}_sqweezed"            
  else 
    target 
  end
  copy_source

  write_globalconf
  # Parses the global configuration file in $HOME.
  parse_conf
  # Parses the local configuration file in source directory.
  local_conf=mkpath(@conf_filename)
  parse_conf(local_conf) if File.exists?(local_conf)
 
  # CLI/Overrides of the values already set in config files. 
  override_conf.each{|k,v| set_conf(k, v)} unless override_conf.empty?

  # Creates the list of the files in the project directory.
  
  list_files

end

#set_conf(key, value) ⇒ Object



47
# File 'lib/confManager.rb', line 47

def set_conf(key,value);@conf[key.to_sym]=value;end

#write_globalconfObject

Defines a global .sqweeze.yml file and places it in the user’s home directory.

The golobal config files sets the default path of the image compression binaries (see @conf).



117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/confManager.rb', line 117

def write_globalconf
  unless File.exists?("#{ENV['HOME']}/#{@conf_filename}") 
       File.open("#{ENV['HOME']}/#{@conf_filename}",'w') do |f|
         f.write("bin_paths:
 - pngcrush: /usr/bin/pngcrush
 - jpegtran: /usr/bin/jpegtran
 - gifsicle: /usr/bin/gifsicle
         ")
         f.close
       end
  end
end