Skip to content

Instantly share code, notes, and snippets.

@foca
Created July 25, 2008 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foca/2521 to your computer and use it in GitHub Desktop.
Save foca/2521 to your computer and use it in GitHub Desktop.
#!/bin/sh
export COLUMNS=$COLUMNS # term width isn't exported properly :(
export PS1='`ps1`'
#!/bin/sh
# cd into matching gem directory ("cd -" friendly)
cdgem() {
local gempath=$(gem env gemdir)/gems
if [[ $1 == "" ]]; then
cd $gempath
return
fi
local gem=$(ls $gempath | g $1 | sort | tail -1)
if [[ $gem != "" ]]; then
cd $gempath/$gem
fi
}
_cdgem() {
COMPREPLY=($(compgen -W '$(ls `gem env gemdir`/gems)' -- ${COMP_WORDS[COMP_CWORD]}))
return 0;
}
complete -o default -o nospace -F _cdgem cdgem;
# check for a rake task on the current dir
function rake_exists? {
[[ -f Rakefile && $(rake -T | g $1 | wc -l) -gt 0 ]]; return $?
}
# get current revision of a repo
svn_revision() {
svn info $@ | awk '/^Revision:/ {print $2}'
}
# print the log or 'no changes' after an update
svn_up_and_log() {
local old_rev=$(svn_revision $@)
local first_up=$((${old_rev} + 1))
svn up -q $@
if [ $(svn_revision $@) -gt ${old_rev} ]; then
svn log -v -rHEAD:${first_up} $@
else
echo "No changes."
fi
}
# tag a directory in a command to come to it later
tag() {
alias $1='cd $PWD'
}
# alias last command
a() {
x=`history 1 | sed 's/.\{7\}//'`;
alias ${1}="${x}";
}
# True if a domain name is available
domainavailable() {
if whois $1 | grep "No match for" &> /dev/null; then
echo "$1 is available"
return 0
else
echo "$1 is not available"
return 1
fi
}
# Check all domains passed as arguments and print those available
availabledomains() {
for f in $@; do
domainavailable $f &> /dev/null && echo $f;
done
}
# CD back to current git's project base dir
cdg() {
local cdup=$(git-rev-parse --show-cdup 2> /dev/null)
if [ $? == 0 ]; then
if [ -z "$cdup" ]; then
cdup=.
fi
cd $cdup/$1
else
echo "Not in a git repository"
return $?
fi
}
# Git "dirty?"
git-dirty() {
git st 2>/dev/null | wc -l | awk '{if ($1 > 2) print "*"}'
}
# size of passed file, in MB
sizeof() {
shr "puts sizeof('$1')"
}
ps1() {
shr "puts PS1.to_s"
}
# size of curdir
dirsize() {
shr "puts dirsize"
}
# executes ruby command with shell stuff mixed in
shr() {
ruby -r ~/.ruby/shellthings -e "$@"
}
# Use ruby as a calculator"
calc() {
ruby -e 'include Math; puts eval(ARGV.join(" "))' $@;
}
# copied from the 'colored' gem
##
# cute.
#
# >> "this is red".red
#
# >> "this is red with a blue background (read: ugly)".red_on_blue
#
# >> "this is red with an underline".red.underline
#
# >> "this is really bold and really blue".bold.blue
#
# >> Colored.red "This is red" # but this part is mostly untested
module Colored
extend self
COLORS = {
'black' => 30,
'red' => 31,
'green' => 32,
'yellow' => 33,
'blue' => 34,
'magenta' => 35,
'cyan' => 36,
'white' => 37
}
EXTRAS = {
'clear' => 0,
'bold' => 1,
'underline' => 4,
'reversed' => 7
}
COLORS.each do |color, value|
define_method(color) do
colorize(self, :foreground => color)
end
define_method("on_#{color}") do
colorize(self, :background => color)
end
COLORS.each do |highlight, value|
next if color == highlight
define_method("#{color}_on_#{highlight}") do
colorize(self, :foreground => color, :background => highlight)
end
end
end
EXTRAS.each do |extra, value|
next if extra == 'clear'
define_method(extra) do
colorize(self, :extra => extra)
end
end
define_method(:to_eol) do
tmp = sub(/^(\e\[[\[\e0-9;m]+m)/, "\\1\e[2K")
if tmp == self
return "\e[2K" << self
end
tmp
end
def colorize(string, options = {})
colored = [color(options[:foreground]), color("on_#{options[:background]}"), extra(options[:extra])].compact * ''
colored << string
colored << extra(:clear)
end
def colors
@@colors ||= COLORS.keys.sort
end
def extra(extra_name)
extra_name = extra_name.to_s
"\e[#{EXTRAS[extra_name]}m" if EXTRAS[extra_name]
end
def color(color_name)
background = color_name.to_s =~ /on_/
color_name = color_name.to_s.sub('on_', '')
return unless color_name && COLORS[color_name]
"\e[#{COLORS[color_name] + (background ? 10 : 0)}m"
end
end unless Object.const_defined? :Colored
String.send(:include, Colored)
Since gist blows up with filenames that have slashes:
~/.bashrc
~/.functions
~/ruby/shellthings.rb
~/ruby/colored.rb
require File.dirname(__FILE__) + "/colored"
def human_readable_size(number)
number = number.to_i
(unit, divisor) = case
when number > 1073741824 then ["GiB", 1073741824.0]
when number > 1048576 then ["MiB", 1048576.0]
when number > 1024 then ["KiB", 1024.0]
else [ "B", 1]
end
format "%0.02f #{unit}", (number / divisor).to_s
end
def sizeof(file)
human_readable_size File.size(file)
end
def dirsize(dir=Dir.pwd)
human_readable_size Dir["#{dir}/*"].inject(0) {|s,f| File.file?(f) ? s + File.size(f) : s }
end
module PS1
extend self
def term_width
ENV["COLUMNS"].to_i
end
def user
ENV["USER"].green.bold
end
def pwd(max)
orig_dir = dir = Dir.pwd.gsub("/Users/#{ENV["USER"]}", "~")
dir = dir.gsub(%r{^([^/]+)/}, "") while dir.length + 4 > max
dir = ".../" + dir if dir != orig_dir
dir.yellow.bold
end
def size
["[".blue.bold,
dirsize.magenta.bold,
"]".blue.bold].join(" ")
end
def git?
while (d = d ? File.dirname(d) : Dir.pwd).length > 1
return true if File.directory?(File.join(d, ".git"))
end
false
end
def git_branch
return unless git?
branch = File.basename(`git symbolic-ref HEAD`.chomp)
dirty = `git status 2>/dev/null`.chomp.split("\n").size > 2 ? "*" : ""
"(git: #{branch}".cyan.bold + dirty.bold + ")".cyan.bold
end
def datetime
qualifier = case Time.now.strftime("%d").to_i
when 1, 21, 31 then "st"
when 2, 22 then "nd"
when 3, 23 then "rd"
else "th"
end
["[".blue.bold,
Time.now.strftime("%H:%M").yellow.bold,
"|".blue.bold,
Time.now.strftime("%a, %b %d#{qualifier}").yellow.bold,
"]".blue.bold].join(" ")
end
def to_s
# magic 3: minimum 3 equal signs separating date and size
max_pwd_width = term_width - 5 - [user, git_branch, size, datetime].compact.inject(0) {|t,s| t + uncolored(s).length }
left_hand = [user, pwd(max_pwd_width), git_branch, size].compact.join(" ")
right_hand = datetime
whitespace = term_width - uncolored(left_hand).length - uncolored(right_hand).length
in_between = ("=" * (whitespace > 0 ? whitespace : 1)).blue.bold
left_hand + in_between + right_hand + "\n$ "
end
private
def uncolored(str)
str.gsub(/\e\[\d+m/, '')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment