ratchetcat-commander 0.0.4

Sign up to get free protection for your applications and to get access to all the features.
data/History.txt ADDED
@@ -0,0 +1,3 @@
1
+ == 1.0.1 2008-09-09
2
+
3
+ * Initial release
data/License.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 FIXME full name
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Manifest.txt ADDED
@@ -0,0 +1,26 @@
1
+ History.txt
2
+ License.txt
3
+ Manifest.txt
4
+ PostInstall.txt
5
+ README.txt
6
+ Rakefile
7
+ commander.gemspec
8
+ config/hoe.rb
9
+ config/requirements.rb
10
+ lib/commander.rb
11
+ script/console
12
+ script/destroy
13
+ script/generate
14
+ script/txt2html
15
+ setup.rb
16
+ tasks/deployment.rake
17
+ tasks/environment.rake
18
+ tasks/website.rake
19
+ test/test_commander.rb
20
+ test/test_github_environment.rb
21
+ test/test_helper.rb
22
+ website/index.html
23
+ website/index.txt
24
+ website/javascripts/rounded_corners_lite.inc.js
25
+ website/stylesheets/screen.css
26
+ website/template.html.erb
data/PostInstall.txt ADDED
File without changes
data/README.txt ADDED
@@ -0,0 +1,84 @@
1
+ = Commander
2
+
3
+ == DESCRIPTION:
4
+
5
+ Commander combines the execution of system commands with logging.
6
+
7
+ == FEATURES/PROBLEMS:
8
+
9
+ * Supports single or batched commands
10
+ * Provides exit status after command is run.
11
+ * Extends logger to capture output from STDOUT or STDERR, and flag errors
12
+
13
+ Commander uses the open4 gem and the ruby logger to accomplish these tasks.
14
+
15
+ == SYNOPSIS:
16
+
17
+ Commander was originally intended for use in rake tasks launching multiple system commands. Program flow was varied based on the exit status or source of the output from these commands and Commander includes some convenience methods for handling such situations.
18
+
19
+ Setup:
20
+
21
+ log = Logger.new( STDOUT )
22
+ log.level = Logger::Warn
23
+ c = Commander.new( log )
24
+
25
+ Commander accepts single commands:
26
+
27
+ c = Commander.new( log )
28
+ c.run( "df -h" )
29
+
30
+ Alternatively, you may add commands to an array for batch execution:
31
+
32
+ c = Commander.new( log )
33
+ c.commands << "df -h"
34
+ c.commands << "ls -ltrh"
35
+ c.run_commands()
36
+
37
+ Exit status of a single command is trivial to check (thanks to the open4 gem):
38
+
39
+ c = Commander.new( log )
40
+ c.run( "df -h" )
41
+ p c.exit_status #=> 0
42
+
43
+ Commander adds a buffer to the ruby logger, which allows us to perform a simple check for errors over the whole log:
44
+
45
+ c = Commander.new( log )
46
+ c.run( "df -h" )
47
+ p c.errors? #=> false
48
+
49
+ =Note
50
+
51
+ Please note: You must initialize Commander with a reference to a Logger object. Additionally, Commander requires the {Open4}[http://www.codeforpeople.com/lib/ruby/open4/] gem (by Ara T. Howard).
52
+
53
+ == REQUIREMENTS:
54
+
55
+ {Open4}[http://www.codeforpeople.com/lib/ruby/open4/]
56
+
57
+ == INSTALL:
58
+
59
+ <tt>sudo gem install commander</tt>
60
+
61
+ == LICENSE:
62
+
63
+ (The MIT License)
64
+
65
+ Copyright (c) 2008 Jon Fuller
66
+
67
+ Permission is hereby granted, free of charge, to any person obtaining
68
+ a copy of this software and associated documentation files (the
69
+ 'Software'), to deal in the Software without restriction, including
70
+ without limitation the rights to use, copy, modify, merge, publish,
71
+ distribute, sublicense, and/or sell copies of the Software, and to
72
+ permit persons to whom the Software is furnished to do so, subject to
73
+ the following conditions:
74
+
75
+ The above copyright notice and this permission notice shall be
76
+ included in all copies or substantial portions of the Software.
77
+
78
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
79
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
80
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
81
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
82
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
83
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
84
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ require 'config/requirements'
2
+ require 'config/hoe' # setup Hoe + all gem configuration
3
+
4
+ Dir['tasks/**/*.rake'].each { |rake| load rake }
data/config/hoe.rb ADDED
@@ -0,0 +1,73 @@
1
+ require 'commander'
2
+
3
+ AUTHOR = 'Jon Fuller' # can also be an array of Authors
4
+ EMAIL = "ratchetcat+github@gmail.com"
5
+ DESCRIPTION = "Commander combines the execution of system commands with logging."
6
+ GEM_NAME = 'commander' # what ppl will type to install your gem
7
+ RUBYFORGE_PROJECT = 'commander' # The unix name for your project
8
+ HOMEPATH = "http://github.com/ratchetcat/commander"
9
+ DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
10
+ EXTRA_DEPENDENCIES = [
11
+ ['open4', '>= 0.9.6']
12
+ # ['activesupport', '>= 1.3.1']
13
+ ] # An array of rubygem dependencies [name, version]
14
+ @config_file = "~/.rubyforge/user-config.yml"
15
+ @config = nil
16
+ RUBYFORGE_USERNAME = "unknown"
17
+ def rubyforge_username
18
+ unless @config
19
+ begin
20
+ @config = YAML.load(File.read(File.expand_path(@config_file)))
21
+ rescue
22
+ puts <<-EOS
23
+ ERROR: No rubyforge config file found: #{@config_file}
24
+ Run 'rubyforge setup' to prepare your env for access to Rubyforge
25
+ - See http://newgem.rubyforge.org/rubyforge.html for more details
26
+ EOS
27
+ exit
28
+ end
29
+ end
30
+ RUBYFORGE_USERNAME.replace @config["username"]
31
+ end
32
+
33
+
34
+ REV = nil
35
+ # UNCOMMENT IF REQUIRED:
36
+ # REV = YAML.load(`svn info`)['Revision']
37
+ VERS = Commander::VERSION::STRING + (REV ? ".#{REV}" : "")
38
+ RDOC_OPTS = ['--quiet', '--title', 'commander documentation',
39
+ "--opname", "index.html",
40
+ "--line-numbers",
41
+ "--main", "README",
42
+ "--inline-source"]
43
+
44
+ class Hoe
45
+ def extra_deps
46
+ @extra_deps.reject! { |x| Array(x).first == 'hoe' }
47
+ @extra_deps
48
+ end
49
+ end
50
+
51
+ # Generate all the Rake tasks
52
+ # Run 'rake -T' to see list of generated tasks (from gem root directory)
53
+ $hoe = Hoe.new(GEM_NAME, VERS) do |p|
54
+ p.developer(AUTHOR, EMAIL)
55
+ p.description = DESCRIPTION
56
+ p.summary = DESCRIPTION
57
+ p.url = HOMEPATH
58
+ p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
59
+ p.test_globs = ["test/**/test_*.rb"]
60
+ p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean.
61
+
62
+ # == Optional
63
+ p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
64
+ #p.extra_deps = EXTRA_DEPENDENCIES
65
+
66
+ #p.spec_extras = {} # A hash of extra values to set in the gemspec.
67
+ end
68
+
69
+ CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
70
+ PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
71
+ $hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc')
72
+ $hoe.rsync_args = '-av --delete --ignore-errors'
73
+ $hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue ""
@@ -0,0 +1,15 @@
1
+ require 'fileutils'
2
+ include FileUtils
3
+
4
+ require 'rubygems'
5
+ %w[rake hoe newgem rubigen].each do |req_gem|
6
+ begin
7
+ require req_gem
8
+ rescue LoadError
9
+ puts "This Rakefile requires the '#{req_gem}' RubyGem."
10
+ puts "Installation: gem install #{req_gem} -y"
11
+ exit
12
+ end
13
+ end
14
+
15
+ $:.unshift(File.join(File.dirname(__FILE__), %w[.. lib]))
data/lib/commander.rb ADDED
@@ -0,0 +1,116 @@
1
+ $:.unshift(File.dirname(__FILE__)) unless
2
+ $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
3
+
4
+ require 'rubygems'
5
+ require 'open4'
6
+ require 'logger'
7
+
8
+ class Commander
9
+
10
+ module VERSION #:nodoc:
11
+ MAJOR = 0
12
+ MINOR = 0
13
+ TINY = 4
14
+
15
+ STRING = [MAJOR, MINOR, TINY].join('.')
16
+ end
17
+
18
+ # The LoggerBuffer module extends the standard logger with a buffer -- useful for tracking error conditions.
19
+ module LoggerBuffer
20
+ attr_accessor :buffer
21
+
22
+ def self.extended( base )
23
+ base.instance_eval 'alias :_add :add'
24
+ base.extend( Commander::LoggerBuffer::Methods )
25
+ base.instance_variable_set( "@buffer", [] )
26
+ end
27
+
28
+ module Methods
29
+ def add(severity, message = nil, progname = nil, &block)
30
+ severity ||= UNKNOWN
31
+ if @logdev.nil? or severity < @level
32
+ return true
33
+ end
34
+ progname ||= @progname
35
+ if message.nil?
36
+ if block_given?
37
+ message = yield
38
+ else
39
+ message = progname
40
+ progname = @progname
41
+ end
42
+ end
43
+
44
+ msg = format_message(format_severity(severity), Time.now, progname, message)
45
+ @buffer << msg
46
+ @logdev.write(msg)
47
+ true
48
+ end
49
+ end
50
+ end
51
+
52
+ attr_accessor :commands, :exit_status, :log
53
+
54
+ def initialize( logger )
55
+ raise ArgumentError.new("A reference to a valid logger must be provided.") if logger.nil? || !logger.respond_to?(:info) || !logger.respond_to?(:error)
56
+ @log = logger
57
+ @log.extend( Commander::LoggerBuffer )
58
+
59
+ @exit_status = 0
60
+ @commands = []
61
+ end
62
+
63
+ # run a single command
64
+ # set override to true in order to suppress warnings from STDERR
65
+ def run( cmd, override = false )
66
+ @log.info "Command: #{ cmd }"
67
+
68
+ # switched to popen4 for support of exitstatus and ease-of-use
69
+ begin
70
+ pid, stdin, stdout, stderr = Open4::popen4 cmd
71
+ ignored, status = Process::waitpid2 pid
72
+
73
+ stdout_array = stdout.readlines
74
+ stderr_array = stderr.readlines
75
+ rescue Exception => err
76
+ # set status.exitstatus to 1 due to failure
77
+ status = Object.new()
78
+ status.instance_eval do
79
+ def exitstatus
80
+ 1
81
+ end
82
+ end
83
+
84
+ stdout_array = []
85
+ stderr_array = [ err ]
86
+ end
87
+
88
+ stdout_array.each do | line |
89
+ @log.info line
90
+ end
91
+
92
+ stderr_array.each do | line |
93
+ if override
94
+ @log.info line
95
+ else
96
+ @log.error line
97
+ end
98
+ end
99
+
100
+ @exit_status = status.exitstatus
101
+ end
102
+
103
+ # run commands in commands array sequentially
104
+ def run_commands()
105
+ @commands.each do | command |
106
+ self.run( command )
107
+ end
108
+ end
109
+
110
+ # returns true if logging facility has recorded warnings
111
+ def errors?
112
+ return true if @log.buffer.join().match(/WARN|ERROR|FATAL|UNKNOWN/i)
113
+ return false
114
+ end
115
+
116
+ end
data/script/console ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env ruby
2
+ # File: script/console
3
+ irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
4
+
5
+ libs = " -r irb/completion"
6
+ # Perhaps use a console_lib to store any extra methods I may want available in the cosole
7
+ # libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}"
8
+ libs << " -r #{File.dirname(__FILE__) + '/../lib/commander.rb'}"
9
+ puts "Loading commander gem"
10
+ exec "#{irb} #{libs} --simple-prompt"
data/script/destroy ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+ APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
3
+
4
+ begin
5
+ require 'rubigen'
6
+ rescue LoadError
7
+ require 'rubygems'
8
+ require 'rubigen'
9
+ end
10
+ require 'rubigen/scripts/destroy'
11
+
12
+ ARGV.shift if ['--help', '-h'].include?(ARGV[0])
13
+ RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit]
14
+ RubiGen::Scripts::Destroy.new.run(ARGV)
data/script/generate ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+ APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
3
+
4
+ begin
5
+ require 'rubigen'
6
+ rescue LoadError
7
+ require 'rubygems'
8
+ require 'rubigen'
9
+ end
10
+ require 'rubigen/scripts/generate'
11
+
12
+ ARGV.shift if ['--help', '-h'].include?(ARGV[0])
13
+ RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit]
14
+ RubiGen::Scripts::Generate.new.run(ARGV)
data/script/txt2html ADDED
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ GEM_NAME = 'commander' # what ppl will type to install your gem
4
+ RUBYFORGE_PROJECT = 'commander'
5
+
6
+ require 'rubygems'
7
+ begin
8
+ require 'newgem'
9
+ require 'rubyforge'
10
+ rescue LoadError
11
+ puts "\n\nGenerating the website requires the newgem RubyGem"
12
+ puts "Install: gem install newgem\n\n"
13
+ exit(1)
14
+ end
15
+ require 'redcloth'
16
+ require 'syntax/convertors/html'
17
+ require 'erb'
18
+ require File.dirname(__FILE__) + "/../lib/#{GEM_NAME}/version.rb"
19
+
20
+ version = Commander::VERSION::STRING
21
+ download = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
22
+
23
+ def rubyforge_project_id
24
+ RubyForge.new.autoconfig["group_ids"][RUBYFORGE_PROJECT]
25
+ end
26
+
27
+ class Fixnum
28
+ def ordinal
29
+ # teens
30
+ return 'th' if (10..19).include?(self % 100)
31
+ # others
32
+ case self % 10
33
+ when 1: return 'st'
34
+ when 2: return 'nd'
35
+ when 3: return 'rd'
36
+ else return 'th'
37
+ end
38
+ end
39
+ end
40
+
41
+ class Time
42
+ def pretty
43
+ return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}"
44
+ end
45
+ end
46
+
47
+ def convert_syntax(syntax, source)
48
+ return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'')
49
+ end
50
+
51
+ if ARGV.length >= 1
52
+ src, template = ARGV
53
+ template ||= File.join(File.dirname(__FILE__), '/../website/template.html.erb')
54
+ else
55
+ puts("Usage: #{File.split($0).last} source.txt [template.html.erb] > output.html")
56
+ exit!
57
+ end
58
+
59
+ template = ERB.new(File.open(template).read)
60
+
61
+ title = nil
62
+ body = nil
63
+ File.open(src) do |fsrc|
64
+ title_text = fsrc.readline
65
+ body_text_template = fsrc.read
66
+ body_text = ERB.new(body_text_template).result(binding)
67
+ syntax_items = []
68
+ body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){
69
+ ident = syntax_items.length
70
+ element, syntax, source = $1, $2, $3
71
+ syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>"
72
+ "syntax-temp-#{ident}"
73
+ }
74
+ title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip
75
+ body = RedCloth.new(body_text).to_html
76
+ body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] }
77
+ end
78
+ stat = File.stat(src)
79
+ created = stat.ctime
80
+ modified = stat.mtime
81
+
82
+ $stdout << template.result(binding)