Skip to content

Commit

Permalink
init json stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
ezio416 committed Feb 1, 2024
1 parent 08b1346 commit 39d89dd
Show file tree
Hide file tree
Showing 7 changed files with 136 additions and 11 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "py416"
version = "0.61"
version = "0.62"
authors = [
{ name="Ezio416", email="[email protected]" },
]
Expand Down
6 changes: 3 additions & 3 deletions src/py416/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
Name: py416
Author: Ezio416
Created: 2022-08-15
Updated: 2023-03-14
Version: 0.60
Updated: 2024-01-31
Version: 0.62
A collection of various functions
'''
from .general import *
__version__ = 0, 60
__version__ = 0, 62
v = __version__
4 changes: 3 additions & 1 deletion src/py416/files.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'''
| Author: Ezio416
| Created: 2022-08-16
| Updated: 2023-03-14
| Updated: 2024-01-31
- Functions for filesystem and path string manipulation
Expand Down Expand Up @@ -961,6 +961,8 @@ def splitpath(path: str) -> tuple:
path = getcwd()
elif path == '..': # parent of current directory
path = forslash(os.path.dirname(getcwd()))
elif path == '.' * len(path): # >2 dots - current directory
path = getcwd()
elif (parts := path.split('/'))[-1] == '.': # folder/. is just folder
path = path[:-2]
elif parts[-1] == '..': # parent of path
Expand Down
79 changes: 79 additions & 0 deletions src/py416/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
'''
| Author: Ezio416
| Created: 2024-01-31
| Updated: 2024-01-31
- Functions for interacting with json objects
'''
import json
import os

from .files import getpath, listdir


def pretty(path: str = '.', indent: int = 4, sort_keys: bool = True, overwrite: bool = True) -> int:
'''
- takes one or more .json files and makes them human-readable
- will only work on files ending with .json, all other files are skipped
- appends '_pretty' to the end of the base filename, i.e. 'data.json' becomes 'data_pretty.json'
- skips files already ending with '_pretty.json' - we assume those are already done
Parameters
----------
path: str
- path to file or folder to work on
- if a file, will only do that file
- if a folder, will do every file in that folder
- does not search subfolders
- default: current working directory
indent: int
- number of spaces to indent by
- default: 4
sort_keys: bool
- whether to sort keys
- default: True
overwrite: bool
- whether to overwrite a '_pretty.json' if it already exists
- default: True
Returns
-------
int
- number of files that were formatted
'''
if path == '.':
files: tuple[str] = tuple(getpath(f) for f in listdir(dirs=False))
else:
if os.path.exists(path):
if os.path.isdir(path):
files: tuple[str] = tuple(getpath(file) for file in listdir(path, dirs=False))
elif os.path.isfile(path):
files: tuple[str] = tuple(getpath(path))
else:
print(f'invalid path given: {path}')
return

total: int = 0

for file in files:
parts: list[str] = file.split('.')
pre_ext: str = '.'.join(parts[:-1])
ext: str = parts[-1]

if pre_ext.endswith('_pretty') or ext != 'json':
continue

with open(file, 'r') as f:
contents: dict = json.loads(f.read())

new_file: str = pre_ext + '_pretty.json'

if not overwrite and os.path.exists(new_file):
continue

with open(new_file, 'w') as f:
json.dump(contents, f, indent=indent, sort_keys=sort_keys)

total += 1

return total
29 changes: 28 additions & 1 deletion src/py416/scripts.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,41 @@
'''
| Author: Ezio416
| Created: 2023-03-14
| Updated: 2023-03-14
| Updated: 2024-01-31
- Functions behind console scripts
- Call these functions directly by name from the command line
'''
import sys

from .files import rmdir, unzipdir
from .json import pretty


# def jsp():
# '''
# - takes one or more .json files and makes them human-readable
# - will only work on files ending with .json, all other files are ignored

# Flags
# ---------
# - -p, --path (str): path to file/folder (default current working directory)
# - if a file, will only do that file
# - if a folder, will do every file in that folder
# - -i, --indent (int): number of spaces to indent by (default 4)
# - -b, --sort_keys (bool): whether to sort keys (default True)
# '''
# if len(sys.argv) > 1:
# args: list = sys.argv
# args_default: list = ['', 4, True]

# if args in ('-p', '--path'):
# if len(args)

# print(f'formatted {pretty(*args_default)} .json files')
# return

# print(f'formatted {pretty()} .json files')


def rmd():
Expand Down
10 changes: 5 additions & 5 deletions tests/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def test_getcwd():
('/gfsyt/trw', '/gfsyt/trw'),
('/dir1/dir2/.', '/dir1/dir2'),
('/dir1/dir2/..', '/dir1'),
#Windows
# Windows
('D:', 'D:/'),
('D:/', 'D:/'),
('D:/test/party/time/baby', 'D:/test/party/time/baby'),
Expand All @@ -134,7 +134,7 @@ def test_getcwd():
('\\\\bdi-az-data01\\Projects', '//bdi-az-data01/Projects'),
('//bdi-az-data01/Projects/.', '//bdi-az-data01/Projects'),
('//bdi-az-data01/Projects/..', '//bdi-az-data01'),
# None
# Any
('', ''),
('folder/..', ''),
])
Expand Down Expand Up @@ -165,7 +165,7 @@ def test_getpath(i, o):
('//', '//'),
('//bdi', '//bdi'),
(('//bdi', 'drive'), '//bdi/drive'),
# None
# Any
('', ''),
(('', ''), ''),
('J', 'J'),
Expand Down Expand Up @@ -407,7 +407,7 @@ def test_move(tmp_path):
('\\\\bdi-az-data01\\Projects', '//bdi-az-data01'),
('//bdi-az-data01/Projects/.', '//bdi-az-data01'),
('//bdi-az-data01/Projects/..', '//bdi-az-data01'),
# None
# Any
('', ''),
('folder/..', ''),
])
Expand Down Expand Up @@ -487,7 +487,7 @@ def test_rmdir(tmp_path):
('\\\\bdi-az-data01\\Projects', ('//bdi-az-data01', 'Projects')),
('//bdi-az-data01/Projects/.', ('//bdi-az-data01', 'Projects')),
('//bdi-az-data01/Projects/..', ('//bdi-az-data01',)),
# None
# Any
('', ('',)),
('folder/..', ('',))
])
Expand Down
17 changes: 17 additions & 0 deletions tests/test_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import os
import sys

import pytest
import pytest_check as check

sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import src.py416.json as p4j


def test_pretty(tmp_path):
pass
# print(p4j.pretty(tmp_path))


# if __name__ == '__main__':
# test_pretty(r'C:\Users\Ezio\Code\trackmania-json-tracking')

0 comments on commit 39d89dd

Please sign in to comment.