Skip to content

Commit

Permalink
feat: v1.0.20 (#41)
Browse files Browse the repository at this point in the history
* feat: v1.0.20

* feat: v1.0.20

* feat: v1.0.20

* feat: v1.0.20

---------

Co-authored-by: ddc <ddc@users.noreply.github.com>
  • Loading branch information
ddc and ddc committed Feb 12, 2024
1 parent 200a148 commit 439ae95
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 89 deletions.
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ from ddcUtils import FileUtils
fu = FileUtils()
```

+ OPEN_FILE
+ Open the given file and returns 0 for success and 1 for failed access to the file
+ SHOW
+ Open the given file or directory in explorer or notepad and returns True for success or False for failed access
```
@staticmethod
open_file(file_path: str) -> int
show(path: str) -> bool
```

+ LIST_FILES
Expand Down Expand Up @@ -101,6 +101,14 @@ fu = FileUtils()
download_file(remote_file_url, local_file_path) -> bool
```

+ DOWNLOAD_GITHUB_DIR
+ Download directory from remote url to local and returns True or False
Need to specify the branch on remote url
example: https://github.com/ddc/ddcutils/blob/master/ddcutils/databases
```
download_github_dir(self, remote_dir_url: str, local_dir_path: str) -> bool
```
+
+ GET_EXE_BINARY_TYPE
+ Returns the binary type of the given windows EXE file
```
Expand Down Expand Up @@ -200,7 +208,7 @@ mu = MiscUtils()
+ This function will return the name of the active branch
```
@staticmethod
get_active_branch_name(default_master_branch_name: str = "master") -> str
get_active_branch_name() -> str | None
```

+ GET_CURRENT_DATE_TIME
Expand Down
82 changes: 65 additions & 17 deletions ddcUtils/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import configparser
import errno
import gzip
import json
import os
import shutil
import struct
Expand Down Expand Up @@ -88,28 +89,28 @@ def _get_section_data(self, parser: configparser.ConfigParser, section: str, fin
return final_data

@staticmethod
def open_file(file_path: str) -> int:
def show(path: str) -> bool:
"""
Open the given file and returns 0 for success or 1 for failed access to the file
:param file_path:
:return: 0 | 1
Open the given file or directory in explorer or notepad and returns True for success or False for failed access
:param path:
:return: bool
"""

if not os.path.isfile(file_path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
if not os.path.exists(path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)
try:
match OsUtils.get_os_name():
case "Windows":
os.startfile(file_path)
os.startfile(path)
return_code = 0
case "Darwin":
return_code = subprocess.call(("open", file_path))
return_code = subprocess.call(("open", path))
case _:
return_code = subprocess.call(("xdg-open", file_path))
return return_code
return_code = subprocess.call(("xdg-open", path))
return not bool(return_code)
except Exception as e:
sys.stderr.write(get_exception(e))
return 1
return False

@staticmethod
def list_files(directory: str, starts_with: str = None, ends_with: str = None) -> list:
Expand Down Expand Up @@ -250,8 +251,56 @@ def download_file(remote_file_url, local_file_path) -> bool:
if req.status_code == 200:
with open(local_file_path, "wb") as outfile:
outfile.write(req.content)
return True
except requests.HTTPError as e:
sys.stderr.write(get_exception(e))
return False

def download_github_dir(self, remote_dir_url: str, local_dir_path: str) -> bool:
"""
Download directory from remote url to local and returns True or False
Need to specify the branch on remote url
example: https://github.com/ddc/ddcutils/blob/master/ddcutils/databases
:param remote_dir_url:
:param local_dir_path:
:return:
"""

try:
if not os.path.exists(local_dir_path):
os.makedirs(local_dir_path, exist_ok=True)

req_dir = requests.get(remote_dir_url)
if req_dir.status_code == 200:
data_dict = json.loads(req_dir.content)
files_list = data_dict["payload"]["tree"]["items"]
for file in files_list:
remote_file_url = f"{remote_dir_url}/{file['name']}"
local_file_path = f"{local_dir_path}/{file['name']}"
if file["contentType"] == "directory":
self.download_github_dir(remote_file_url, local_file_path)
else:
req_file = requests.get(remote_file_url)
if req_file.status_code == 200:
data_dict = json.loads(req_file.content)
content = data_dict["payload"]["blob"]["rawLines"]
if not content:
payload = data_dict['payload']
url = (f"https://raw.githubusercontent.com/"
f"{payload['repo']['ownerLogin']}/"
f"{payload['repo']['name']}/"
"master/"
f"{payload['path']}")
req_file = requests.get(url)
with open(local_file_path, "wb") as outfile:
outfile.write(req_file.content)
else:
with open(local_file_path, "w") as outfile:
outfile.writelines([f"{line}\n" for line in content])

except Exception as e:
sys.stderr.write(get_exception(e))
return False
return True

Expand All @@ -275,22 +324,21 @@ def get_exe_binary_type(file_path: str) -> str | None:
machine = struct.unpack("<H", s)[0]
match machine:
case 332:
sys.stdout.write("IA32 (32-bit x86)")
# IA32 (32-bit x86)
binary_type = "IA32"
case 512:
sys.stdout.write("IA64 (Itanium)")
# IA64 (Itanium)
binary_type = "IA64"
case 34404:
sys.stdout.write("AMD64 (64-bit x86)")
# IAMD64 (64-bit x86)
binary_type = "AMD64"
case 452:
sys.stdout.write("ARM eabi (32-bit)")
# IARM eabi (32-bit)
binary_type = "ARM-32bits"
case 43620:
sys.stdout.write("AArch64 (ARM-64, 64-bit)")
# IAArch64 (ARM-64, 64-bit)
binary_type = "ARM-64bits"
case _:
sys.stdout.write(f"Unknown architecture {machine}")
binary_type = None
return binary_type

Expand Down
9 changes: 5 additions & 4 deletions ddcUtils/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging.handlers
import os
import sys
from .exceptions import get_exception


class Log:
Expand Down Expand Up @@ -38,15 +39,15 @@ def setup_logging(self):
try:
os.makedirs(self.dir, exist_ok=True) if not os.path.isdir(self.dir) else None
except Exception as e:
sys.stderr.write(f"[ERROR]:[Unable to create logs directory]:{str(e)}: {self.dir}\n")
sys.stderr.write(f"[ERROR]:[Unable to create logs directory]:{get_exception(e)}: {self.dir}\n")
sys.exit(1)

log_file_path = os.path.join(self.dir, f"{self.filename}.log")

try:
open(log_file_path, "a+").close()
except IOError as e:
sys.stderr.write(f"[ERROR]:[Unable to open log file for writing]:{str(e)}: {log_file_path}\n")
sys.stderr.write(f"[ERROR]:[Unable to open log file for writing]:{get_exception(e)}: {log_file_path}\n")
sys.exit(1)

_debug_formatt = ""
Expand Down Expand Up @@ -96,7 +97,7 @@ def __call__(self, source, dest):
fout.writelines(fin)
os.remove(source)
except Exception as e:
sys.stderr.write(f"[ERROR]:[Unable to zip log file]:{str(e)}: {source}\n")
sys.stderr.write(f"[ERROR]:[Unable to zip log file]:{get_exception(e)}: {source}\n")


class RemoveOldLogs:
Expand All @@ -109,7 +110,7 @@ def __init__(self, logs_dir, days_to_keep):
try:
os.remove(file_path)
except Exception as e:
sys.stderr.write(f"[ERROR]:[Unable to remove old logs]:{str(e)}: {file_path}\n")
sys.stderr.write(f"[ERROR]:[Unable to remove old logs]:{get_exception(e)}: {file_path}\n")

@staticmethod
def _is_file_older_than_x_days(file_path, days_to_keep):
Expand Down
5 changes: 2 additions & 3 deletions ddcUtils/misc_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,9 @@ def user_choice() -> input:
pass

@staticmethod
def get_active_branch_name(default_master_branch_name: str = "master") -> str:
def get_active_branch_name() -> str | None:
"""
Returns the name of the active branch
:param default_master_branch_name:
:return: str
"""

Expand All @@ -65,7 +64,7 @@ def get_active_branch_name(default_master_branch_name: str = "master") -> str:
if line[0:4] == "ref:":
return line.partition("refs/heads/")[2]
except FileNotFoundError:
return default_master_branch_name
return None

@staticmethod
def get_current_date_time() -> datetime:
Expand Down
6 changes: 2 additions & 4 deletions ddcUtils/os_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,10 @@ def is_windows() -> bool:
:return:
"""

if platform.system() == "Windows":
return True
return False
return True if platform.system().lower() == "windows" else False

@staticmethod
def get_current_path() -> Path:
def get_current_path() -> Path | None:
"""
Returns the current working directory
:return: Path
Expand Down
Loading

0 comments on commit 439ae95

Please sign in to comment.