feat: Logging works

This commit is contained in:
Sayantan Santra 2023-08-10 14:50:42 -05:00
parent c1451bcc37
commit c56a97c733
Signed by: SinTan1729
GPG key ID: EB3E68BFBA25C85F
4 changed files with 66 additions and 23 deletions

View file

@ -1,10 +1,12 @@
import os import os
import sys import sys
from Notifications import send_notif from Notifications import send_notif
import time
# Move apps to proper location # Move apps to proper location
def move_apps(appstate): def move_apps(appstate):
build_config = appstate['build_config'] build_config = appstate['build_config']
print = appstate['logger'].info
try: try:
os.mkdir('archive') os.mkdir('archive')
@ -24,8 +26,8 @@ def move_apps(appstate):
# sys.exit('There was an error moving the final apk files!') # sys.exit('There was an error moving the final apk files!')
# Do some cleanup, keep only the last 3 build's worth of files and a week worth of logs # Do some cleanup, keep only the last 3 build's worth of files and a week worth of logs
with os.scandir('archive') as dir:
files = [] files = []
dir = os.scandir('archive')
for f in dir: for f in dir:
if name in f.name: if name in f.name:
files.append(f) files.append(f)
@ -34,10 +36,23 @@ def move_apps(appstate):
for f in files[3:]: for f in files[3:]:
os.remove(f) os.remove(f)
print('Deleted old build '+f.name) print('Deleted old build '+f.name)
dir.close()
# Delete logs older than 7 days
with os.scandir('logs') as dir:
now = time.now()
for f in dir:
if f.stat().st_ctime < now - 7 * 86400:
os.remove(f)
def clean_exit(msg, appstate, code=1): def clean_exit(msg, appstate, code=1):
print = appstate['logger'].info
try:
appstate['notification_config']
send_notif(appstate, error=True) send_notif(appstate, error=True)
except:
pass
if msg: if msg:
print(msg, file=sys.stderr) print(msg)
exit(code) exit(code)

View file

@ -2,13 +2,14 @@ import os
import sys import sys
import configparser as cp import configparser as cp
import json import json
import subprocess
from Cleanup import clean_exit from Cleanup import clean_exit
import subprocess
# Build the revanced apps # Build the revanced apps
def build_apps(appstate): def build_apps(appstate):
build_config = appstate['build_config'] build_config = appstate['build_config']
flag = appstate['flag'] flag = appstate['flag']
print = appstate['logger'].info
chosen_patches = cp.ConfigParser() chosen_patches = cp.ConfigParser()
chosen_patches.read('chosen_patches.toml') chosen_patches.read('chosen_patches.toml')
@ -69,9 +70,13 @@ def build_apps(appstate):
print(f"Building {pretty_name} (nonroot)...") print(f"Building {pretty_name} (nonroot)...")
try: try:
output = subprocess.run(cmd, shell=True) with subprocess.Popen(cmd, shell=True, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout as output:
for line in output:
line_utf = line.decode('utf-8').strip('\n')
if line_utf:
print(line_utf)
except Exception as e: except Exception as e:
clean_exit(f"There was an error while building {pretty_name}!", appstate) clean_exit(f"There was an error while building {pretty_name}!\n{e}", appstate)
try: try:
os.rename(output_name+'.apk', output_name+'.apk') # TODO: Add timestamp here os.rename(output_name+'.apk', output_name+'.apk') # TODO: Add timestamp here

View file

@ -4,7 +4,9 @@ import requests as req
import subprocess import subprocess
def send_notif(appstate, error=False): def send_notif(appstate, error=False):
print = appstate['logger'].info
timestamp = appstate['timestamp'] timestamp = appstate['timestamp']
if error: if error:
msg = f"There was an error during build! Please check the logs.\nTimestamp: {timestamp}" msg = f"There was an error during build! Please check the logs.\nTimestamp: {timestamp}"
else: else:
@ -72,9 +74,13 @@ def send_notif(appstate, error=False):
continue continue
cmd = f"./telegram.sh -t {token} -c {chat} -T {encoded_title} -M \"{msg}\"" cmd = f"./telegram.sh -t {token} -c {chat} -T {encoded_title} -M \"{msg}\""
try: try:
subprocess.run(cmd, shell=True) with subprocess.Popen(cmd, shell=True, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout as output:
for line in output:
line_utf = line.decode('utf-8').strip('\n')
if line_utf:
print(line_utf)
except Exception as e: except Exception as e:
print('Failed!' + str(e)) clean_exit(f"Failed!\n{e}", appstate)
case _: case _:
print('Don\'t know how to send notifications to ' + entry) print('Don\'t know how to send notifications to ' + entry)

View file

@ -11,9 +11,8 @@ from JAVABuilder import *
from datetime import datetime from datetime import datetime
from Notifications import send_notif from Notifications import send_notif
from Cleanup import * from Cleanup import *
import logging
# TODO: Logging
# TODO: Notifications
# TODO: Run post_script (preferably in any language) # TODO: Run post_script (preferably in any language)
# TODO: README # TODO: README
# TODO: PATCHES_GUIDE.md (maybe delete it?) # TODO: PATCHES_GUIDE.md (maybe delete it?)
@ -85,10 +84,8 @@ appstate = {}
# Get a timestamp # Get a timestamp
time = datetime.now() time = datetime.now()
appstate['timestamp'] = time.strftime('%Y%m%d%H%M%S') appstate['timestamp'] = time.strftime('%Y%m%d%H%M%S')
print(f"Started building ReVanced apps at {time.strftime('%d %B, %Y %H:%M:%S')}")
print('----------------------------------------------------------------------')
# Read configs # Read arguments
try: try:
os.chdir(sys.argv[1]) os.chdir(sys.argv[1])
except IndexError: except IndexError:
@ -96,14 +93,34 @@ except IndexError:
except FileNotFoundError: except FileNotFoundError:
clean_exit('Invalid working directory provided!', appstate) clean_exit('Invalid working directory provided!', appstate)
# Set up logging
try:
os.mkdir('logs')
except FileExistsError:
pass
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger()
logger.addHandler(logging.FileHandler(f"logs/{appstate['timestamp']}.log", 'w'))
print = logger.info
appstate['logger'] = logger
# Get the flag
try: try:
flag = sys.argv[2] flag = sys.argv[2]
except: except:
flag = None flag = None
if flag not in ['buildonly', 'checkonly', 'force', 'experimental']:
clean_exit(f"Unknown flag: {flag}", appstate)
appstate['flag'] = flag appstate['flag'] = flag
appstate['microg_updated'] = False appstate['microg_updated'] = False
print(f"Started building ReVanced apps at {time.strftime('%d %B, %Y %H:%M:%S')}")
print('----------------------------------------------------------------------')
# Read configs
try: try:
appstate['build_config']=cp.ConfigParser() appstate['build_config']=cp.ConfigParser()
appstate['build_config'].read_file(open('build_config.toml', 'r')) appstate['build_config'].read_file(open('build_config.toml', 'r'))