Skip to content

Commit 754a7c7

Browse files
committed
- Move run_command() to __init__()
- Rename updatemetadata() to poolmetadata() - Add/update documentation
1 parent 3c97c1b commit 754a7c7

File tree

16 files changed

+284
-428
lines changed

16 files changed

+284
-428
lines changed

bidscoin/__init__.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@
2424
import shutil
2525
import warnings
2626
import tempfile
27+
import subprocess
2728
from pathlib import Path
2829
from importlib import metadata
2930
from typing import Tuple, Union, List
31+
from logging import getLogger
3032
from .due import due, Doi
3133
try:
3234
import tomllib
@@ -40,6 +42,8 @@
4042
with open(Path(__file__).parents[1]/'pyproject.toml', 'rb') as fid:
4143
__version__ = tomllib.load(fid)['project']['version']
4244

45+
LOGGER = getLogger(__name__)
46+
4347
# Add license metadata
4448
__license__ = 'GNU General Public License v3.0 or later (GPLv3+)'
4549
__copyright__ = f"2018-{datetime.date.today().year}, Marcel Zwiers"
@@ -142,6 +146,25 @@ def lsdirs(folder: Path, wildcard: str='*') -> List[Path]:
142146
return sorted([item for item in sorted(folder.glob(wildcard)) if item.is_dir() and not is_hidden(item.relative_to(folder))])
143147

144148

149+
def run_command(command: str, success: tuple=(0,None)) -> int:
150+
"""
151+
Runs a command in a shell using subprocess.run(command, ..)
152+
153+
:param command: The command that is executed
154+
:param success: The return codes for successful operation (e,g, for dcm2niix it is (0,3))
155+
:return: The return code (e.g. 0 if the command was successfully executed (no errors), > 0 otherwise)
156+
"""
157+
158+
LOGGER.verbose(f"Command:\n{command}")
159+
process = subprocess.run(command, shell=True, capture_output=True, text=True)
160+
if process.stderr or process.returncode not in success:
161+
LOGGER.error(f"Failed to run:\n{command}\nErrorcode {process.returncode}:\n{process.stdout}\n{process.stderr}")
162+
else:
163+
LOGGER.verbose(f"Output:\n{process.stdout}")
164+
165+
return process.returncode
166+
167+
145168
def trackusage(event: str, dryrun: bool=False) -> dict:
146169
"""Sends a url GET request with usage data parameters (if tracking is allowed and we are not asleep)
147170

bidscoin/bcoin.py

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@
88
import os
99
import types
1010
import coloredlogs
11-
import inspect
1211
import logging
1312
import shutil
14-
import subprocess
1513
import sys
1614
import urllib.request
1715
import time
@@ -221,25 +219,6 @@ def reporterrors() -> str:
221219
return errors
222220

223221

224-
def run_command(command: str, success: tuple=(0,None)) -> int:
225-
"""
226-
Runs a command in a shell using subprocess.run(command, ..)
227-
228-
:param command: The command that is executed
229-
:param success: The return codes for successful operation (e,g, for dcm2niix it is (0,3))
230-
:return: The return code (e.g. 0 if the command was successfully executed (no errors), > 0 otherwise)
231-
"""
232-
233-
LOGGER.verbose(f"Command:\n{command}")
234-
process = subprocess.run(command, shell=True, capture_output=True, text=True)
235-
if process.stderr or process.returncode not in success:
236-
LOGGER.error(f"Failed to run:\n{command}\nErrorcode {process.returncode}:\n{process.stdout}\n{process.stderr}")
237-
else:
238-
LOGGER.verbose(f"Output:\n{process.stdout}")
239-
240-
return process.returncode
241-
242-
243222
def list_executables(show: bool=False) -> list:
244223
"""
245224
:param show: Print the installed console scripts if True
@@ -454,8 +433,7 @@ def test_plugin(plugin: Union[Path,str], options: dict) -> int:
454433

455434
# First test to see if we can import the plugin
456435
module = import_plugin(plugin, ('bidsmapper_plugin','bidscoiner_plugin'))
457-
if not inspect.ismodule(module):
458-
LOGGER.error(f"Invalid plugin: '{plugin}'")
436+
if module is None:
459437
return 1
460438

461439
# Then run the plugin's own 'test' routine (if implemented)

bidscoin/bids.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2530,7 +2530,7 @@ def addmetadata(bidsses: Path):
25302530
json.dump(jsondata, sidecar, indent=4)
25312531

25322532

2533-
def updatemetadata(datasource: DataSource, targetmeta: Path, usermeta: Meta, extensions: Iterable, sourcemeta: Path=Path()) -> Meta:
2533+
def poolmetadata(datasource: DataSource, targetmeta: Path, usermeta: Meta, extensions: Iterable, sourcemeta: Path=Path()) -> Meta:
25342534
"""
25352535
Load the metadata from the target (json sidecar), then add metadata from the source (json sidecar) and finally add
25362536
the user metadata (meta table). Source metadata other than json sidecars are copied over to the target folder. Special

bidscoin/bidsapps/fixmeta.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def fixmeta(bidsfolder: str, pattern: str, metadata: dict, participant: list, bi
8787

8888
# Load/copy over the source meta-data
8989
jsonfile = target.with_suffix('').with_suffix('.json')
90-
jsondata = bids.updatemetadata(datasource, jsonfile, bids.Meta({}), ['.json'])
90+
jsondata = bids.poolmetadata(datasource, jsonfile, bids.Meta({}), ['.json'])
9191
for key, value in metadata.items():
9292
if isinstance(value, list):
9393
for n in range(0, len(value), 2):

bidscoin/bidsapps/skullstrip.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from importlib.util import find_spec
2121
if find_spec('bidscoin') is None:
2222
sys.path.append(str(Path(__file__).parents[2]))
23-
from bidscoin import bcoin, bids, lsdirs, trackusage, DEBUG
23+
from bidscoin import bcoin, bids, lsdirs, trackusage, run_command, DEBUG
2424
from bidscoin.due import due, Doi
2525

2626

@@ -141,7 +141,7 @@ def skullstrip(bidsfolder: str, pattern: str, participant: list, masked: str, ou
141141
jt.outputPath = f"{os.getenv('HOSTNAME')}:{Path.cwd() if DEBUG else tempfile.gettempdir()}/{jt.jobName}.out"
142142
jobids.append(pbatch.runJob(jt))
143143
LOGGER.info(f"Your skullstrip job has been submitted with ID: {jobids[-1]}")
144-
elif bcoin.run_command(f"mri_synthstrip -i {srcimg} -o {outputimg} -m {maskimg} {args}"):
144+
elif run_command(f"mri_synthstrip -i {srcimg} -o {outputimg} -m {maskimg} {args}"):
145145
continue
146146

147147
# Add a json sidecar-file with the "SkullStripped" field

bidscoin/plugins/README

Lines changed: 0 additions & 175 deletions
This file was deleted.

0 commit comments

Comments
 (0)