/
shell-prompt
executable file
·97 lines (77 loc) · 2.24 KB
/
shell-prompt
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
#!/usr/bin/env perl
use strict;
use warnings;
# Add this to your zshrc:
# function shell_prompt_precmd() {
# PROMPT=`shell-prompt`
# }
# precmd_functions+=(shell_prompt_precmd)
# Add this to your bashrc:
# PS1='$(shell-prompt)'
$| = 1;
my $user = $ENV{USER};
(my $pwd = $ENV{PWD}) =~ s{^/(?:Users|home)/\Q$user\E(/|$)}{~$1};
chomp(my $host = `hostname -s`);
chomp(my $cols = `tput cols`);
my $battery;
my $battery_file = "$ENV{HOME}/.battery" ;
if (-M $battery_file >= 0.001) {
chomp($battery = `battery`);
$battery =~ s/\.\d*//;
$battery =~ s/%//;
open my $handle, '>', $battery_file;
print $handle $battery;
}
else {
open my $handle, '<', $battery_file;
chomp($battery = <$handle>);
}
# VCS info
my $vcs;
my $status = `git status 2>&1`;
if (!$?) {
$vcs = 'g';
$vcs .= '*' if $status !~ /nothing to commit/;
if ($status =~ /On branch (.*)/) {
$vcs .= ":$1";
$vcs .= "+$1" if $status =~ /Your branch is ahead .* by (\d+) commit/;
$vcs .= "-$1" if $status =~ /Your branch is behind .* by (\d+) commit/;
$vcs .= "+$1-$2" if $status =~ /and have (\d+) and (\d+) different commit.* each, respectively/;
}
else {
$vcs .= ':' . `git describe --tags`;
chomp $vcs;
}
$vcs =~ s/\*:/*/;
}
my $nested;
$nested = ($ENV{SHLVL}-1).'x' if $ENV{SHLVL} > 1;
my ($lhs_length, $rhs_length);
sub calc_length {
$lhs_length = 2 + length($pwd);
$lhs_length += length($nested) if $nested;
$lhs_length += 3 + length($vcs) if $vcs;
$lhs_length += 4 + length($battery);
$rhs_length = 4 + length($user) + length($host);
$lhs_length + $rhs_length;
}
# Collapse long directory names into one letter abbreviations from the top down
while (calc_length > $cols) {
$pwd =~ s{/([^/])[^/]+/}{/$1/}
or last;
}
# nest level
print "\e[1;31m$nested\e[m" if $nested;
# pwd
print "\e[1;30m(\e[33m$pwd\e[30m)";
# vcs
print "-(\e[0;36m$vcs\e[1;30m)" if $vcs;
# dashes
print ('-' x ($cols - ($lhs_length + $rhs_length)));
# battery
my $battery_color = $battery < 20 ? "\e[1;31m" : $battery < 80 ? "\e[0;33m" : "\e[0;32m";
print "[$battery_color$battery%%\e[1;30m]-" if $battery;
# user@host
print "\e[1;30m(\e[0;32m$user\@$host\e[1;30m)-";
# newline and $
print "\e[m\n\$ ";