Skip to content

Commit

Permalink
Create shared dbprint utils
Browse files Browse the repository at this point in the history
  • Loading branch information
L1ghtmann authored and 0cyn committed Jan 10, 2024
1 parent 5ed1d81 commit 114a4d2
Show file tree
Hide file tree
Showing 9 changed files with 105 additions and 195 deletions.
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
author='cynder',
url='https://dragon.cynder.me/',
install_requires=['ninja', 'pyyaml', 'ruyaml', 'packaging', 'tqdm'],
packages=['dragon', 'dragongen', 'buildgen'],
packages=['dragon', 'dragongen', 'buildgen', 'shared'],
package_dir={
'dragon': 'src/dragon',
'dragongen': 'src/dragongen',
'buildgen': 'src/buildgen',
'shared': 'src/shared',
},
package_data={
'dragon': ['shscripts/*', 'config/*'],
Expand Down
65 changes: 29 additions & 36 deletions src/dragon/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,7 @@
'''

import os, sys, yaml, subprocess, socket
from .util import dprintline, OutputColors, OutputWeight

dbstate = lambda msg: dprintline(label_color=OutputColors.Green, tool_name="Device", text_color=OutputColors.White,
text_weight=OutputWeight.Bold, pusher=False, msg=msg)
dbwarn = lambda msg: dprintline(label_color=OutputColors.Yellow, tool_name="Device", text_color=OutputColors.White,
text_weight=OutputWeight.Normal, pusher=False, msg=msg)
dberror = lambda msg: dprintline(label_color=OutputColors.Red, tool_name="Device", text_color=OutputColors.White,
text_weight=OutputWeight.Bold, pusher=False, msg=msg)
from shared.util import dbstate, dbwarn, dberror


def system(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
Expand Down Expand Up @@ -116,18 +109,18 @@ def run_cmd(self, cmd, quiet=False):
return

if not self.test_connection():
dberror(f'Could not connect to device at {self.host}:{self.port}')
dberror("Device", f'Could not connect to device at {self.host}:{self.port}')
if self.host == "localhost" and self.port == 4444:
dberror(f'To configure a new device, run "dragon s"')
dberror("Device", f'To configure a new device, run "dragon s"')
self.connection_failure_resolver()
return

if not quiet:
if cmd == '':
dbstate("Launching Device Shell")
dbstate("Device", "Launching Device Shell")
DeviceShell.launch(self)
return
dbstate(f'Running "{cmd}" on {self.host}:{self.port}')
dbstate("Device", f'Running "{cmd}" on {self.host}:{self.port}')
return system_pipe_output(f'ssh -p {self.port} root@{self.host} "{cmd}"')

def export_ip(self):
Expand All @@ -139,20 +132,20 @@ def export_ip(self):
print(f'export {x}="{exports[x]}"')

def setup_key_auth(self):
dbstate('Setting up keybased auth')
dbstate("Device", 'Setting up keybased auth')
exists = system('stat ~/.ssh/id_rsa') == 0
if not exists:
dbstate('Generating Keyfile')
dbstate("Device", 'Generating Keyfile')
system("ssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa <<<y 2>&1 >/dev/null")

# We don't use ssh-copy-id because some systems (Elucubratus, etc) don't have it
dbstate('Copying keyfile')
dbstate("Device", 'Copying keyfile')
success = system(
f'cat ~/.ssh/id_rsa.pub | ssh -p {self.port} root@{self.host} "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"')
if success == 0:
dbstate('Enabled keybased auth')
dbstate("Device", 'Enabled keybased auth')
else:
dberror('Failed')
dberror("Device", 'Failed')


class DeviceManager(object):
Expand Down Expand Up @@ -188,10 +181,10 @@ def resolve_known_hosts_issue(self, stderr):
known_hosts_line = int(line.split('known_hosts:')[-1])
file_location = line.split(' key in ')[-1].split(":")[0]

dbwarn("There is already an entry in the known_hosts file for your system")
dbwarn("Device", "There is already an entry in the known_hosts file for your system")
if file_location:
dbwarn(f'Bad entry: {file_location}:{known_hosts_line}')
dbwarn("You will not be able to connect to this device until this is resolved. Remove this line? (y/n)")
dbwarn("Device", f'Bad entry: {file_location}:{known_hosts_line}')
dbwarn("Device", "You will not be able to connect to this device until this is resolved. Remove this line? (y/n)")
if 'y' in input('> ').lower():
try:
with open(file_location, "r") as infile:
Expand All @@ -206,13 +199,13 @@ def resolve_known_hosts_issue(self, stderr):
print(f'Removed {line}')
return True
except IOError:
dberror("Error reading or writing to file. Please manually remove the line.")
dberror("Device", "Error reading or writing to file. Please manually remove the line.")
return False
except Exception:
dberror("Unknown error occured.")
dberror("Device", "Unknown error occured.")
return False

dberror("Could not automatically resolve any information about the error. Please See the following output.")
dberror("Device", "Could not automatically resolve any information about the error. Please See the following output.")
print(stderr)
return False

Expand All @@ -225,9 +218,9 @@ def setup(self):
'''

dbstate('Enter Device IP or hostname')
dbstate("Device", 'Enter Device IP or hostname')
ip = input('>>> ')
dbstate('enter port (leave empty for 22)')
dbstate("Device", 'enter port (leave empty for 22)')
port = input('>>> ')

if port == '':
Expand All @@ -237,13 +230,13 @@ def setup(self):

device = Device(ip, port)

dbstate('Testing Connection')
dbstate("Device", 'Testing Connection')
connected = False
if device.test_connection():
dbstate('Connected!')
dbstate("Device", 'Connected!')
connected = True
else:
dbwarn('Connection failed, add it anyways? (y/n)')
dbwarn("Device", 'Connection failed, add it anyways? (y/n)')
if 'y' not in input('> ').lower():
return

Expand All @@ -258,14 +251,14 @@ def setup(self):
if success:
break
if success:
dbstate("Successfully resolved issue")
dbstate("Device", "Successfully resolved issue")
else:
dberror("Could not resolve known_hosts issue.")
dberror("Device", "Could not resolve known_hosts issue.")

if not device.test_keybased_auth():
device.setup_key_auth()
else:
dbstate("Keybased auth already configured")
dbstate("Device", "Keybased auth already configured")

self.add_device(device)

Expand All @@ -278,21 +271,21 @@ def main():
device_manager.setup()
except KeyboardInterrupt:
print()
dbstate('Cancelled')
dbstate("Device", 'Cancelled')
if 'run' in sys.argv[1]:
device_manager.current.run_cmd(' '.join(sys.argv[2:]))
if 'qr' in sys.argv[1]:
device_manager.current.run_cmd(' '.join(sys.argv[2:]), quiet=True)
if 'get' in sys.argv[1]:
device_manager.current.export_ip()
if 'test' in sys.argv[1]:
dbstate('Testing Connection')
dbstate("Device", 'Testing Connection')
if device_manager.current.test_connection():
dbstate('Connected!')
dbstate("Device", 'Connected!')
exit(0)
else:
dberror('Connection to device failed')
dberror('Make sure SSH is functioning properly and/or run "dragon s" to configure your device')
dberror("Device", 'Connection to device failed')
dberror("Device", 'Make sure SSH is functioning properly and/or run "dragon s" to configure your device')
exit(1)


Expand Down
27 changes: 10 additions & 17 deletions src/dragon/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,19 @@

# if you're here to contribute to this file, im sorry. ::::)

import os, sys, pwd, pprint
import os, sys, pwd
import ruyaml as yaml
from .util import dprintline, OutputColors, OutputWeight

dbstate = lambda msg: dprintline(label_color=OutputColors.Green, tool_name="Project Editor",
text_color=OutputColors.White, text_weight=OutputWeight.Bold, pusher=False, msg=msg)
dbwarn = lambda msg: dprintline(label_color=OutputColors.Yellow, tool_name="Project Editor",
text_color=OutputColors.White, text_weight=OutputWeight.Normal, pusher=False, msg=msg)
dberror = lambda msg: dprintline(label_color=OutputColors.Red, tool_name="Project Editor",
text_color=OutputColors.White, text_weight=OutputWeight.Bold, pusher=False, msg=msg)
from shared.util import dbstate


def get_input(prompt, default):
dbstate(f'{prompt} ({default})')
dbstate("Project Editor", f'{prompt} ({default})')
ret = input('>> ')
return ret if ret.strip() else default


def get_from_selector(prompt, values, default):
dbstate(prompt)
dbstate("Project Editor", prompt)
itemlist = []
for i, key in enumerate(values):
print(f'[{i}] > {key}')
Expand Down Expand Up @@ -430,9 +423,9 @@ def __init__(self, root_directory):
self.variables = {}

def create_new(self):
dbstate('-=-=============================')
dbstate('Creating new Package')
dbstate('-=-=============================')
dbstate("Project Editor", '-=-=============================')
dbstate("Project Editor", 'Creating new Package')
dbstate("Project Editor", '-=-=============================')
self.variables['name'] = get_input('Project Name', self.directory_name)
self.variables['id'] = get_input('Bundle ID', f'com.{self.current_username}.{self.directory_name}')
self.variables['depends'] = 'mobilesubstrate'
Expand All @@ -455,9 +448,9 @@ def __init__(self, variables=None):
self.name = ''

def create_new(self, proj_root):
dbstate('-=-=============================')
dbstate('Creating new Module')
dbstate('-=-=============================')
dbstate("Project Editor", '-=-=============================')
dbstate("Project Editor", 'Creating new Module')
dbstate("Project Editor", '-=-=============================')
self.variables['type'] = get_from_selector('Select Module Type', {'Tweak': 'tweak', 'App': 'app',
'CLI Tool': 'cli', 'Library': 'library',
'Preference Bundle': 'prefs',
Expand Down
64 changes: 1 addition & 63 deletions src/dragon/util.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
#!/usr/bin/env python3

import os.path as path
from enum import IntEnum
import pkg_resources
import sys

DRAGONBUILD_VERSION = pkg_resources.get_distribution('dragon').version


def version() -> str:
return DRAGONBUILD_VERSION
return pkg_resources.get_distribution('dragon').version


def tool_path() -> str:
Expand All @@ -18,61 +14,3 @@ def tool_path() -> str:

def deployable_path() -> str:
return path.dirname(__file__) + '/config/'


colors = [["\033[0;31m", "\033[0;32m", "\033[0;33m", "\033[0;34m", "\033[0;36m",
"\033[0;37m", "\033[0m"], ["\033[1;31m", "\033[1;32m", "\033[1;33m", "\033[1;34m",
"\033[1;36m", "\033[1;37m", "\033[0m"]]


class OutputColors(IntEnum):
Black = 30
Red = 31
Green = 32
Yellow = 33
Blue = 34
Magenta = 35
Cyan = 36
White = 37


class OutputWeight(IntEnum):
Normal = 0
Bold = 1


def color_string(output_color, output_weight):
return f'\033[{str(output_weight.value)};{str(output_color.value)}m'


def dprintline(label_color: OutputColors, tool_name: str, text_color: OutputColors, text_weight: OutputWeight,
pusher: bool, msg: str):
print("%s[%s]%s %s%s%s" % (
color_string(label_color, OutputWeight.Bold), tool_name, color_string(text_color, text_weight),
">>> " if pusher else "", msg, colors[0][6]))


class ShellHarnessAdapter:
def __init__(self):
pass

@staticmethod
def echo(string):
print(f'echo -e "{string}"', file=sys.stdout)

@staticmethod
def printline(label_color: OutputColors, tool_name: str, text_color: OutputColors, text_weight: OutputWeight,
pusher: bool, msg: str):
output_string = "%s[%s]%s %s%s%s" % (
color_string(label_color, OutputWeight.Bold), tool_name, color_string(text_color, text_weight),
">>> " if pusher else "", msg, colors[0][6])
ShellHarnessAdapter.echo(output_string)

def dprintline(col: int, tool: str, textcol: int, bold: int, pusher: int, msg: str):
ShellHarnessAdapter.echo("%s[%s]%s %s%s%s" % (
colors[1][col], tool, colors[bold][textcol], ">>> " if pusher
else "", msg, colors[0][6]))

@staticmethod
def run(cmd: str):
print(f'{cmd}')
18 changes: 2 additions & 16 deletions src/dragongen/bfilter.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,7 @@
#!/usr/bin/env python3

import yaml, os, sys

colors = [["\033[0;31m", "\033[0;32m", "\033[0;33m", "\033[0;34m", "\033[0;36m",
"\033[0;37m", "\033[0m"], ["\033[1;31m", "\033[1;32m", "\033[1;33m", "\033[1;34m",
"\033[1;36m", "\033[1;37m", "\033[0m"]]


def dprintline(col: int, tool: str, textcol: int, bold: int, pusher: int, msg: str):
print("%s[%s]%s %s%s%s" % (
colors[1][col], tool, colors[bold][textcol], ">>> " if pusher else "", msg, colors[0][6]))


dbstate = lambda msg: dprintline(1, "Packager", 5, 1, 0, msg)
dbwarn = lambda msg: dprintline(2, "Packager", 5, 0, 0, msg)
dberror = lambda msg: dprintline(0, "Packager", 5, 1, 0, msg)

# from shared.util import dbstate

# This script will get called w/
# argc=3 argv[0] argv[1] argv[2]
Expand All @@ -26,7 +12,7 @@ def main():
with open(sys.argv[1]) as f:
config = yaml.safe_load(f)

# dbstate("Creating Filter for " + sys.argv[2])
# dbstate("Packager", "Creating Filter for " + sys.argv[2])

filter_dict = config[sys.argv[2]]['filter']
print(filter_serialize(filter_dict))
Expand Down
Loading

0 comments on commit 114a4d2

Please sign in to comment.