Class: Nyx

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

Constant Summary collapse

VERSION =
'1.3.3'

Instance Method Summary collapse

Instance Method Details

#check_interface_version(interface, source) ⇒ Object

def



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/nyx.rb', line 571

def check_interface_version(interface, source)
  nyxi = Nyx::VERSION.split '.'
  jsoni = interface.split '.'

  if jsoni[0] != nyxi[0]
    self.failed_version_check interface, source
  else # major versions are equal
    if jsoni[1] > nyxi[1]
      # ie. json requires extra features
      self.failed_version_check interface, source
    elsif jsoni[1] == nyxi[1] && jsoni[2] > nyxi[2]
      # ie. potential problems with bugfix'es
      self.failed_version_check interface, source
    end#if
  end#if
end

#compile(args) ⇒ Object

def



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/nyx.rb', line 185

def compile(args)
  if args.length != 0
    dirpath = args[0].sub(/(\/)+$/,'')+'/'
  else # no parameters, assume .
    dirpath = './'
  end#if

  if ! File.exist? dirpath
    self.fail 'Target directory does not exist.'
    return;
  end#if

  jsonconfigfile = dirpath+'nyx.json'
  if ! File.exist? jsonconfigfile
    self.fail 'Missing nyx.json file in target directory.'
    return;
  end#if

  conf = JSON.parse(open(jsonconfigfile).read)

  # ensure nyx.json interface isn't newer

  conf_interface = '1.0.0'
  if (conf != nil && conf.has_key?('interface'))
    conf_interface = conf['interface'];
  end#if

  self.check_interface_version(conf_interface, 'nyx.json');

  # core processing

  conf['cores'].each do |wpcoreconf|
    self.core dirpath, wpcoreconf
  end#each

  puts ""
  puts "  fin"
end

#compile_scripts(args = nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/nyx.rb', line 17

def compile_scripts(args = nil)

  # @todo CLEANUP properly read "silent" parameter

  if args != nil
    if args.length != 0
      dirpath = args[0].sub(/(\/)+$/,'')+'/'
      silent = false
    else # no parameters, assume .
      dirpath = './'
      silent = false
    end#if
  else # direct invokation
    dirpath = './'
    silent = false
  end#if

  dirpath = File.expand_path(dirpath) + '/'

  if ! File.exist? dirpath
    puts '  Err: target directory does not exist.'
    return;
  end#if

  conf = self.mjolnir_config(dirpath, '+scripts.php');

  self.do_cleanup_scripts dirpath, conf, silent

  self.ensure_closure_compiler(dirpath)

  puts
  puts " Recompiling..."
  puts " ----------------------------------------------------------------------- "
  conf = self.read_script_configuration(dirpath);
  self.recompile_scripts(conf, dirpath);
  puts " >>> all files regenarated "

end

#compile_style(args = nil) ⇒ Object

def



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

def compile_style(args = nil)

  # @todo CLEANUP properly read "silent" parameter

  if args != nil
    if args.length != 0
      dirpath = args[0].sub(/(\/)+$/,'')+'/'
      silent = false
    else # no parameters, assume .
      dirpath = './'
      silent = false
    end#if
  else # direct invokation
    dirpath = './'
    silent = false
  end#if

  if ! File.exist? dirpath
    puts '  Err: target directory does not exist.'
    return;
  end#if

  conf = self.mjolnir_config(dirpath, '+style.php');

  self.do_cleanup_style dirpath, conf, silent

  Kernel.exec('compass compile -c bin/etc/compass/production.rb --environment production')

end

#core(path, conf) ⇒ Object

Work methods



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
257
258
259
260
261
262
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
296
297
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
# File 'lib/nyx.rb', line 232

def core(path, conf)
  Dir.chdir path
  corepath = conf['path'].sub(/(\/)+$/, '')

  puts "  processing #{corepath}"
  # remove the core if it exists
  FileUtils.rm_rf corepath
  # clone a fresh copy
  puts "  cloning #{conf['repo']} -> #{conf['version']}"
  g = Git.clone conf['repo'], corepath
  g.checkout conf['version']
  FileUtils.rm_rf corepath+'/.git'

  # process "keep" rules
  if conf.has_key? 'keep'
    srcpath = File.expand_path(corepath)
    keep = conf['keep']
    filecount = Dir["#{srcpath}/**/*"].length
    fileidx = 0
    removed = 0
    print "   - keep: #{fileidx} files processed (#{removed} deleted)"
    Dir.glob("#{srcpath}/**/*", File::FNM_DOTMATCH) do |file|
      basename = File.basename(file)
      next if basename == '.' or basename == '..'
      fileidx += 1
      print (' ' * 256) + "\r"
      print "   - keep: #{fileidx} files processed (#{removed} deleted)"
      filepath = File.expand_path(file)
      filesubpath = filepath.sub(srcpath, '').gsub(/^\//, '')

      keepfile = false
      keep.each do |path|
        if filesubpath.start_with? path
          keepfile = true
          break
        end#if
      end#each

      if ! keepfile
        FileUtils.rm_rf filepath
        removed += 1
      end#if
    end#glob
    puts
  end#if

  # process "ensure" rules
  if conf.has_key? 'ensure'
    srcpath = File.expand_path(corepath) + '/'
    ensure_rules = conf['ensure']
    print "   - ensuring files"
    ensure_rules.each do |depfiles, srcfiles|
      depfilespath = srcpath + depfiles.sub(/\/$/, '') + '/'
      srcfilespath = srcfiles.sub(/\/$/, '')
      Dir.glob("#{depfilespath}**/*", File::FNM_DOTMATCH) do |file|
        # skip parent and self symbols
        basename = File.basename(file)
        next if basename == '.' or basename == '..'
        # compute file paths
        filepath = File.expand_path(file)
        filesubpath = filepath.sub(depfilespath, '')
        srcfile = srcfilespath + '/' + filesubpath
        # skip directories
        next if File.directory?(filepath)
        # progress info
        print (' ' * 256) + "\r"
        prettysubpath = filepath.sub(srcpath, '')
        print "   - ensure: #{prettysubpath}"
        # write missing file
        if ! File.exist?(srcfile)
          text = File.read filepath
          FileUtils.mkpath File.dirname(srcfile)
          File.write srcfile, text
        end#if
      end#glob
    end#each
    print (' ' * 256) + "\r"
    puts "   - ensure: all dependencies resolved"
  end#if

  # process "remove" rules
  if conf.has_key? 'remove'
    removed = 0
    srcpath = File.expand_path(corepath) + '/'
    conf['remove'].each do |file|
      filepath = srcpath + file
      if File.exist? filepath
        removed += 1
        FileUtils.rm_rf filepath
      end#if
    end#each
    files_tr = removed != 1 ? 'files' : 'file';
    puts "   - remove: #{removed} #{files_tr} deleted"
  end#if

end

#do_cleanup_scripts(dirpath, conf, silent) ⇒ Object

def



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/nyx.rb', line 329

def do_cleanup_scripts(dirpath, conf, silent)
  if ( ! silent)
    puts
  end#if

  basedir = dirpath.gsub /\/$/, ''

  # cleanup config
  conf['root'].gsub! /[\/\\]$/, ''
  conf['sources'].gsub! /[\/\\]$/, ''

  rootdir = basedir+'/'+conf['root'];

  self.purge_dir(rootdir)

  # copy all files to the root
  srcdir = basedir+'/'+conf['sources'];

  Dir["#{srcdir}/**/*"].each do |file|
    if (file.to_s.gsub(srcdir.to_s, '') !~ /\/(test|tests|docs|demos|examples|demo|example)(\/|$)/)
      if file !~ /^\..*$/ && file !~ /^.*\.(js|json)$/ &&
        rootfile = rootdir + (file.gsub srcdir, '')
        # check if file is non-empty directory
        if File.directory?(file) && ! (Dir.entries(file) - %w[ . .. ]).empty?
          if ( ! silent)
            puts "   moving  #{file.gsub(basedir, '')} => #{rootfile.gsub(basedir, '')}"
          end#if
          FileUtils.cp_r(file, rootfile)
        else # file
          if ( ! silent)
            puts "   moving  #{file.gsub(basedir, '')} => #{rootfile.gsub(basedir, '')}"
          end#if
          FileUtils.cp(file, rootfile)
        end#if
      end#if
    end#if
  end#each

  if ( ! silent)
    puts
  end#if
end

#do_cleanup_style(dirpath, conf, silent) ⇒ Object

def



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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/nyx.rb', line 372

def do_cleanup_style(dirpath, conf, silent)
  if ( ! silent)
    puts
  end#if

  basedir = File.expand_path(dirpath)

  # cleanup config
  conf['root'].gsub! /[\/\\]$/, ''
  conf['sources'].gsub! /[\/\\]$/, ''

  rootdir = basedir + '/' + conf['root'];

  self.purge_dir(rootdir)

  # copy all non .scss files to the root; compass only copies images/
  srcdir = basedir + '/' + conf['sources'];

  Dir["#{srcdir}/**/*"].each do |file|
    if (file.to_s.gsub(srcdir.to_s, '') !~ /\/(jquery|test|tests|docs|js|javascript|less|demos|examples|demo|example)(\/|$)/)
      if file !~ /^\..*$/ && file !~ /^.*\.(scss|sass|json|md)$/
        rootfile = rootdir + (file.gsub srcdir, '')
        # check if file is non-empty directory
        if File.directory?(file) && ! (Dir.entries(file) - %w[ . .. ]).empty?
          if ( ! silent)
            puts "   moving  #{file.gsub(basedir, '')} => #{rootfile.gsub(basedir, '')}"
          end#if
          if ! File.exist? rootfile
            begin
              # FileUtils.cp_r(file, rootfile)
              FileUtils.mkdir(rootfile)
            rescue
              puts "    failed to copy directory!"
            end#rescue
          end#if
        elsif ! File.directory?(file)
          if ( ! silent)
            puts "   moving  #{file.gsub(basedir, '')} => #{rootfile.gsub(basedir, '')}"
          end#if
          begin
            FileUtils.cp(file, rootfile)
          rescue
            puts "    failed to copy file!"
          end#rescue
        end#if
      end#if
    end#if
  end#each

  if ( ! silent)
    puts
  end#if
end

#download(domain, file, to) ⇒ Object

Helpers



518
519
520
521
522
523
524
525
# File 'lib/nyx.rb', line 518

def download(domain, file, to)
  Net::HTTP.start(domain) do |http|
    resp = http.get(file)
    open(to, "wb") do |file|
      file.write(resp.body)
    end#open
  end#http.start
end

#ensure_closure_compiler(basedir) ⇒ Object

def



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/nyx.rb', line 426

def ensure_closure_compiler(basedir)
  # ensure closure compiler jar is present
  tmpdir = basedir.gsub(/[\/\\]$/, '') + '/bin/tmp'
  if ! File.exists? tmpdir + '/compiler.jar'
    Dir.chdir tmpdir
    if ! File.exists? tmpdir+"/closure.zip"
      download("closure-compiler.googlecode.com", "/files/compiler-latest.zip", tmpdir+"/closure.zip")
    end
    Zip::ZipFile.open(tmpdir+"/closure.zip") do |zipfile|
      zipfile.each do |file|
        if file.name == 'compiler.jar'
          puts "extracting #{file}"
          zipfile.extract(file.name, tmpdir + '/compiler.jar')
        end#if
      end#each
    end#open
  end#def
  Dir.chdir basedir
end

#fail(msg) ⇒ Object

def



592
593
594
# File 'lib/nyx.rb', line 592

def fail(msg)
  puts "  Err: #{msg}"
end

#failed_version_check(interface, source) ⇒ Object

def



588
589
590
# File 'lib/nyx.rb', line 588

def failed_version_check(interface, source)
  self.fail "Incompatible versions: #{source} @ #{interface} but nyx.gem @ #{Nyx::VERSION}"
end

#locate_up(path, filename) ⇒ Object

def



542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/nyx.rb', line 542

def locate_up(path, filename)
  if File.exist?(path + filename)
    return path + filename
  else # didnt find file
    parent = File.expand_path(path + '..').sub /\/$/, ''
    rawfilepath = parent.sub /^[a-zA-Z]:/, ''
    if rawfilepath.length != 0
      return self.locate_up(parent + '/', filename)
    else # file system root
      return nil # failed to find file
    end#if
  end#if
end

#mjolnir_config(path, configname) ⇒ Object

def



527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/nyx.rb', line 527

def mjolnir_config(path, configname)
  # located mjolnir.php or etc/mjolnir.php
  bootstrap_path = self.locate_up(path, 'etc/mjolnir.php')
  if bootstrap_path == nil
    bootstrap_path = self.locate_up(path, 'mjolnir.php')
  end#if

  if bootstrap_path == nil
    self.fail 'Failed to locate mjolnir bootstrap file.'
  end#if

  json_config = `php -r "chdir('#{path}'); require '#{bootstrap_path}'; echo json_encode(include '#{configname}');"`
  return JSON.parse json_config
end

#process_scripts(r, conf) ⇒ Object

def



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/nyx.rb', line 470

def process_scripts(r, conf)

  if r.eql? '+scripts.php'
    puts ' >>> recompiling all...'
    # reload confuration
    conf = self.read_script_configuration(dirpath);
    if conf['mode'] == 'complete'
      self.regenerate_scripts('master', conf['complete-mapping'])
    else # non-complete mode
      # regenerate all
      conf['targeted-mapping'].each do |key, files|
        self.regenerate_scripts(key, files)
      end#each
    end#if
  end

  if conf['mode'] == 'complete'

    conf['complete-mapping'].each do |file|
      if file.eql? r
        puts " >>> recompiling [complete-script]"
        # regenerate the closure
        self.recompile_scripts(conf, dirpath)
        break;
      end#if
    end#each

  else # non-complete mode

    # search configuration for file
    conf['targeted-mapping'].each do |key, files|
      files.each do |file|
        if file.eql? r
          puts " >>> recompiling [#{key}]"
          # regenerate the closure
          self.regenerate_scripts(key, files);
        end#if
      end#each
    end#each

  end#if

end

#purge_dir(directory) ⇒ Object

remove all non dot files



557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/nyx.rb', line 557

def purge_dir(directory)
  Dir["#{directory}/*"].each do |file|
    next if file == '.' || file == '..'
    if File.directory? file
      self.purge_dir(File.expand_path(file))
      if (Dir.entries(file) - %w[ . .. ]).empty?
        Dir.rmdir file
      end#if
    elsif file !~ /^\..*$/ # ignore dot files
      FileUtils.rm_rf file, :noop => false, :verbose => false
    end#if
  end#each
end

#read_script_configuration(dirpath) ⇒ Object

def



56
57
58
59
60
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
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
116
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
145
# File 'lib/nyx.rb', line 56

def read_script_configuration(dirpath)
  conf = self.mjolnir_config(dirpath, '+scripts.php');

  # normalize targeted common
  if ! conf['targeted-common'].is_a?(Array)
    temp = [];
    conf['targeted-common'].each do |key, file|
      temp.push(file)
    end#each
    conf['targeted-common'] = temp;
  end#if

  # normalize targeted mapping
  conf['targeted-mapping'].each do |key, files|
    if ! files.is_a?(Array) && ! files.is_a?(String)
      temp = [];
      files.each do |key, file|
        temp.push(file)
      end#each
      conf['targeted-mapping'][key] = temp;
    end#if
  end#each

  if conf['targeted-common'] == nil
    conf['targeted-common'] = [];
  else # not nil
    conf['targeted-common'] = conf['targeted-common'].find_all do |item|
      item !~ /(^[a-z]+:\/\/|^\/\/).*$/
    end#find_all
  end#def

  # remove aliased keys
  conf['targeted-mapping'].each do |key, files|
    if files.is_a? String
      conf['targeted-mapping'].delete(key);
    end#if
  end#each

  # include common files
  conf['targeted-mapping'].each do |key, files|
    files = files.find_all do |item|
      item !~ /(^[a-z]+:\/\/|^\/\/).*$/
    end#find_all
    conf['targeted-mapping'][key] = conf['targeted-common'].clone;
    files.each do |file|
      if ( ! conf['targeted-mapping'][key].include?(file))
        conf['targeted-mapping'][key].push(file)
      end#if
    end#each
  end#each

  # convert to paths
  conf['targeted-mapping'].each do |key, files|
    files = files.find_all do |item|
      item !~ /(^[a-z]+:\/\/|^\/\/).*$/
    end#find_all
    cleaned_files = []
    files.each do |value|
      if value.kind_of? Array
        cleaned_files.push value[1]
      else # not array
        cleaned_files.push value
      end#if
    end#each
    cleaned_files.collect! do |file|
      'src/'+file+'.js';
    end#collect
    conf['targeted-mapping'][key] = cleaned_files
  end#each

  # convert to paths
  files = conf['complete-mapping']
  files = files.find_all do |item|
    item !~ /(^[a-z]+:\/\/|^\/\/).*$/
  end#find_all
  cleaned_files = []
  files.each do |key, value|
    if value.kind_of? Array
      cleaned_files.push value[1]
    else # not array
      cleaned_files.push value
    end#if
  end#each
  cleaned_files.collect! do |file|
    'src/'+file+'.js';
  end#collect
  conf['complete-mapping'] = cleaned_files

  return conf
end

#recompile_scripts(conf, dirpath) ⇒ Object

def



446
447
448
449
450
451
452
453
454
# File 'lib/nyx.rb', line 446

def recompile_scripts(conf, dirpath)
  if (conf['mode'] == 'complete')
    self.regenerate_scripts('master', conf['complete-mapping'], conf)
  else # targeted mode
    conf['targeted-mapping'].each do |key, files|
      self.regenerate_scripts(key, files, conf)
    end#each
  end#if
end

#regenerate_scripts(key, files, conf) ⇒ Object

def



456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/nyx.rb', line 456

def regenerate_scripts(key, files, conf)
  if conf['closure.flags'] != nil
    compiler_options = conf['closure.flags'].join ' '
  else # no flags
    compiler_options = ''
  end#if

  rootdir = conf['root'];
  if files.size > 0
    puts " compiling #{key}"
    `java -jar bin/tmp/compiler.jar #{compiler_options} --js #{files.join(' ')} --js_output_file ./#{rootdir}#{key}.min.js --create_source_map ./#{rootdir}#{key}.min.js.map --source_map_format=V3`;
  end
end

#version(args) ⇒ Object

def



224
225
226
# File 'lib/nyx.rb', line 224

def version(args)
  puts "  #{Nyx::VERSION}"
end

#watch_scripts(args = nil) ⇒ Object

def



147
148
149
# File 'lib/nyx.rb', line 147

def watch_scripts(args = nil)
  puts "  todo: watch scripts code"
end

#watch_style(path = nil) ⇒ Object

def



181
182
183
# File 'lib/nyx.rb', line 181

def watch_style(path = nil)
  puts "  todo: watch scripts code"
end