Skip to content

Commit

Permalink
Merge pull request #36 from VocalFan/main
Browse files Browse the repository at this point in the history
Go from OS to Pathlib
  • Loading branch information
gusborg88 authored May 23, 2024
2 parents e5071f6 + 95a834a commit 2bc1bde
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 70 deletions.
51 changes: 51 additions & 0 deletions .github/workflows/pr-builds.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: FNF Porter Build

on:
pull_request:
branches: [ "main" ]

permissions:
contents: read

jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-latest, macos-latest, ubuntu-latest]
include:
- os: windows-latest
icon: icon.ico
ext: .exe
- os: macos-latest
icon: icon.icns
ext:
- os: ubuntu-latest
icon: ""
ext:

steps:
- uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Cache pip
uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pyinstaller numpy pydub luaparser pyqt6
- name: Build with PyInstaller
run: |
pyinstaller --onefile setup.py --icon=${{ matrix.icon }} --noconsole -n "FNF Porter PR-${{ github.event.pull_request.number }}"
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: FNF_Porter_Build_${{ matrix.os }}
path: dist/*${{ matrix.ext }}
76 changes: 38 additions & 38 deletions psychtobase/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from base64 import b64decode
import json
import logging
import os
import shutil
import time
from pathlib import Path
from psychtobase.src import Constants
from psychtobase.src.tools import ModConvertTools as ModTools
import threading
Expand All @@ -20,14 +20,14 @@
vocalSplitMasterToggle = True

def folderMake(folder_path):
if not os.path.exists(folder_path):
if not Path(folder_path).exists():
try:
os.makedirs(folder_path)
Path(folder_path).mkdir(parents=True, exist_ok=True)
except Exception as e:
logging.error(f'Something went wrong: {e}')

def fileCopy(source, destination):
if os.path.exists(source):
if Path(source).exists():
try:
shutil.copyfile(source, destination)
except Exception as e:
Expand All @@ -36,12 +36,12 @@ def fileCopy(source, destination):
logging.warn(f'Path {source} doesn\'t exist.')

def treeCopy(source, destination):
if not os.path.exists(destination) and os.path.exists(source):
if not Path(destination).exists() and Path(source).exists():
try:
shutil.copytree(source, destination)
except Exception as e:
logging.error(f'Something went wrong: {e}')
elif not os.path.exists(source):
elif not Path(source).exists():
logging.warn(f'Path {source} does not exist.')

def convert(psych_mod_folder, result_folder, options):
Expand All @@ -53,7 +53,7 @@ def convert(psych_mod_folder, result_folder, options):
logging.info(options)

modName = psych_mod_folder # MOD FOLDER PSYCH ENGINE
modFoldername = os.path.basename(psych_mod_folder)
modFoldername = Path(psych_mod_folder).name

logging.info(f'Converting from{psych_mod_folder} to {result_folder}')

Expand All @@ -64,7 +64,7 @@ def convert(psych_mod_folder, result_folder, options):
psychPackJson = dir[0]
polymodMetaDir = dir[1]

if os.path.exists(f'{modName}{psychPackJson}'):
if Path(f'{modName}{psychPackJson}').exists():
polymod_meta = ModTools.convertPack(json.loads(open(f'{modName}{psychPackJson}', 'r').read()))
folderMake(f'{result_folder}/{modFoldername}/')
open(f'{result_folder}/{modFoldername}/{polymodMetaDir}', 'w').write(json.dumps(polymod_meta, indent=4))
Expand All @@ -80,7 +80,7 @@ def convert(psych_mod_folder, result_folder, options):
psychPackPng = dir[0]
polymodIcon = dir[1]

if os.path.exists(f'{modName}{psychPackPng}'):
if Path(f'{modName}{psychPackPng}').exists():
folderMake(f'{result_folder}/{modFoldername}/')
try:
fileCopy(f'{modName}{psychPackPng}', f'{result_folder}/{modFoldername}/{polymodIcon}')
Expand All @@ -103,7 +103,7 @@ def convert(psych_mod_folder, result_folder, options):
psychCredits = dir[0]
modCredits = dir[1]

if os.path.exists(f'{modName}{psychCredits}'):
if Path(f'{modName}{psychCredits}').exists():
folderMake(f'{result_folder}/{modFoldername}/')
resultCredits = ModTools.convertCredits(open(f'{modName}{psychCredits}', 'r').read())
open(f'{result_folder}/{modFoldername}/{modCredits}', 'w').write(resultCredits)
Expand All @@ -120,9 +120,9 @@ def convert(psych_mod_folder, result_folder, options):
songs = files.findAll(f'{psychChartFolder}*')

for song in songs:
# logging.info(f'Checking if {song} is a valid chart directory...')
if os.path.isdir(song):
logging.info(f'Found {song}, validating data in it')
logging.info(f'Checking if {song} is a valid chart directory...')
if Path(song).is_dir():
logging.info(f'Loading charts in {song}')

outputpath = f'{result_folder}/{modFoldername}'

Expand Down Expand Up @@ -163,10 +163,10 @@ def convert(psych_mod_folder, result_folder, options):
folderMake(f'{result_folder}/{modFoldername}{bgCharacterAssets}')

for character in files.findAll(f'{psychCharacterAssets}*'):
if not os.path.isdir(character):
if Path(character).is_file():
logging.info(f'Copying asset {character}')
try:
fileCopy(character, result_folder + f'/{modFoldername}' + bgCharacterAssets + os.path.basename(character))
fileCopy(character, result_folder + f'/{modFoldername}' + bgCharacterAssets + Path(character).name)
except Exception as e:
logging.error(f'Could not copy asset {character}: {e}')
else:
Expand All @@ -187,7 +187,7 @@ def convert(psych_mod_folder, result_folder, options):

for character in files.findAll(f'{psychCharacters}*'):
logging.info(f'Checking if {character} is a file...')
if not os.path.isdir(character) and character.endswith('.json'):
if Path(character).is_file() and character.endswith('.json'):
converted_char = CharacterObject(character, result_folder + f'/{modFoldername}' + bgCharacters)

converted_char.convert()
Expand All @@ -207,10 +207,10 @@ def convert(psych_mod_folder, result_folder, options):
folderMake(f'{result_folder}/{modFoldername}{bgCharacterAssets}')

for character in files.findAll(f'{psychCharacterAssets}*'):
if not os.path.isdir(character):
if Path(character).is_file():
logging.info(f'Copying asset {character}')
try:
fileCopy(character, result_folder + f'/{modFoldername}' + bgCharacterAssets + os.path.basename(character))
fileCopy(character, result_folder + f'/{modFoldername}' + bgCharacterAssets + Path(character).name)
except Exception as e:
logging.error(f'Could not copy asset {character}: {e}')
else:
Expand All @@ -231,25 +231,25 @@ def convert(psych_mod_folder, result_folder, options):
_allSongFiles = files.findAll(f'{psychSongs}*')

for song in _allSongFiles:
_songKeyUnformatted = os.path.basename(song)
_songKeyUnformatted = Path(song).name
songKeyFormatted = _songKeyUnformatted.replace(' ', '-').lower()

_allSongFilesClear = [os.path.basename(__song) for __song in _allSongFiles]
_allSongFilesClear = [Path(__song).name for __song in _allSongFiles]
isPsych073Song = 'Voices-Opponent.ogg' in _allSongFilesClear and 'Voices-Player.ogg' in _allSongFilesClear

logging.info(f'Checking if {song} is a valid song directory...')
if os.path.isdir(song):
if Path(song).is_dir():
logging.info(f'Copying files in {song}')
for songFile in files.findAll(f'{song}/*'):
if os.path.basename(songFile) == 'Inst.ogg' and songOptions['inst']:
if Path(songFile).name == 'Inst.ogg' and songOptions['inst']:
logging.info(f'Copying asset {songFile}')
try:
folderMake(f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}')
fileCopy(songFile,
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{os.path.basename(songFile)}')
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{Path(songFile).name}')
except Exception as e:
logging.error(f'Could not copy asset {songFile}: {e}')
elif os.path.basename(songFile) == 'Voices.ogg' and songOptions['split'] and vocalSplitMasterToggle and not isPsych073Song:
elif Path(songFile).name == 'Voices.ogg' and songOptions['split'] and vocalSplitMasterToggle and not isPsych073Song:
# Vocal Split
songKey = _songKeyUnformatted

Expand Down Expand Up @@ -281,7 +281,7 @@ def convert(psych_mod_folder, result_folder, options):
try:
folderMake(f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}')
fileCopy(songFile,
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{os.path.basename(songFile)}')
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{Path(songFile).name}')
except Exception as e:
logging.error(f'Could not copy asset {songFile}: {e}')
elif isPsych073Song:
Expand All @@ -296,9 +296,9 @@ def convert(psych_mod_folder, result_folder, options):

if chart != None:
try:
if os.path.basename(songFile) == 'Voices-Player.ogg':
if Path(songFile).name == 'Voices-Player.ogg':
fileCopy(songFile, f"{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/Voices-{chart.metadata['playData']['characters'].get('player')}.ogg")
elif os.path.basename(songFile) == 'Voices-Opponent.ogg':
elif Path(songFile).name == 'Voices-Opponent.ogg':
fileCopy(songFile, f"{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/Voices-{chart.metadata['playData']['characters'].get('opponent')}.ogg")

except Exception as e:
Expand All @@ -307,7 +307,7 @@ def convert(psych_mod_folder, result_folder, options):
logging.warning(f'{songKeyFormatted} is a Psych Engine 0.7.3 song with separated vocals. Copy rename was attempted, however your chart was not found. These files will be copied instead.')
## Psst! If you were taken here, your chart is needed to set your character to the file!
fileCopy(songFile,
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{os.path.basename(songFile)}')
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{Path(songFile).name}')

elif songOptions['voices']:
logging.info(f'Copying asset {songFile}')
Expand All @@ -317,7 +317,7 @@ def convert(psych_mod_folder, result_folder, options):
try:
folderMake(f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}')
fileCopy(songFile,
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{os.path.basename(songFile)}')
f'{result_folder}/{modFoldername}{bgSongs}{songKeyFormatted}/{Path(songFile).name}')
except Exception as e:
logging.error(f'Could not copy asset {songFile}: {e}')
weekCOptions = options.get('weeks', {
Expand All @@ -338,7 +338,7 @@ def convert(psych_mod_folder, result_folder, options):
logging.info(f'Loading {week} into the converter...')

weekJSON = json.loads(open(week, 'r').read())
week_filename = os.path.basename(week)
week_filename = Path(week).name
converted_week = WeekTools.convert(weekJSON, modName, week_filename)
open(f'{result_folder}/{modFoldername}{baseLevels}{week_filename}', 'w').write(json.dumps(converted_week, indent=4))

Expand All @@ -356,7 +356,7 @@ def convert(psych_mod_folder, result_folder, options):
try:
folderMake(f'{result_folder}/{modFoldername}{baseLevels}')
fileCopy(asset,
f'{result_folder}/{modFoldername}{baseLevels}{os.path.basename(asset)}')
f'{result_folder}/{modFoldername}{baseLevels}{Path(asset).name}')
except Exception as e:
logging.error(f'Could not copy asset {asset}: {e}')

Expand All @@ -373,7 +373,7 @@ def convert(psych_mod_folder, result_folder, options):
try:
folderMake(f'{result_folder}/{modFoldername}{baseLevels}')
fileCopy(asset,
f'{result_folder}/{modFoldername}{baseLevels}{os.path.basename(asset)}')
f'{result_folder}/{modFoldername}{baseLevels}{Path(asset).name}')
except Exception as e:
logging.error(f'Could not copy asset {asset}: {e}')

Expand All @@ -389,21 +389,21 @@ def convert(psych_mod_folder, result_folder, options):
logging.info(f'Converting {asset}')
folderMake(f'{result_folder}/{modFoldername}{baseStages}')
stageJSON = json.loads(open(asset, 'r').read())
assetPath = f'{result_folder}/{modFoldername}{baseStages}{os.path.basename(asset)}'
assetPath = f'{result_folder}/{modFoldername}{baseStages}{Path(asset).name}'

stageLua = asset.replace('.json', '.lua')
logging.info(f'Parsing .lua with matching .json name: {stageLua}')

luaProps = []
if os.path.exists(stageLua):
if Path(stageLua).exists():
logging.info(f'Parsing {stageLua} and attempting to extract methods and calls')
try:
luaProps = StageLuaParse.parseStage(stageLua)
except Exception as e:
logging.error(f'Could not complete parsing of {stageLua}: {e}')

logging.info(f'Converting Stage JSON')
stageJSONConverted = json.dumps(StageTool.convert(stageJSON, os.path.basename(asset), luaProps), indent=4)
stageJSONConverted = json.dumps(StageTool.convert(stageJSON, Path(asset).name, luaProps), indent=4)
open(assetPath, 'w').write(stageJSONConverted)

if options.get('images'): # Images include XMLs
Expand All @@ -417,9 +417,9 @@ def convert(psych_mod_folder, result_folder, options):
for asset in allimagesandfolders:
logging.info(f'Checking on {asset}')

if os.path.isdir(asset):
if Path(asset).is_dir():
logging.info(f'{asset} is directory, checking if it should be excluded...')
folderName = os.path.basename(asset)
folderName = Path(asset).name
if not folderName in Constants.EXCLUDE_FOLDERS_IMAGES['PsychEngine']:
logging.info(f'{asset} is not excluded... attempting to copy.')
try:
Expand All @@ -437,7 +437,7 @@ def convert(psych_mod_folder, result_folder, options):
logging.info(f'{asset} is file, copying')
try:
folderMake(f'{result_folder}/{modFoldername}{baseImages}')
fileCopy(asset, f'{result_folder}/{modFoldername}{baseImages}{os.path.basename(asset)}')
fileCopy(asset, f'{result_folder}/{modFoldername}{baseImages}{Path(asset).name}')
except Exception as e:
logging.error(f'Failed to copy {asset}: {e}')

Expand Down
8 changes: 4 additions & 4 deletions psychtobase/src/Paths.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
import os
from pathlib import Path

class Paths:
assetsDir = ''
Expand All @@ -17,8 +17,8 @@ def getLibraryPath(file:str, library:str = 'preload'):
return Paths.getPreloadPath(file)
return Paths.getLibraryPathForce(file, library)

getLibraryPathForce = staticmethod(lambda file, library : os.path.join(Paths.assetsDir, library, file))
getPreloadPath = staticmethod(lambda file : os.path.join(Paths.assetsDir, file))
getLibraryPathForce = staticmethod(lambda file, library: Paths.assetsDir / library / file)
getPreloadPath = staticmethod(lambda file: Paths.assetsDir / Path(file))

txt = staticmethod(lambda key, library=None: Paths.getPath(f'{key}.txt', library))
xml = staticmethod(lambda key, library=None: Paths.getPath(f'{key}.xml', library))
Expand Down Expand Up @@ -50,4 +50,4 @@ def openTextFile(file: str):

@staticmethod
def join(*path) -> str:
return os.path.join(*path)
return str(Path(path[0]).joinpath(*path[1:]))
9 changes: 5 additions & 4 deletions psychtobase/src/files.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from glob import glob
import logging
from os import path, makedirs
from pathlib import Path

def removeTrail(filename):
return filename.replace('.json', '')
Expand All @@ -12,6 +12,7 @@ def findAll(folder):
logging.info(f'Finding all files or directories with glob: {folder}')
return glob(folder)

def folderMake(folder_path): #Sorry Tom but I'm dumb and not patient!
if not path.exists(folder_path):
makedirs(folder_path)
def folderMake(folder_path):
folder = Path(folder_path)
if not folder.exists():
folder.mkdir(parents=True)
Loading

0 comments on commit 2bc1bde

Please sign in to comment.