Switch to pathlib

This commit is contained in:
2017-06-23 20:05:10 -07:00
parent 8d8c3b84fd
commit 4b7feeebb1
2 changed files with 29 additions and 27 deletions

View File

@@ -7,6 +7,7 @@ sys.path.insert(0, '/usr/lib/python3.6/site-packages')
import requests
import json
import os
import pathlib
import ast
import argparse
import zipfile
@@ -44,28 +45,28 @@ def parse_blinfo(source: str) -> dict:
raise BadAddon('No bl_info found')
def extract_blinfo(path):
def extract_blinfo(path: pathlib.Path) -> dict:
"""Extract bl_info dict from addon at path (can be single file, module, or zip)"""
source = None
# get last component of path, including when the path ends with trailing slash
addon_name = os.path.split(path.rstrip(os.path.sep))[1]
# get last component of path
addon_name = path.parts[-1]
if os.path.isdir(path):
with open(os.path.join(path, '__init__.py'), 'r') as f:
if path.is_dir():
with open(path / '__init__.py', 'r') as f:
source = f.read()
else:
# HACK: perhaps not the best approach determining filetype..?
try:
with zipfile.ZipFile(path, 'r') as z:
with zipfile.ZipFile(str(path), 'r') as z:
for fname in z.namelist():
# HACK: this seems potentially fragile; depends on zipfile listing root contents first
if fname.endswith('__init__.py'):
source = z.read(fname)
break
except zipfile.BadZipFile:
with open(path, 'r') as f:
with path.open() as f:
source = f.read()
if source == None:
@@ -75,18 +76,18 @@ def extract_blinfo(path):
def make_repo(outpath):
"""Make repo.json for files in directory 'outpath'"""
def make_repo(repopath: pathlib.Path):
"""Make repo.json for files in directory 'repopath'"""
repo_data = {}
package_data = []
if not os.path.exists(outpath):
raise FileNotFoundError
if not repopath.is_dir():
raise FileNotFoundError(repopath)
for addon in os.listdir(outpath):
for addon_path in repopath.iterdir():
package_datum = {}
addon_path = os.path.join(outpath, addon)
addon = addon_path.parts[-1]
try:
bl_info = extract_blinfo(addon_path)
@@ -106,7 +107,7 @@ def make_repo(outpath):
repo_data['packages'] = package_data
with open(os.path.join(outpath, "repo.json"), 'w', encoding='utf-8') as repo_file:
with (repopath / 'repo.json').open('w', encoding='utf-8') as repo_file:
json.dump(repo_data, repo_file, indent=4, sort_keys=True)
@@ -122,7 +123,7 @@ if __name__ == '__main__':
make = subparsers.add_parser('make')
make.add_argument('path')
make.set_defaults(func=lambda args: make_repo(args.path))
make.set_defaults(func=lambda args: make_repo(pathlib.Path(args.path)))
args = parser.parse_args()
args.func(args)