Class: Codestrap::Core

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv = nil) ⇒ Core

Returns a new instance of Core.



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

def initialize(argv=nil)
  # CLI options
  if argv
    self.cli = Codestrap::Cli.new argv
    self.cli.options
  end

  # Config
  @config = Codestrap::Config.new

  case @config.local.urls
    when Array
      @config.local.urls.each do |url|
        @clients ||= []
        @clients << Codestrap::Client.new(url)
      end
    when String
      @clients ||= []
      @clients << Codestrap::Client.new(@config.local.urls)
    when NilClass
    else
      raise Exception, 'Unknown data structure'
  end
  self
end

Instance Attribute Details

#cliCodestrap::Cli

Command line object

Returns:



34
35
36
# File 'lib/codestrap.rb', line 34

def cli
  @cli
end

#clientsArray<Codestrap::Client>

List of client objects

Returns:



39
40
41
# File 'lib/codestrap.rb', line 39

def clients
  @clients
end

#configCodestrap::Config

Configuration object created from Codestrapfile

Returns:



44
45
46
# File 'lib/codestrap.rb', line 44

def config
  @config
end

#envHash

Environment variables. Defaults to system environment variables

Returns:

  • (Hash)


52
53
54
# File 'lib/codestrap.rb', line 52

def env
  @env ||= ENV.to_hash
end

#projectString

Boilerplate template path

Returns:

  • (String)


29
30
31
# File 'lib/codestrap.rb', line 29

def project
  @project
end

#templateString

Codestrap template path

Returns:

  • (String)


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

def template
  @template
end

Class Method Details

.loggerCodestrap::Log

Logging object

Returns:



120
121
122
123
124
125
# File 'lib/codestrap.rb', line 120

def self.logger
  @@logger ||= begin
    logger  = Codestrap::Log.new
    @@logger = logger
  end
end

Instance Method Details

#execute!Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/codestrap.rb', line 153

def execute!
  # Run type
  case
    when cli.command =~ /stub(.+)$/
      self.template = $1
      stub
    when cli.command =~ /strap(.+)$/
      self.project = $1
      strap
    when self.cli.options.generate
      strap_rcfile
      strap_init_home
      strap_links
    else
      logger.error :INVALIDCMD, cli.command
      exit 1
  end

  exit 0
end

#list_cmdsArray Also known as: ls_cmd

List all stub.. and strap.. commands

Returns:

  • (Array)


492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/codestrap.rb', line 492

def list_cmds
  links = []
  dir   = @config.local.links
  if File.directory? dir
    Dir.chdir(dir) do
      Dir.glob('*').each do |f|
        next unless File.symlink? f
        next unless f =~ /^(?:stub|strap)[A-Za-z0-9._-]+$/
        links.push f
      end
    end
  end
  links
end

#list_strapsArray Also known as: ls_strap

Available projects from local and server

Returns:

  • (Array)


469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/codestrap.rb', line 469

def list_straps
  straps = []
  if @clients
    @clients.each do |client|
      straps ||= []
      straps += client.straplist || []
      straps.flatten!
    end
  end
  @config.local.content.each do |dir|
    next unless File.directory? dir
    if File.directory? dir
      Dir.chdir(dir) do
        straps += Dir.glob('*').select { |f| File.directory? f }
      end
    end
  end
  straps.uniq
end

#list_stubsArray Also known as: ls_codestrap

Available codestraps from local and server

Returns:

  • (Array)


448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/codestrap.rb', line 448

def list_stubs
  codestraps = []
  if @clients
    @clients.each do |client|
      codestraps ||= []
      codestraps += client.stublist || []
      codestraps.flatten!
    end
  end
  @config.local.content.each do |dir|
    next unless File.directory? dir
    Dir.chdir(dir) do
      codestraps += Dir.glob('*.erb').select { |f| File.file? f }
    end
  end
  codestraps.uniq
end

#loggerCodestrap::Log

Logging object

Returns:



114
115
116
# File 'lib/codestrap.rb', line 114

def logger
  self.class.logger
end

#strap(dst = nil, src = nil) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/codestrap.rb', line 195

def strap(dst=nil, src=nil)
  # Create objects
  obj         = Codestrap::Object::Factory.new
  obj.dirs    = @config.local.objects
  obj.clients = @clients
  obj.cli     = @cli
  obj.config  = @config

  argv             = self.cli.argv
  renderer         = Codestrap::Strap::Factory.new('Standard').construct(argv)
  renderer.ignore  = @config.local.ignore
  renderer.objects = obj
  renderer.src     = src || self.project
  renderer.dst     = dst || self.cli.argv[0]
  renderer.pre
  renderer.execute
  renderer.post
  renderer.to_disk
end

#strap_init_home(codestrap = '.codestrap') ⇒ Object

Initialize home directory

Parameters:

  • codestrap (String) (defaults to: '.codestrap')

    Optional name of codestrap directory in $HOME. Defaults to '.codestrap'



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/codestrap.rb', line 263

def strap_init_home(codestrap='.codestrap')
  root_path = File.join(env['HOME'], codestrap)
  unless File.exist?(root_path)
    puts "Creating #{root_path}"
    Dir.mkdir(root_path)
  end
  %w(bin content objects).each do |dir|
    path = File.join(root_path, dir)
    unless File.exist?(path)
      puts "Creating #{path}"
      FileUtils.mkpath path
    end
  end
  codestrapfile = File.join(env['HOME'], codestrap, 'Codestrapfile')
  unless File.exist?(codestrapfile)
    tmpfile = Tempfile.new('codestrapfile')
    output = <<EOF
Codestrapfile.config do |conf|
  # Base directory or list of base directories that contain "object" and "content" sub directories
  # Defaults to $HOME/.codestrap
  #conf.local.base   = [ "ENV['HOME']/.codestrap", '/usr/local/codestrap' ]
  #conf.local.base = "ENV['HOME']/.codestrap"

  # Ignore paths or list of paths to ignore
  #conf.local.ignore = [ '.git', '.svn' ]
  #conf.local.ignore = '.git'
end
EOF
    tmpfile.write(output)
    tmpfile.close
    File.rename(tmpfile, codestrapfile)
  end
end

Generate symlinks



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/codestrap.rb', line 298

def strap_links
  # FixMe - Move to Codestrap::Log
  unless cli.command =~ /^strap$/
    logger.error(:LINKTARGET, cli.command, 'strap')
    exit 1
  end

  # stub templates
  newtemplates = list_stubs.map { |f| File.basename(f, '.erb') } - list_cmds.select { |f| f =~ /^stub/ }.map { |f| f =~ /^stub(.+)$/; $1 }

  newtemplates.each do |file|
    link = File.expand_path(File.join(@config.local.links, 'stub' + file))
    if File.symlink?(link) and File.exist?(File.readlink(link))
      next
    elsif File.symlink?(link)
      File.unlink link
    end

    File.symlink cli.abspath, link
  end

  # strap templates
  newprojects = list_straps - list_cmds.select { |f| f =~ /^strap/ }.map { |f| f =~ /^strap(.+)$/; $1 }

  newprojects.each do |project|
    link = File.expand_path File.join(@config.local.links, 'strap' + project)
    if File.symlink?(link) and File.exist?(File.readlink(link))
      next
    elsif File.symlink?(link)
      File.unlink link
    end

    File.symlink cli.abspath, link
  end
end

#strap_metadata(name = nil, options = nil, paths = @config.local.content) ⇒ Hash

Generate strap metadata

Parameters:

  • name (String) (defaults to: nil)

    Optional module name

  • options (Hash) (defaults to: nil)

    Flags to turn off/on metadata { :src => [true|false] :ftype => [true|false] :mode => [true|false] }

  • paths (Array) (defaults to: @config.local.content)

    Optional path list for content search

Returns:

  • (Hash)

    Strap directory structure metadata { 'strap_name' => { :files => [ { :file => 'relative/tree/file/path', :src => '/absolute/file/source', :ftype => 'File type as returned by File::Stat.new(file).ftype, EG "file", "directory"' :mode => 'File mode as returned by File::Stat.new(file).mode' } ] } }



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/codestrap.rb', line 361

def (name=nil, options=nil, paths=@config.local.content)
  # TODO - rename
  tree    = {}
  options ||= {src: false, ftype: true, mode: true}
  cur_dir = Dir.pwd
  paths.each do |path|
    next unless File.directory? path
    Dir.chdir(path) do
      Dir.entries('.').each do |mod|
        next if mod =~ /^\.{1,2}$/
        next unless File.directory? mod
        next if name and not name.eql? mod
        next if tree.has_key? mod
        tree[mod] = {files: []}
        Dir.chdir(mod) do
          Dir.glob('**/**').each do |file|
            stat       = File.stat file
            obj        = {}
            obj[:file] = file
            if options[:src]
              case path
                when %r{^/}
                  obj[:src] = File.expand_path(File.join(path, mod, file))
                else
                  obj[:src] = File.expand_path(File.join(cur_dir, path, mod, file))
              end
            end
            obj[:ftype] = stat.ftype if options[:ftype]
            obj[:mode]  = sprintf('%o', stat.mode) if options[:mode]
            tree[mod][:files] << obj
          end
        end
      end
    end
  end
  tree
end

#strap_rcfileObject

Adds an entry to rcfile depending on shell



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/codestrap.rb', line 217

def strap_rcfile
  line = "\nexport PATH=$PATH:$HOME/.codestrap/bin\n"

  # Check shell
  rcfile = begin
    case env['SHELL']
      when %r{/bin/bash$}
        File.join(env['HOME'], '.bash_profile')
      when %r{/bin/zsh$}
        File.join(env['HOME'], '.zshrc')
      when %r{/bin/sh$}
        File.join(env['HOME'], '.profile')
      else
        nil
    end
  end

  # Check rcfile
  write = begin
    case
      when !rcfile
        false
      when(File.exist?(rcfile) and File.foreach(rcfile).grep(%r{export PATH=\$PATH:\$HOME/\.codestrap/bin}).length < 1)
        line = "\n" + line
        true
      when(not File.exist?(rcfile))
        true
      else
        false
    end
  end

  # Write file
  if write
    puts "Adding PATH='$PATH:$HOME/.codestrap/bin' to #{rcfile}"
    File.open(rcfile,'a') do |fh|
      fh.write(line)
    end
  end
end

#stub(dst = nil, src = nil) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/codestrap.rb', line 174

def stub(dst=nil, src=nil)
  # Create objects
  obj         = Codestrap::Object::Factory.new
  obj.dirs    = @config.local.objects
  obj.clients = @clients
  obj.cli     = @cli
  obj.config  = @config

  argv             = self.cli.argv

  # Render setup
  renderer         = Codestrap::Stub::Factory.new('Standard').construct(argv)
  renderer.objects = obj
  renderer.src     = src || self.template
  renderer.dst     = dst || self.cli.argv[0]
  renderer.pre
  renderer.execute
  renderer.post
  renderer.to_disk
end

#stub_metadata(name = nil, options = nil, paths = @config.local.content) ⇒ Hash

Generate strap metadata

Parameters:

  • name (String) (defaults to: nil)

    Optional module name

  • options (Hash) (defaults to: nil)

    Flags to turn off/on metadata { :src => [true|false] :ftype => [true|false] :mode => [true|false] }

  • paths (Array) (defaults to: @config.local.content)

    Optional path list for content search

Returns:

  • (Hash)

    Strap directory structure metadata { 'stub_name' => { :src => 'relative/tree/file/path.erb', :ftype => 'File type as returned by File::Stat.new(file).ftype, EG "file", "directory"' :mode => 'File mode as returned by File::Stat.new(file).mode' } }



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/codestrap.rb', line 421

def (name=nil, options=nil, paths=@config.local.content)
  # TODO - rename
  codestraps   = {}
  options ||= {src: false, ftype: true, mode: true}
  paths.each do |path|
    full_path = File.expand_path path
    next unless File.directory? full_path
    Dir.chdir(full_path) do
      Dir.entries('.').each do |file|
        next if file =~ /^\.{1,2}$/
        next unless File.file? file
        next if name and not name.eql? File.basename(file, '.erb')
        mod                = File.basename(file, '.erb')
        stat               = File.stat file
        codestraps[mod]         = {}
        codestraps[mod][:src]   = File.expand_path(File.join(full_path, file)) if options[:src]
        codestraps[mod][:ftype] = stat.ftype if options[:ftype]
        codestraps[mod][:mode]  = sprintf('%o', stat.mode) if options[:mode]
      end
    end
  end
  codestraps
end