Skip to content

Commit

Permalink
Add uninstall script and other updates (#25)
Browse files Browse the repository at this point in the history
* add alias for batterymanager for now

* add uninstall script

* test alias

* add status messages

* fix spacing before command

* move command names and descriptions to their respective classes

* make green

* it's bytes not str

* don't need

* debug

* test formatting

* test formatting

* does this fix it?

* add temperature

* add -

* add -

* fix

* remove to fix

* don't delete system .bashrc and don't delete community .bashrc for now

* test uninstall

* debug

* add uninstall command to python CLI

* fix

* update README.md

* fix battery

* remove fork

* last commit, remove from aliases

* uninstall the entrypoint script

Co-authored-by: AskAlice <[email protected]>
  • Loading branch information
sshane and AskAlice authored Jun 23, 2020
1 parent 0601b87 commit 98acc29
Show file tree
Hide file tree
Showing 13 changed files with 144 additions and 31 deletions.
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ This repo is very much in active development! Expect it to evolve greatly over t
# Getting Started

```bash
bash <(curl -fsSL install.emu.sh) # the brain of the bird
source /home/.bashrc
bash <(curl -fsSL install.emu.sh) # the brain of the bird
source /home/.bashrc
```

<img src="https://thumbs.gfycat.com/DopeyHairyGeese-size_restricted.gif" alt ="" />
Expand Down Expand Up @@ -42,16 +42,23 @@ The default directory of your bash/ssh session is now `/data/openpilot`. Much ea

### General

- `emu fork install https://github.com/...`: Clones the fork URL to `/data/openpilot`. Current folder is moved to `/data/openpilot.old` before cloning
- `emu fork`: 🍴 manage installed forks, or clone a new one
- `install`: Clones a fork URL to `/data/openpilot`. Current folder is moved to `/data/openpilot.old` after cloning
- `emu update`: 🎉 updates this tool
- `emu info`: 📈 Statistics about your device
- `battery`: 🔋 see information about the state of your battery
- `emu uninstall`: 👋 Uninstalls emu

### Panda

- `emu panda flash`: Flashes the panda
- `emu panda flash2`: Flashes the panda without `make recover`
- `emu panda`: 🐼 panda interfacing tools
- `flash`: 🐼 flashes panda with make recover (usually works with the C2)
- `flash2`: 🎍 flashes panda using Panda module (usually works with the EON)

### Debugging

- `emu debug controls`: You can debug controlsd and output it to a log file `/data/output.log`
- `emu debug`: de-🐛-ing tools
- `controlsd`: 🔬 logs controlsd to /data/output.log by default

# Git config

Expand Down
10 changes: 2 additions & 8 deletions emu.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,15 @@

from py_utils.emu_utils import BaseFunctions
from py_utils.emu_utils import OPENPILOT_PATH
from emu_commands.fork import Fork
from emu_commands.update import Update
from emu_commands.panda import Panda
from emu_commands.debug import Debug
from emu_commands import EMU_COMMANDS

sys.path.append(OPENPILOT_PATH) # for importlib
DEBUG = not path.exists('/data/params/d')

class Emu(BaseFunctions):
def __init__(self, args):
self.args = args
self.commands = {'fork': Fork('🍴 control installed forks, or clone a new one'),
'update': Update('🎉 updates this tool, recommended to restart ssh session'),
'panda': Panda('🐼 panda interfacing tools'),
'debug': Debug('de-🐛-ing tools')}
self.commands = {cmd.name: cmd for cmd in EMU_COMMANDS}
self.parse()

def parse(self):
Expand Down
9 changes: 9 additions & 0 deletions emu_commands/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from emu_commands.fork import Fork
from emu_commands.update import Update
from emu_commands.panda import Panda
from emu_commands.debug import Debug
from emu_commands.info import Info
from emu_commands.uninstall import Uninstall


EMU_COMMANDS = [Fork(), Update(), Panda(), Debug(), Info(), Uninstall()]
9 changes: 4 additions & 5 deletions emu_commands/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from py_utils.colors import COLORS
from py_utils.emu_utils import ArgumentParser, BaseFunctions, warning, success
from py_utils.emu_utils import ArgumentParser, BaseFunctions, success, error

class CommandBase(BaseFunctions):
def __init__(self, description):
self.description = description
def __init__(self):
self.commands = {}

def main(self, args, cmd_name):
Expand All @@ -18,12 +17,12 @@ def main(self, args, cmd_name):
return
self.start_function_from_str(cmd)
else:
self.start_function_from_str(cmd_name)
self.start_function_from_str(cmd_name) # eg. update and uninstall

def start_function_from_str(self, cmd):
cmd = '_' + cmd
if not hasattr(self, cmd):
print('Command has not been implemented yet, please try updating.')
error('Command has not been implemented yet, please try updating.')
return
getattr(self, cmd)() # call command's function

Expand Down
7 changes: 5 additions & 2 deletions emu_commands/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
from py_utils.emu_utils import OPENPILOT_PATH

class Debug(CommandBase):
def __init__(self, description):
super().__init__(description)
def __init__(self):
super().__init__()
self.name = 'debug'
self.description = 'de-🐛-ing tools'

self.commands = {'controlsd': Command(description='🔬 logs controlsd to /data/output.log by default',
flags=[Flag(['-o', '--output'], 'Name of file to save log to', has_value=True)])}
self.default_path = '/data/output.log'
Expand Down
7 changes: 5 additions & 2 deletions emu_commands/fork.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
from py_utils.emu_utils import OPENPILOT_PATH

class Fork(CommandBase):
def __init__(self, description):
super().__init__(description)
def __init__(self):
super().__init__()
self.name = 'fork'
self.description = '🍴 manage installed forks, or clone a new one'

self.commands = {'install': Command(description='🦉 Whoooose fork do you wanna install?',
flags=[Flag(['clone_url'], '🍴 URL of fork to clone', has_value=True),
Flag(['-l', '--lite'], '💡 Clones only the default branch with all commits flattened for quick cloning'),
Expand Down
34 changes: 34 additions & 0 deletions emu_commands/info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from emu_commands.base import CommandBase, Command, Flag
from py_utils.emu_utils import run, warning, error, check_output, COLORS, success

class Info(CommandBase):
def __init__(self):
super().__init__()
self.name = 'info'
self.description = '📈 Statistics about your device'

self.commands = {'battery': Command(description='🔋 see information about the state of your battery')}

def _battery(self):
r = check_output('dumpsys batterymanager')
if not r:
error('Unable to get battery status!')
return
r = r.decode('utf-8').split('\n')
r = [i.strip() for i in r if i != ''][1:]
battery_idxs = {'level': 7, 'temperature': 10}
success('Battery info:')
for name in battery_idxs:
idx = battery_idxs[name]
info = r[idx]

value = float(info.split(': ')[1])
if name == 'temperature':
value /= 10
value = str(value) + ' °C'
else:
value = str(value) + '%'

value = COLORS.SUCCESS + str(value)
name = COLORS.WARNING + name.title()
print('- {}: {}{}'.format(name, value, COLORS.ENDC))
7 changes: 5 additions & 2 deletions emu_commands/panda.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
from py_utils.emu_utils import OPENPILOT_PATH

class Panda(CommandBase):
def __init__(self, description):
super().__init__(description)
def __init__(self):
super().__init__()
self.name = 'panda'
self.description = '🐼 panda interfacing tools'

self.commands = {'flash': Command(description='🐼 flashes panda with make recover (usually works with the C2)'),
'flash2': Command(description='🎍 flashes panda using Panda module (usually works with the EON)')}

Expand Down
15 changes: 15 additions & 0 deletions emu_commands/uninstall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from emu_commands.base import CommandBase, Command, Flag
from py_utils.emu_utils import run, warning, error, check_output, COLORS, success, input_with_options, UNINSTALL_PATH

class Uninstall(CommandBase):
def __init__(self):
super().__init__()
self.name = 'uninstall'
self.description = '👋 Uninstalls emu'

def _uninstall(self):
print('Are you sure you want to uninstall emu?')
if input_with_options(['Y', 'n'], 'n')[0] == 0:
run(['sh', UNINSTALL_PATH])
else:
error('Not uninstalling!')
6 changes: 4 additions & 2 deletions emu_commands/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
from py_utils.emu_utils import UPDATE_PATH

class Update(CommandBase):
def __init__(self, description):
super().__init__(description)
def __init__(self):
super().__init__()
self.name = 'update'
self.description = '🎉 updates this tool, recommended to restart ssh session'

def _update(self):
if not run(['sh', UPDATE_PATH]):
Expand Down
37 changes: 35 additions & 2 deletions py_utils/emu_utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import psutil
import difflib
import requests
import argparse
import subprocess
import sys
if __package__ is None:
from os import path
sys.path.append(path.abspath(path.join(path.dirname(__file__), '../py_utils')))
Expand All @@ -17,6 +18,7 @@
COMMUNITY_BASHRC_PATH = '/data/community/.bashrc'
OH_MY_COMMA_PATH = '/data/community/.oh-my-comma'
UPDATE_PATH = '{}/update.sh'.format(OH_MY_COMMA_PATH)
UNINSTALL_PATH = '{}/uninstall.sh'.format(OH_MY_COMMA_PATH)
OPENPILOT_PATH = '/data/openpilot'


Expand Down Expand Up @@ -61,6 +63,37 @@ def next_arg(self, lower=True, ingest=True):
return arg


def input_with_options(options, default=None):
"""
Takes in a list of options and asks user to make a choice.
The most similar option list index is returned along with the similarity percentage from 0 to 1
"""
def str_sim(a, b):
return difflib.SequenceMatcher(a=a, b=b).ratio()

user_input = input('[{}]: '.format('/'.join(options))).lower().strip()
if not user_input:
return default, 0.0
sims = [str_sim(i.lower().strip(), user_input) for i in options]
argmax = sims.index(max(sims))
return argmax, sims[argmax]


def check_output(cmd):
"""
If cmd is a string, it is split into a list, otherwise it doesn't modify cmd.
The status is returned, True being success, False for failure
"""
if isinstance(cmd, str):
cmd = cmd.split()

try:
return subprocess.check_output(cmd)
except Exception as e:
# print(e)
return False


def run(cmd, out_file=None):
"""
If cmd is a string, it is split into a list, otherwise it doesn't modify cmd.
Expand All @@ -77,7 +110,7 @@ def run(cmd, out_file=None):
r = subprocess.call(cmd, stdout=f)
return not r
except Exception as e:
print(e)
# print(e)
return False


Expand Down
13 changes: 13 additions & 0 deletions uninstall.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/bash

# COMMUNITY_PATH=/data/community # probably shouldn't remove since it will hold forks in the future
COMMUNITY_BASHRC_PATH=/data/community/.bashrc
OH_MY_COMMA_PATH=/data/community/.oh-my-comma

#echo "Deleting $COMMUNITY_BASHRC_PATH"
#rm $COMMUNITY_BASHRC_PATH
sed -i.bak.$(date +"%Y-%m-%d-%T") -e '/^## BEGIN \.oh-my-comma magic ###/,/^### End of \.oh-my-comma magic ###/d' ${COMMUNITY_BASHRC_PATH}
echo "Deleting $OH_MY_COMMA_PATH"
rm -rf $OH_MY_COMMA_PATH

echo "Uninstalled!"
2 changes: 0 additions & 2 deletions update.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,3 @@ echo "====== FROM ======"
printf "Version \033[92m${PREV_VERSION}\033[0m | branch \033[92m${PREV_BRANCH}\033[0m | remote \033[92m${PREV_REMOTE}\033[0m\n"
printf "Version \033[92m${CURRENT_VERSION}\033[0m | branch \033[92m${CURRENT_BRANCH}\033[0m | remote \033[92m${CURRENT_REMOTE}\033[0m\n"
echo "======= TO ======="

exec $SHELL # auto source

0 comments on commit 98acc29

Please sign in to comment.