forked from mislav/dotfiles
/
sake
602 lines (571 loc) · 20 KB
/
sake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
55
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
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
183
184
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
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
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
328
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
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
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
desc 'Install the plugin in vendor/plugins/will_paginate'
task 'will_paginate:install' do
require("fileutils")
wp_dir = "vendor/plugins/will_paginate"
begin
FileUtils.mkdir(wp_dir)
rescue Errno::EEXIST
$stderr.puts("#{wp_dir} already exists: updating ...")
end
url = "http://github.com/mislav/will_paginate/tarball/master"
system("wget -nv #{url} -O- | tar xzv -C #{wp_dir} --strip 1")
end
desc 'Add an external project as a sub-tree'
task 'git:subtree:add' do
require("readline")
name = (print("Remote Name? ")
Readline.readline.chomp)
url = (print("Git Repo Url? ")
Readline.readline.chomp)
`git remote add #{name} #{url}`
`git config remote.#{name}.fetch refs/heads/*:refs/remotes/#{name}/*`
`git config --add remote.#{name}.fetch refs/tags/*:refs/remotes/#{name}/tags/*`
`git config remote.#{name}.tagopt --no-tags`
`git fetch #{name}`
end
desc 'Merge a sub-tree into your project'
task 'git:subtree:merge' do
require("readline")
name = (print("Remote Name? ")
Readline.readline.chomp)
branch = (print("Remote Branch? ")
Readline.readline.chomp)
dest = (print("Destination? ")
Readline.readline.chomp)
`git merge -s ours --no-commit #{name}/#{branch}`
`git read-tree --prefix=#{dest} -u #{name}/#{branch}`
`git commit -m \"Merge branch '#{branch}' of #{name}\"`
end
desc 'Pull (fetch & merge) into an existing sub-tree'
task 'git:subtree:pull' do
require("readline")
name = (print("Remote Name? ")
Readline.readline.chomp)
branch = (print("Remote Branch? ")
Readline.readline.chomp)
`git pull -s subtree #{name} #{branch}`
end
desc 'Find all .erb or .rhtml files in the current directory tree and report any syntax errors'
task 'check:erb' do
require("erb")
require("open3")
(Dir["**/*.erb"] + Dir["**/*.rhtml"]).each do |file|
next if file.match("vendor/rails")
Open3.popen3("ruby -c") do |stdin, stdout, stderr|
stdin.puts(ERB.new(File.read(file), nil, "-").src)
stdin.close
error = stderr.readline rescue false
if error then
puts("#{file}:#{(error.match(/on line (\d+)/)[1] + ":") rescue nil} #{error}")
end
puts(error) if error
begin
stdout.close
rescue
false
end
begin
stderr.close
rescue
false
end
end
end
end
desc 'Find all .rb files in the current directory tree and report any syntax errors'
task 'check:ruby' do
require("open3")
Dir["**/*.rb"].each do |file|
next if file.match("vendor/rails")
next if file.match("vendor/plugins/.*/generators/.*/templates")
Open3.popen3("ruby -c #{file}") do |stdin, stdout, stderr|
error = stderr.readline rescue false
if error then
puts("#{file}:#{(error.match(/on line (\d+)/)[1] + ":") rescue nil} #{error}")
end
begin
stdin.close
rescue
false
end
begin
stdout.close
rescue
false
end
begin
stderr.close
rescue
false
end
end
end
end
desc 'Find all .yml files in the current directory tree and report any syntax errors'
task 'check:yaml' do
require("yaml")
Dir["**/*.yml"].each do |file|
next if file.match("vendor/rails")
begin
YAML.load_file(file)
rescue => e
puts("#{file}:#{(e.message.match(/on line (\d+)/)[1] + ":") rescue nil} #{e.message}")
end
end
end
desc 'Builds and installs a gem within its source; uses \'rake install[_gem]\' or the gemspec'
task 'gem:install' do
install_tasks = `rake -T | grep \"^rake install\" | sed -e \"s/#.*//\" | sed -e \"s/^rake //\"`.split("\n")
if (install_tasks.size > 0) then
task = install_tasks.first.strip
puts("Running 'rake #{task}'...")
sh("rake #{task}")
exit
end
if gemspec = Dir["*.gemspec"].first then
puts("Building #{gemspec}")
sh("gem build #{gemspec}")
gem = `ls -t *.gem`.split("\n").first
puts("Installing #{gem}")
sh("sudo gem install #{gem}")
end
end
desc 'View GEM=gemname'
task 'gem:view' do
unless gems = ENV["GEM"] then
puts(" Usage:\n sake gems:view GEM=gemname\n".gsub(/ /, ""))
end
begin
(require("rubygems")
require("optparse"))
rescue LoadError
abort("There was a problem loading rubygems, optparse")
end
class ViewGem
attr_reader(:name)
def initialize(name)
@name = name
validate!
end
def requirement
(@requirement or Gem::Requirement.new(">= 0.0.0"))
end
def run
path ? (open) : (abort("Could not find #{name} #{requirement}"))
end
def open
system("#{editor} '#{path}'")
end
private
def validate!
abort("ERROR: Must provide gem name.\n---\n#{parser}") unless name
end
def path
@path ||= Gem.source_index.find_name(name, requirement).last.full_gem_path
rescue
nil
end
def parser
OptionParser.new do |opts|
opts.banner = "viewgem NAME [OPTIONS]\nOPTIONS:"
opts.on("-v VERSION", "--version", "Specify gem version") do |raw_req|
@requirement = Gem::Requirement.new(raw_req)
end
opts.on_tail("-h", "--help", "Show this message") { abort(opts.to_s) }
end
end
def editor
env_editor = (ENV["VIEWGEM_EDITOR"] or ENV["EDITOR"])
return env_editor if env_editor
case RUBY_PLATFORM
when /darwin/ then
"mate"
else
"vi"
end
end
end
ViewGem.new(ENV["GEM"]).run
end
desc 'Flog the most commonly revised files in the git history'
task 'git:analyze:commits:flog_frequent' do
counts = Hash.new(0)
IO.popen("PAGER=cat git log --name-only --pretty=oneline 2>&1") do |pipe|
until pipe.eof do
(line = pipe.readline
next unless line =~ /^(app|lib).*\.rb$/
counts[line.chomp] += 1)
end
end
counts.sort_by { |item| item.last }.reverse.first(15).each do |item|
flog_score = `flog -s #{item.first}`.to_f.round
puts("#{item.first} (in #{item.last} commits) (Flog: #{flog_score})")
end
end
desc 'Ignore build and user-specific files in Xcode projects.'
task 'git:ignore:xcode' do
xcode_ignores = (["build", "*.xcodeproj/*", "!*.xcodeproj/project.pbxproj"].join("\n") + "\n")
File.open(".gitignore", "a+") do |gitignore|
gitignore.rewind
current_ignores = gitignore.read
(gitignore << xcode_ignores) unless current_ignores.include?(xcode_ignores)
end
end
desc 'Install man pages for current git version'
task 'git:manpages:install' do
unless git_version = `git --version`.scan(/[\d.]+/)[0] then
puts("Git not installed or 'git --version' not returning format 'git version A.B.C.D'")
exit
end
puts("Installing manpages for git #{git_version}")
require("fileutils")
FileUtils.mkdir_p("/usr/local/share/man")
FileUtils.chdir("/tmp") do
puts("Downloading and unpacking manpages in #{`pwd`}")
`curl -O \"http://kernel.org/pub/software/scm/git/git-manpages-#{git_version}.tar.bz2\"`
puts(`sudo tar xjv -C /usr/local/share/man -f git-manpages-#{git_version}.tar.bz2`)
end
puts("Test your git manpages by trying the command: man git")
end
desc 'Push all changes to the SVN repository'
task 'git:publish' do
branch = `git branch | grep \"*\"`.strip[(2..-1)]
if (branch == "master") then
switch = false
else
`git diff-files --quiet`
if ($?.exitstatus == 1) then
puts("You have outstanding changes. Please commit them first.")
exit(1)
end
puts("* Merging topic '#{branch}' back into master...")
`git checkout master`
sh("git merge #{branch}")
switch = true
end
puts("* Pushing changes...")
sh("git svn dcommit")
if switch then
puts("* Switching back to #{branch}...")
`git checkout #{branch}`
end
end
desc 'Pull new commits from the repository'
task 'git:pull' do
puts("* Pulling in new commits...")
sh("git fetch")
`git diff-files --quiet`
if ($?.exitstatus == 1) then
stash = true
clear = (`git stash list`.scan("\n").size == 0)
puts("* Saving changes...")
`git stash save`
else
stash = false
end
branch = `git branch | grep \"*\"`.strip[(2..-1)]
if (branch == "master") then
switch = false
else
switch = true
`git checkout master`
puts("* Switching back to master...")
end
puts("* Applying new commits...")
sh("git rebase origin")
if switch then
puts("* Porting changes into #{branch}...")
`git checkout #{branch}`
sh("git rebase master")
end
if stash then
puts("* Applying changes...")
sh("git stash apply")
`git stash clear` if clear
end
end
desc 'Push all changes to the repository'
task 'git:push' do
branch = `git branch | grep \"*\"`.strip[(2..-1)]
if (branch == "master") then
switch = false
else
`git diff-files --quiet`
if ($?.exitstatus == 1) then
puts("You have outstanding changes. Please commit them first.")
exit(1)
end
puts("* Merging topic '#{branch}' back into master...")
`git checkout master`
sh("git merge #{branch}")
switch = true
end
puts("* Pushing changes...")
sh("git push")
if switch then
puts("* Switching back to #{branch}...")
`git checkout #{branch}`
end
end
desc 'Pull new commits from the SVN repository'
task 'git:rebase' do
`git diff-files --quiet`
if ($?.exitstatus == 1) then
stash = true
clear = (`git stash list`.scan("\n").size == 0)
puts("* Saving changes...")
`git stash save`
else
stash = false
end
branch = `git branch | grep \"*\"`.strip[(2..-1)]
if (branch == "master") then
switch = false
else
switch = true
`git checkout master`
puts("* Switching back to master...")
end
puts("* Pulling in new commits...")
sh("git svn fetch")
sh("git rebase trunk")
if switch then
puts("* Porting changes into #{branch}...")
`git checkout #{branch}`
sh("git rebase master")
end
if stash then
puts("* Applying changes...")
sh("git stash apply")
`git stash clear` if clear
end
end
desc 'Downloads and installs latest version of git'
task 'git:src:install', :needs => [ 'git:src:latest_version' ] do
download_url = ENV["GIT_DOWNLOAD_URL"]
git_package = File.basename(download_url)
git_src_folder = git_package.gsub(/.tar.gz/, "")
target_base_folder = "/usr/local"
usr_src_folder = File.join(target_base_folder, "src")
require("fileutils")
FileUtils.mkdir_p(usr_src_folder)
FileUtils.chdir(usr_src_folder) do
if File.exists?(git_package) then
puts("File #{git_package} already downloaded, skipping download...")
else
`wget #{download_url}`
end
if File.exists?(git_src_folder) then
puts("Removing existing #{git_src_folder} source")
FileUtils.rm_rf(git_src_folder)
end
puts("Unpacking #{git_src_folder}")
`tar xfv #{git_package}`
FileUtils.chdir(git_src_folder) do
puts("Installing to #{target_base_folder}")
sh("make prefix=#{target_base_folder} all")
sh("sudo make prefix=#{target_base_folder} install all")
end
end
puts("Run 'sake git:manpages:install' to install manpages for #{`git --version`}")
end
task 'git:src:latest_version' do
require("rubygems")
begin
(gem("hpricot")
require("hpricot"))
rescue LoadError
puts("REQUIREMENT: Hpricot")
puts("Installation: sudo gem install hpricot")
exit
end
require("open-uri")
doc = open("http://git.or.cz/").read
if download_url = doc.match(/http:\/\/kernel.org\/pub\/software\/scm\/git\/git-([\d.]+).tar.gz/) then
ENV["GIT_DOWNLOAD_URL"] = download_url[0]
puts("Current git src version: #{$1}")
end
end
desc 'Show the current status of the checkout'
task 'git:status' do
system("git status")
end
desc 'Create a new topic branch'
task 'git:topic' do
require("readline")
total = `git branch`.scan("quick").size
(total == 0) ? (default = "quick") : (default = "quick#{(total + 1)}")
name = Readline.readline("Topic name (default #{default}): ")
name = default if name.strip.empty?
sh("git checkout -b #{name}")
end
desc 'Migrates an existing website folder into a gh-pages branch, and links back as submodule'
task 'github:pages:migrate_website' do
current_branch = `git branch | grep \"^*\" | sed -e \"s/* //\"`.strip
repo = `git config --list | grep \"^remote.origin.url\" | sed -e \"s/remote.origin.url=//\"`.strip
website_folder = (ENV["WEBSITE_PATH"] or "website")
tmp_folder = "/tmp/gh-pages-website"
puts("Moving #{website_folder} folder to branch gh-pages.")
puts("Working in #{current_branch} branch of #{repo}:")
commands = " rm -rf #{tmp_folder}\n mv #{website_folder} #{tmp_folder}\n git commit -a -m \"temporarily removing #{website_folder} whilst moving to gh-pages branch\"\n git symbolic-ref HEAD refs/heads/gh-pages\n rm .git/index\n git clean -fdx\n cp -R #{tmp_folder}/* .\n git add .\n git commit -a -m 'Import original #{website_folder} folder from #{current_branch} branch'\n git push origin gh-pages\n git checkout #{current_branch}\n git submodule add -b gh-pages #{repo} #{website_folder}\n git commit -a -m \"migrated #{website_folder} -> gh-pages branch, and replaced with submodule link\"\n git push\n".gsub(/^ /, "")
commands.split(/\n/).each { |cmd| sh(cmd) }
end
desc 'Creates the gh-pages branch, and links to it as \'website\' as submodule'
task 'github:pages:setup' do
current_branch = `git branch | grep \"^*\" | sed -e \"s/* //\"`.strip
repo = `git config --list | grep \"^remote.origin.url\" | sed -e \"s/remote.origin.url=//\"`.strip
puts("Working in #{current_branch} branch of #{repo}:")
commands = " git symbolic-ref HEAD refs/heads/gh-pages\n rm .git/index\n git clean -fdx\n echo \"My GitHub Page\" > index.html\n git add .\n git commit -a -m 'First gh-pages commit'\n git push origin gh-pages\n git checkout #{current_branch}\n git submodule add -b gh-pages #{repo} website\n git commit -a -m \"website -> gh-pages folder\"\n git push\n".gsub(/^ /, "")
commands.split(/\n/).each { |cmd| sh(cmd) }
end
desc 'Install GEM=gemname or GEMS=gem1,gem2 into each multiruby gem cache'
task 'multiruby:gems:install' do
unless gems = (ENV["GEM"] or ENV["GEMS"]) then
puts(" Usage:\n sake multiruby:gems:install GEM=gemname\n sake multiruby:gems:install GEMS=gem1,gem2\n".gsub(/ /, ""))
end
gems = gems.split(/,\s*/)
sh("multiruby -S gem install --no-ri --no-rdoc --development #{gems.join(" ")}")
end
desc 'Runs specs in current project against multiruby'
task 'multiruby:spec' do
default_ruby_flags = "-w -I#{["lib", "ext", "bin", "test"].join(File::PATH_SEPARATOR)}"
ruby_flags = (ENV["RUBY_FLAGS"] or default_ruby_flags)
filter = ENV["FILTER"]
test_globs = ENV["TEST"] ? ([ENV["TEST"]]) : (["spec/**/*_spec.rb"])
tests = (["rubygems", "spec"] + test_globs.map { |g| Dir.glob(g) }.flatten)
tests.map! { |f| "require \"#{f}\"" }
cmd = "#{ruby_flags} -e '#{tests.join("; ")}' #{filter}"
system("multiruby #{cmd}")
end
desc 'Runs tests in current project against multiruby'
task 'multiruby:test' do
default_ruby_flags = "-w -I#{["lib", "ext", "bin", "test"].join(File::PATH_SEPARATOR)}"
ruby_flags = (ENV["RUBY_FLAGS"] or default_ruby_flags)
filter = ENV["FILTER"]
test_globs = ENV["TEST"] ? ([ENV["TEST"]]) : (["test/**/test_*.rb"])
tests = (["rubygems", "test/unit"] + test_globs.map { |g| Dir.glob(g) }.flatten)
tests.map! { |f| "require \"#{f}\"" }
cmd = "#{ruby_flags} -e '#{tests.join("; ")}' #{filter}"
system("multiruby #{cmd}")
end
desc 'Runs any tests or specs in current project against multiruby'
task 'multiruby', :needs => [ 'multiruby:test', 'multiruby:spec' ] do
# do nothing
end
desc 'Launch mysql shell.'
task 'mysql:console', :needs => [ 'mysql:params' ] do
sh("mysql #{ENV["MYSQL_PARAMS"]}")
end
desc 'Dump the database to FILE (depends on mysql:params)'
task 'mysql:dump', :needs => [ 'mysql:params' ] do
fname = (ENV["FILE"] or ENV["DEFAULT_DB_DUMP_NAME"])
zipper = "| gzip" if fname =~ /\.gz$/
cmd = "mysqldump --add-drop-table --add-locks -K -e #{ENV["MYSQL_PARAMS"]} #{zipper} > #{fname}"
sh(cmd)
end
desc 'Load the database from FILE (depends on mysql:params)'
task 'mysql:load', :needs => [ 'mysql:params' ] do
fname = (ENV["FILE"] or ENV["DEFAULT_DB_DUMP_NAME"])
if fname =~ /\.gz$/ then
cmd = "gunzip < #{fname} | mysql #{ENV["MYSQL_PARAMS"]}"
else
cmd = "mysql #{ENV["MYSQL_PARAMS"]} < #{fname}"
end
sh(cmd)
end
task 'mysql:params', :needs => [ 'environment' ] do
ENV["DEFAULT_DB_DUMP_NAME"] = File.join(RAILS_ROOT, "db", "#{RAILS_ENV}-content.sql.gz")
config = ActiveRecord::Base.configurations[RAILS_ENV]
ENV["MYSQL_PARAMS"] = { :host => "-h", :username => "-u", :password => "-p", :database => nil }.map do |key, option|
value = (config[key] or config[key.to_s])
"#{option}#{value}" if value
end.join(" ")
end
desc 'Show the date/time format strings defined and example output'
task 'rails:date_formats' do
def no_environment
puts("\nPrerequisite task :environment not found.")
no_rails
end
def no_rails
puts("\nThis task must be run within the context of the root of a Rails application.\n\n")
exit
end
if Rake::Task.task_defined?(:environment) then
Rake::Task[:environment].invoke
else
no_environment
end
no_rails if Module.const_defined?("RAILS_ENV")
now = Time.now
[:to_date, :to_datetime, :to_time].each do |conv_meth|
obj = now.send(conv_meth)
puts(obj.class.name)
puts(("=" * obj.class.name.length))
name_and_fmts = obj.class::DATE_FORMATS.map do |k, v|
[k, "'#{String.===(v) ? (v) : ("&proc")}'"]
end
max_name_size = (name_and_fmts.map { |k, _| k.to_s.length }.max + 2)
max_fmt_size = (name_and_fmts.map { |_, v| v.length }.max + 1)
name_and_fmts.each do |format_name, format_str|
puts(sprintf("%#{max_name_size}s:%-#{max_fmt_size}s %s", format_name, format_str, obj.to_s(format_name)))
end
puts
end
end
desc 'Install your public key on a remote server.'
task 'ssh:install_public_key' do
begin
(require("rubygems")
require("net/ssh")
require("net/scp")
require("highline"))
rescue LoadError
abort("There was a problem loading net-ssh, net-scp, or highline. Please make sure you have them installed via RubyGems.")
end
public_key = if ENV["public_key_path"] then
if File.exists?(ENV["public_key_path"]) then
ENV["public_key_path"]
else
abort("The key you provided via the command line does not exist!")
end
else
discovered_key = ["id_rsa", "id_dsa", "identity"].map { |f| "#{ENV["HOME"]}/.ssh/#{f}.pub" }.detect do |f|
File.exists?(f)
end
if discovered_key then
discovered_key
else
abort("I wasn't able to discover your public key. I tried to find id_rsa.pub, id_dsa.pub,\nor identity.pub in \"#{ENV["HOME"]}/.ssh\". You can hard code the path to the file by \npassing public_key_path via the command line.\n")
end
end
h = HighLine.new
not_blank = Proc.new { |s| (not s.empty?) }
def not_blank.to_s
"not blank"
end
h.say("I need some information to SSH into the server.")
hostname = h.ask("Remote Hostname: ") { |q| q.validate = not_blank }
port = h.ask("Remote port: ") { |q| q.default = 22 }
username = h.ask("Username, enter for default: ") { |q| q.default = ENV["USER"] }
password = h.ask("Password: ") { |q| q.echo = "*" }
begin
Net::SSH.start(hostname, username, :password => password, :port => port) do |ssh|
puts("Uploading your public key... ")
ssh.scp.upload!(public_key, "my_public_key")
puts("Creating '.ssh' directory in your home directory")
ssh.exec!("mkdir .ssh")
puts("Concatenating your public key into the authorized_keys file")
ssh.exec!("cat my_public_key >> .ssh/authorized_keys")
puts("Removing your public key")
ssh.exec!("rm my_public_key")
puts("Setting permissions on .ssh")
ssh.exec!("chmod 700 .ssh")
puts("Setting permissions on your authorized_keys file")
ssh.exec!("chmod 600 .ssh/authorized_keys")
puts("\nAll done! Enjoy your new, potentially password-free login.")
end
rescue Net::SSH::AuthenticationFailed
puts("\nWhat we've got here... is a failure to communicate. There was a problem authenticating you.")
end
end