Skip to content

Commit 7327dd4

Browse files
committed
Merge branch '0.0.14-dev'
2 parents 151835d + cbe6ed2 commit 7327dd4

File tree

9 files changed

+159
-29
lines changed

9 files changed

+159
-29
lines changed

bashhub/bashhub.py

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
from model import UserContext
1111
import rest_client
1212
import bashhub_setup
13-
from bashhub_globals import *
13+
import bashhub_globals
14+
from bashhub_globals import BH_USER_ID, BH_SYSTEM_ID, BH_FILTER
1415
from version import __version__
1516
import shutil
1617
import requests
1718
import subprocess
1819
import shell_utils
20+
import re
1921
from view.status import *
2022

2123
def print_version(ctx, param, value):
@@ -47,14 +49,18 @@ def version():
4749
@click.argument('exit_status', type=int)
4850
def save(command, path, pid, process_start_time, exit_status):
4951
"""Save a command to bashhub.com"""
50-
5152
pid_start_time = unix_time_to_epoc_millis(process_start_time)
5253
command = command.strip()
5354

54-
# Check if we should ignore this commannd or not.
55+
# Check if we should ignore this command.
5556
if "#ignore" in command:
5657
return
5758

59+
# Check if we should filter this command.
60+
bh_filter = bashhub_globals.BH_FILTER
61+
if bh_filter and re.findall(bh_filter, command):
62+
return
63+
5864
context = UserContext(pid, pid_start_time, BH_USER_ID, BH_SYSTEM_ID)
5965
command = CommandForm(command, path, exit_status, context)
6066
rest_client.save_command(command)
@@ -72,6 +78,43 @@ def status():
7278
status_view = rest_client.get_status_view(user_context)
7379
click.echo(build_status_view(status_view))
7480

81+
82+
@bashhub.command()
83+
@click.pass_context
84+
def help(ctx):
85+
"""Show this message and exit"""
86+
click.echo(ctx.parent.get_help())
87+
88+
89+
90+
# Dynamic help text containing the BH_FILTER variable.
91+
filtered_text = "BH_FILTER={0}".format(BH_FILTER) if BH_FILTER else "BH_FILTER \
92+
is unset."
93+
filter_help_text = """Check if a command is filtered from bashhub. Filtering
94+
is configured via a regex exported as BH_FILTER.
95+
\n
96+
{0}""".format(filtered_text)
97+
98+
@bashhub.command(help=filter_help_text)
99+
@click.argument('command', type=str)
100+
@click.option('-r', '--regex', default=BH_FILTER, help='Regex to filter against')
101+
def filter(command, regex):
102+
103+
# Check if the regex we receive is valid
104+
if not bashhub_globals.is_valid_regex(regex):
105+
click.secho("Regex {0} is invalid".format(regex), fg='red')
106+
return
107+
108+
v = re.findall(regex, command)
109+
click.echo(filtered_text)
110+
if v and regex:
111+
matched = [str(s) for s in set(v)]
112+
output = click.style("{0} \nIs Filtered. Matched ".format(command),
113+
fg='yellow') + click.style(str(matched), fg='red')
114+
click.echo(output)
115+
else:
116+
click.echo("{0} \nIs Unfiltered".format(command))
117+
75118
@bashhub.command()
76119
@click.argument('version', type=str, default="")
77120
def update(version):
@@ -124,7 +167,6 @@ def main():
124167
bashhub()
125168
except Exception as e:
126169
formatted = traceback.format_exc(e)
127-
click.echo("Oops, look like an exception occured: " + str(e))
170+
click.echo("Oops, looks like an exception occured: " + str(e))
128171
sys.exit(1)
129172

130-
main()

bashhub/bashhub_globals.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,25 @@
44
"""
55

66
import os
7-
8-
def get_global_from_env(env_var, default):
9-
return default if env_var not in os.environ.keys() \
10-
else os.environ[env_var]
11-
7+
import re
128

139
# Optional environment variable to configure for development
1410
# export BH_URL='http://localhost:9000'
15-
BH_URL = get_global_from_env('BH_URL', 'https://bashhub.com')
11+
BH_URL = os.getenv('BH_URL', 'https://bashhub.com')
1612

17-
BH_USER_ID = get_global_from_env('BH_USER_ID', '')
13+
BH_USER_ID = os.getenv('BH_USER_ID', '')
1814

19-
BH_SYSTEM_ID = get_global_from_env('BH_SYSTEM_ID', '')
15+
BH_SYSTEM_ID = os.getenv('BH_SYSTEM_ID', '')
2016

21-
BH_HOME = "~/.bashhub" if "HOME" not in os.environ.keys() \
22-
else os.environ["HOME"] + '/.bashhub'
17+
BH_HOME = '~/.bashhub' if 'HOME' not in os.environ.keys() \
18+
else os.environ['HOME'] + '/.bashhub'
2319

20+
def is_valid_regex(regex):
21+
try:
22+
re.compile(regex)
23+
return True
24+
except re.error:
25+
return False
2426

27+
BH_FILTER = os.getenv('BH_FILTER', '') if is_valid_regex(os.getenv('BH_FILTER', '')) \
28+
else '__invalid__'

bashhub/bashhub_setup.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
import requests
1818
from requests import ConnectionError
1919
from requests import HTTPError
20-
import hashlib
2120

2221
def query_yes_no(question, default="yes"):
2322
"""Ask a yes/no question via raw_input() and return their answer.
@@ -182,6 +181,12 @@ def main():
182181
sys.exit(0)
183182

184183
system_id = handle_system_information(user_id)
184+
185+
if system_id == None:
186+
print("Sorry looks like getting your info failed.\
187+
Exiting...")
188+
sys.exit(0)
189+
185190
write_config_file(user_id, system_id)
186191
sys.exit(0)
187192

bashhub/shell/deps/bash-preexec.sh

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
# Author: Ryan Caloras ([email protected])
1212
# Forked from Original Author: Glyph Lefkowitz
1313
#
14-
# V0.2.1
14+
# V0.2.3
1515
#
1616

1717
# General Usage:
@@ -40,6 +40,20 @@ if [[ "$__bp_imported" == "defined" ]]; then
4040
fi
4141
__bp_imported="defined"
4242

43+
44+
# Remove ignorespace and or replace ignoreboth from HISTCONTROL
45+
# so we can accurately invoke preexec with a command from our
46+
# history even if it starts with a space.
47+
__bp_adjust_histcontrol() {
48+
local histcontrol
49+
histcontrol="${HISTCONTROL//ignorespace}"
50+
# Replace ignoreboth with ignoredups
51+
if [[ "$histcontrol" == *"ignoreboth"* ]]; then
52+
histcontrol="ignoredups:${histcontrol//ignoreboth}"
53+
fi;
54+
export HISTCONTROL="$histcontrol"
55+
}
56+
4357
# This variable describes whether we are currently in "interactive mode";
4458
# i.e. whether this shell has just executed a prompt and is waiting for user
4559
# input. It documents whether the current command invoked by the trace hook is
@@ -71,10 +85,11 @@ __bp_precmd_invoke_cmd() {
7185

7286
# For every function defined in our function array. Invoke it.
7387
local precmd_function
74-
for precmd_function in ${precmd_functions[@]}; do
88+
for precmd_function in "${precmd_functions[@]}"; do
7589

7690
# Only execute this function if it actually exists.
77-
if [[ -n $(type -t $precmd_function) ]]; then
91+
# Test existence of functions with: declare -[Ff]
92+
if type -t "$precmd_function" 1>/dev/null; then
7893
__bp_set_ret_value $ret_value
7994
$precmd_function
8095
fi
@@ -96,7 +111,7 @@ __bp_in_prompt_command() {
96111
local trimmed_arg
97112
trimmed_arg=$(__bp_trim_whitespace "$1")
98113

99-
local prompt_command_function
114+
local command
100115
for command in "${prompt_command_array[@]}"; do
101116
local trimmed_command
102117
trimmed_command=$(__bp_trim_whitespace "$command")
@@ -146,10 +161,11 @@ __bp_preexec_invoke_exec() {
146161
return
147162
fi
148163

149-
local this_command="$(history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g")";
164+
local this_command
165+
this_command=$(HISTTIMEFORMAT= history 1 | { read -r _ this_command; echo "$this_command"; })
150166

151167
# Sanity check to make sure we have something to invoke our function with.
152-
if [ -z "$this_command" ]; then
168+
if [[ -z "$this_command" ]]; then
153169
return
154170
fi
155171

@@ -162,7 +178,8 @@ __bp_preexec_invoke_exec() {
162178
for preexec_function in "${preexec_functions[@]}"; do
163179

164180
# Only execute each function if it actually exists.
165-
if [[ -n $(type -t $preexec_function) ]]; then
181+
# Test existence of function with: declare -[fF]
182+
if type -t "$preexec_function" 1>/dev/null; then
166183
$preexec_function "$this_command"
167184
fi
168185
done
@@ -172,7 +189,7 @@ __bp_preexec_invoke_exec() {
172189
__bp_preexec_and_precmd_install() {
173190

174191
# Make sure this is bash that's running this and return otherwise.
175-
if [ -z "$BASH_VERSION" ]; then
192+
if [[ -z "$BASH_VERSION" ]]; then
176193
return 1;
177194
fi
178195

@@ -181,12 +198,17 @@ __bp_preexec_and_precmd_install() {
181198
return 1;
182199
fi
183200

201+
# Adjust our HISTCONTROL Variable if needed.
202+
__bp_adjust_histcontrol
203+
184204
# Take our existing prompt command and append a semicolon to it
185205
# if it doesn't already have one.
186206
local existing_prompt_command
187207

188-
if [ -n "$PROMPT_COMMAND" ]; then
189-
existing_prompt_command=$(echo "$PROMPT_COMMAND" | sed '/; *$/!s/$/;/')
208+
if [[ -n "$PROMPT_COMMAND" ]]; then
209+
existing_prompt_command=${PROMPT_COMMAND%${PROMPT_COMMAND##*[![:space:]]}}
210+
existing_prompt_command=${existing_prompt_command%;}
211+
existing_prompt_command=${existing_prompt_command/%/;}
190212
else
191213
existing_prompt_command=""
192214
fi

bashhub/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '0.0.13'
1+
__version__ = '0.0.14'

bashhub/view/status.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
status_view ="""\
66
=== Bashhub Status
7-
http://bashhub.com/u/{0}
7+
https://bashhub.com/u/{0}
88
Total Commands: {1}
99
Total Sessions: {2}
1010
Total Systems: {3}

install-bashhub.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ zshprofile=~/.zshrc
4141

4242
# Optional parameter to specify a github branch
4343
# to pull from.
44-
github_branch=${1:-'0.0.13'}
44+
github_branch=${1:-'0.0.14'}
4545

4646
install_bashhub() {
4747
check_dependencies

tests/test_bashhub.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import os
2+
3+
import click
4+
from click.testing import CliRunner
5+
6+
from bashhub.bashhub import bashhub
7+
from bashhub.version import __version__
8+
from bashhub.bashhub import rest_client
9+
from bashhub.bashhub import bashhub_globals
10+
11+
def test_bashhub_save():
12+
13+
def print_failed(command):
14+
print("Failed")
15+
pass
16+
17+
rest_client.save_command = print_failed
18+
19+
runner = CliRunner()
20+
args = ['save',
21+
'echo "Running bashhub tests"',
22+
'/tmp',
23+
'1',
24+
'100000',
25+
'1']
26+
27+
ignored_command = ['save',
28+
'echo "Running bashhub tests" #ignore',
29+
'/tmp',
30+
'1',
31+
'100000',
32+
'1']
33+
34+
# Should omit saving if #ignore is set
35+
result = runner.invoke(bashhub, ignored_command)
36+
assert '' == result.output
37+
38+
# Should omit saving a command if BH_FILTER regex is set
39+
#bashhub_globals = Temp()
40+
bashhub_globals.BH_FILTER = 'echo'
41+
result = runner.invoke(bashhub, args)
42+
assert '' == result.output
43+
44+
def test_bashhub_version():
45+
runner = CliRunner()
46+
result = runner.invoke(bashhub, ['version'])
47+
assert __version__ in result.output

tests/test_bashhub_globals.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2+
from bashhub.bashhub import bashhub_globals
3+
4+
def test_is_valid_regex():
5+
invalid_regex = '[a-2]'
6+
valid_regex = '(filter_me|ssh)'
7+
assert False == bashhub_globals.is_valid_regex(invalid_regex)
8+
assert True == bashhub_globals.is_valid_regex(valid_regex)
9+
10+

0 commit comments

Comments
 (0)