Skip to content

Commit

Permalink
wip: migrating code to pathlib
Browse files Browse the repository at this point in the history
  • Loading branch information
newville committed Aug 15, 2024
1 parent ee95703 commit 98c5d76
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 41 deletions.
18 changes: 8 additions & 10 deletions larch/apps.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"""
main Larch Applications
"""
import os
import sys
import locale
import inspect
import shutil
from argparse import ArgumentParser

from pathlib import Path

import matplotlib
from pyshortcuts import make_shortcut, ico_ext, get_desktop
Expand Down Expand Up @@ -53,17 +52,16 @@ def __init__(self, name, script, icon=None, description=None,
def make_desktop_shortcut(self, folder='Larch'):
"""make (or remake) desktop shortcuts for Larch apps"""
bindir = 'Scripts' if uname == 'win' else 'bin'
bindir = os.path.join(sys.prefix, bindir)
bindir = Path(sys.prefix, bindir).absolute()
script = self.script
if not self.script.startswith('_'):
script = os.path.normpath(os.path.join(bindir, self.script))

script = Path(bindir, self.script).absolute()

icon = os.path.join(icondir, self.icon)
icon = Path(icondir, self.icon)
if isinstance(ico_ext, (list, tuple)):
for ext in ico_ext:
ticon = f"{self.icon:s}.{ext:s}"
if os.path.exists(ticon):
if Path(ticon).exists():
icon = ticon

make_shortcut(script, name=self.name, folder=folder, icon=icon,
Expand All @@ -83,7 +81,7 @@ def prep_cli(self):
args = parser.parse_args()
self.filename = None
if 'filename' in args and args.filename is not None:
self.filename = os.path.abspath(args.filename)
self.filename = Path(args.filename).absolute()
self.wx_inspect = args.wx_inspect
self.run_mode = args.run_mode
if self.is_wxapp:
Expand Down Expand Up @@ -237,8 +235,8 @@ def run_larch():

# create desktop icons
if args.makeicons:
larchdir = os.path.join(get_desktop(), 'Larch')
if os.path.exists(larchdir):
larchdir = Path(get_desktop(), 'Larch').absolute()
if Path(larchdir).exists()
shutil.rmtree(larchdir)

for n, app in LarchApps.items():
Expand Down
3 changes: 2 additions & 1 deletion larch/inputText.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from __future__ import print_function
import os
from pathlib import Path
import sys
import time
from collections import deque
Expand Down Expand Up @@ -152,7 +153,7 @@ def clear(self):
def load(self, filename=None):
if filename is not None:
self.filename = filename
if os.path.exists(self.filename):
if Path(filename).exists():
self.clear()
text = read_textfile(filename).split('\n')
for hline in text:
Expand Down
9 changes: 5 additions & 4 deletions larch/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
numpy functions are imported if available and used.
"""
import os
from pathlib import Path
import sys
import types
import ast
Expand Down Expand Up @@ -400,7 +401,7 @@ def show_errors(self):

def run_init_scripts(self):
for fname in site_config.init_files:
if os.path.exists(fname):
if Path(fname).exists():
try:
self.runfile(fname)
except:
Expand Down Expand Up @@ -1048,7 +1049,7 @@ def import_module(self, name, asname=None,
"""
st_sys = self.symtable._sys
for idir in st_sys.path:
if idir not in sys.path and os.path.exists(idir):
if idir not in sys.path and Path(idir).exists():
sys.path.append(idir)

# step 1 import the module to a global location
Expand All @@ -1066,11 +1067,11 @@ def import_module(self, name, asname=None,
islarch = False
larchname = "%s.lar" % name
for dirname in st_sys.path:
if not os.path.exists(dirname):
if not Path(dirname).exists():
continue
if larchname in sorted(os.listdir(dirname)):
islarch = True
modname = os.path.abspath(os.path.join(dirname, larchname))
modname = Path(dirname, larchname).absolute()
try:
thismod = self.runfile(modname, new_module=name)
except:
Expand Down
29 changes: 15 additions & 14 deletions larch/larchlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"""
Helper classes for larch interpreter
"""
from __future__ import division
import sys, os, time
from datetime import datetime
import ast
Expand All @@ -11,6 +10,8 @@
import toml
import inspect
from collections import namedtuple
from pathlib import Path

import ctypes
import ctypes.util

Expand Down Expand Up @@ -132,9 +133,9 @@ def get_error(self):
for tb in traceback.extract_tb(self.exc_info[2]):
if not (sys.prefix in tb[0] and
('ast.py' in tb[0] or
os.path.join('larch', 'utils') in tb[0] or
os.path.join('larch', 'interpreter') in tb[0] or
os.path.join('larch', 'symboltable') in tb[0])):
Path('larch', 'utils') in tb[0] or
Path('larch', 'interpreter') in tb[0] or
Path('larch', 'symboltable') in tb[0])):
tblist.append(tb)
if len(tblist) > 0:
out.append(''.join(traceback.format_list(tblist)))
Expand Down Expand Up @@ -352,7 +353,7 @@ def add2path(envvar='PATH', dirname='.'):
os.environ[envvar] = dirname
else:
paths = oldpath.split(sep)
paths.insert(0, os.path.abspath(dirname))
paths.insert(0, Path(dirname).absolute())
os.environ[envvar] = sep.join(paths)
return oldpath

Expand All @@ -377,13 +378,13 @@ def get_dll(libname):
# normally, we expect the dll to be here in the larch dlls tree
# if we find it there, use that one
fname = _dylib_formats[uname] % libname
dllpath = os.path.join(bindir, fname)
if os.path.exists(dllpath):
dllpath = Path(bindir, fname)
if Path(dllpath).exists():
return loaddll(dllpath)

# if not found in the larch dlls tree, try your best!
dllpath = ctypes.util.find_library(libname)
if dllpath is not None and os.path.exists(dllpath):
if dllpath is not None and Path(dllpath).exists():
return loaddll(dllpath)
return None

Expand All @@ -397,8 +398,8 @@ def read_workdir(conffile):
"""

try:
w_file = os.path.join(user_larchdir, conffile)
if os.path.exists(w_file):
w_file = Path(user_larchdir, conffile).absolute()
if Path(w_file).exists():
line = open(w_file, 'r').readlines()
workdir = line[0][:-1]
os.chdir(workdir)
Expand All @@ -414,7 +415,7 @@ def save_workdir(conffile):
"""

try:
w_file = os.path.join(user_larchdir, conffile)
w_file = Path(user_larchdir, conffile).absolute()
fh = open(w_file, 'w', encoding=sys.getdefaultencoding())
fh.write("%s\n" % get_cwd())
fh.close()
Expand All @@ -428,9 +429,9 @@ def read_config(conffile):
returns dictionary / configuration
"""
cfile = os.path.join(user_larchdir, conffile)
cfile = Path(user_larchdir, conffile).absolute()
out = None
if os.path.exists(cfile):
if Path(cfile).exists():
data = read_textfile(cfile)
try:
out = toml.loads(data)
Expand All @@ -443,7 +444,7 @@ def save_config(conffile, config):
compare read_confif(conffile) which will read this value
"""
cfile = os.path.join(user_larchdir, conffile)
cfile = Path(user_larchdir, conffile).absolute()
dat = toml.dumps(config).encode('utf-8')
with open(cfile, 'wb') as fh:
fh.write(dat)
Expand Down
23 changes: 11 additions & 12 deletions larch/site_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"""
import sys
import os
import importlib.metadata
from pathlib import Path

from subprocess import check_call, CalledProcessError, TimeoutExpired

from packaging.version import parse as version_parse
Expand All @@ -24,7 +25,7 @@

def pjoin(*args):
"simple join"
return nativepath(os.path.join(*args))
return Path(*args).absolute()

def update_larch(with_larix=True):
"pip upgrade larch"
Expand All @@ -36,30 +37,28 @@ def update_larch(with_larix=True):
# = get_homedir() + 'larch' (#win)
home_dir = get_homedir()

here, i_am = os.path.split(__file__)
icondir = os.path.join(here, 'icons')
icondir = Path(Path(__file__).parent, 'icons').absolute()

user_larchdir = pjoin(home_dir, '.larch')
if uname == 'win':
user_larchdir = unixpath(pjoin(home_dir, 'larch'))
user_larchdir = pjoin(home_dir, 'larch')

if 'LARCHDIR' in os.environ:
user_larchdir = nativepath(os.environ['LARCHDIR'])

# on Linux, check for HOME/.local/share,
# make with mode=711 if needed
if uname in ('linux', 'darwin') and os.getuid() > 0:
lshare = os.path.join(home_dir, '.local', 'share')
if not os.path.exists(lshare):
os.makedirs(lshare, mode=457) # for octal 711
lshare = Path(home_dir, '.local', 'share').absolute()
lshare.mkdir(mode=457, parents=True, exist_ok=True) # for octal 711


# initialization larch files to be run on startup
init_files = [pjoin(user_larchdir, 'init.lar')]

if 'LARCHSTARTUP' in os.environ:
startup = os.environ['LARCHSTARTUP']
if os.path.exists(startup):
if Path(startup).exists():
init_files = [nativepath(startup)]

# history file:
Expand All @@ -78,17 +77,17 @@ def make_user_larchdirs():

def make_dir(dname):
"create directory"
if not os.path.exists(dname):
if not Path(dname).exists():
try:
os.mkdir(dname, mode=493)
Path(dname).mkdir(mode=493, parents=True)
except PermissionError:
log_warning(f'no permission to create directory {dname}')
except (OSError, TypeError):
log_error(sys.exc_info()[1])

def write_file(fname, text):
"write wrapper"
if not os.path.exists(fname):
if not Path(fname).exists():
try:
with open(fname, 'w', encoding=sys.getdefaultencoding()) as fileh:
fileh.write(f'# {text}\n')
Expand Down

0 comments on commit 98c5d76

Please sign in to comment.