Skip to content

utils


utils.py - Utility functions for managing Ocean4DVarNet contributions

This module provides helper functions to manage the initialization, validation, and documentation of contribution folders inside the contrib/ directory. Each contribution typically contains:

  • A pyproject.toml file with project metadata
  • A main Python file named after the contribution
  • A README.md file
  • An __init__.py file
  • A tests/ subdirectory with a test file

Key functionalities include:

  • Reading and validating pyproject.toml metadata
  • Automatically generating boilerplate files (README.md, __init__.py, etc.)
  • Synchronizing documentation folders (docs/contrib/)
  • Utility methods to check file/directory existence and list subfolders

Constants:

  • CONTRIB_DIR: Root path for contributions
  • DOCS_CONTRIB_DIR: Root path for associated documentation

This module assumes contributions follow a standardized structure and can be used in CLI scripts or tests to automate common tasks.

Dependencies:

  • Python 3.11+ (for tomllib)
  • For Python 3.6–3.10, the tomli library is used as a fallback. Ensure it is installed: pip install tomli

conftest_file_exists(contrib_path)

Check if a test file with a specific name exists in the given directory.

Args:

  • contrib_path (str): The path to the directory where the test file is expected to be located.
  • name (str): The base name of the test file (without the "test_" prefix and ".py" extension).

Returns:

  • bool: True if the test file exists, False otherwise.
Source code in scripts/utils.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def conftest_file_exists(contrib_path: str) -> bool:
    """
    Check if a test file with a specific name exists in the given directory.

    Args:

    - contrib_path (str): The path to the directory where the test file is expected to be located.
    - name (str): The base name of the test file (without the "test_" prefix and ".py" extension).

    Returns:

    - bool: True if the test file exists, False otherwise.

    """
    return os.path.exists(os.path.join(contrib_path, 'conftest.py'))

create_conftest_file(contrib_path)

Creates a conftest.py file with the necessary configuration for pytest.

This function writes a conftest.py file that ensures the root directory of the project is added to the PYTHONPATH, allowing the test suite to import modules from the scripts package.

Args:

  • contrib_path (str): The path to the contribution directory where the tests/conftest.py file will be created.
  • name (str): The name of the contribution, used for potential customization in the conftest.py file.
Source code in scripts/utils.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def create_conftest_file(contrib_path: str) -> None:
    """
    Creates a `conftest.py` file with the necessary configuration for pytest.

    This function writes a `conftest.py` file that ensures the root directory of the project is added
    to the PYTHONPATH, allowing the test suite to import modules from the `scripts` package.

    Args:

    - contrib_path (str): The path to the contribution directory where the `tests/conftest.py` file will be created.
    - name (str): The name of the contribution, used for potential customization in the `conftest.py` file.

    """

    # Path to the conftest.py file to be created
    conftest_path = os.path.join(contrib_path, 'tests', 'conftest.py')

    # Content to be inserted into the file
    content = '''"""
Pytest configuration file for the test suite.

This file ensures that the root directory of the project is added to the
PYTHONPATH, allowing the test suite to import modules from the `scripts` package.
"""

import sys
import os

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
'''

    # Open the file in write mode (it will be created if it doesn't exist)
    with open(conftest_path, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"Created {conftest_path}")

create_init_py(contrib_path, name)

Create an init.py file in the specified contribution directory.

This function generates an init.py file in the given directory path and writes a simple docstring containing the provided name.

Args:

  • contrib_path (str): The path to the contribution directory where the init.py file will be created.
  • name (str): The name to include in the docstring of the init.py file.

Returns: None

Source code in scripts/utils.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def create_init_py(contrib_path: str, name: str) -> None:
    """
    Create an __init__.py file in the specified contribution directory.

    This function generates an __init__.py file in the given directory path
    and writes a simple docstring containing the provided name.

    Args:

    - contrib_path (str): The path to the contribution directory where the
            __init__.py file will be created.
    - name (str): The name to include in the docstring of the __init__.py file.

    Returns: None

    """
    init_py_path = os.path.join(contrib_path, '__init__.py')
    with open(init_py_path, 'w', encoding='utf-8') as init_py_file:
        init_py_file.write(f"\"\"\" {name} \"\"\"\n")
    print(f"Created {init_py_path}")

create_main_py(contrib_path, name)

Create a main Python file for a contribution.

This function generates a Python file with the specified name in the given contribution path. The file will contain a basic docstring indicating it is part of the ocean4dvarnet contributions.

Args:

  • contrib_path (str): The directory path where the Python file will be created.
  • name (str): The name of the Python file (without the .py extension).

Returns: None

Source code in scripts/utils.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def create_main_py(contrib_path: str, name: str) -> None:
    """
    Create a main Python file for a contribution.

    This function generates a Python file with the specified name in the given
    contribution path. The file will contain a basic docstring indicating it
    is part of the ocean4dvarnet contributions.

    Args:

    - contrib_path (str): The directory path where the Python file will be created.
    - name (str): The name of the Python file (without the .py extension).

    Returns: None
    """
    code_path = os.path.join(contrib_path, f"{name}.py")
    # Content to be inserted into the file
    content = f'''"""ocean4dvarnet contribution {name}"""

def hello_world():
    """A simple function that returns 'Hello, World!'

    Returns:

    - str: The string 'Hello, World!'.

    """
    return "Hello, World!"
'''

    with open(code_path, 'w', encoding='utf-8') as code_file:
        code_file.write(content)
    print(f"Created {code_path}")

create_readme(contrib_path, name, description='')

Create a README.md file in the specified contribution directory.

Args:

  • contrib_path (str): The path to the contribution directory where the README.md file will be created.
  • name (str): The title to be written at the top of the README.md file.
  • description (str, optional): An optional description to include in the README.md file. Defaults to an empty string.
Source code in scripts/utils.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def create_readme(contrib_path: str, name: str, description: str = "") -> None:
    """
    Create a README.md file in the specified contribution directory.

    Args:

    - contrib_path (str): The path to the contribution directory where the README.md file will be created.
    - name (str): The title to be written at the top of the README.md file.
    - description (str, optional): An optional description to include in the README.md file.
       Defaults to an empty string.
    """
    readme_path = os.path.join(contrib_path, 'README.md')
    with open(readme_path, 'w', encoding='utf-8') as readme_file:
        readme_file.write(f"# {name}\n")
        if description:
            readme_file.write(f"{description}")
    print(f"Created {readme_path}")

create_test_file(contrib_path, name)

Create the test file for the contribution.

Args:

  • contrib_path (str): The path to the contribution directory where the test file will be created.
  • name (str): The name of the contribution, used to generate the test file name.
Source code in scripts/utils.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def create_test_file(contrib_path: str, name: str) -> None:
    """
    Create the test file for the contribution.

    Args:

    - contrib_path (str): The path to the contribution directory where the test file will be created.
    - name (str): The name of the contribution, used to generate the test file name.

    """
    test_path = os.path.join(contrib_path, 'tests', f"test_{name}.py")
    # Content to be inserted into the file
    content = f'''"""Unit tests for contribution {name}"""

from {name} import hello_world

def test_hello_world():
    assert hello_world() == "Hello, World!"
'''

    with open(test_path, 'w', encoding='utf-8') as test_file:
        test_file.write(content)
    print(f"Created {test_path}")

create_tests_directory(contrib_path)

Creates a 'tests' directory inside the specified contribution directory.

Args:

  • contrib_path (str): The path to the contribution directory where the 'tests' directory will be created.

Returns:

  • str: The path to the created 'tests' directory.

Notes:

  • If the 'tests' directory already exists, this function will not raise an error.
Source code in scripts/utils.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def create_tests_directory(contrib_path: str) -> str:
    """
    Creates a 'tests' directory inside the specified contribution directory.

    Args:

    - contrib_path (str): The path to the contribution directory where the 'tests' directory will be created.

    Returns:

    - str: The path to the created 'tests' directory.

    Notes:

    - If the 'tests' directory already exists, this function will not raise an error.

    """
    tests_path = os.path.join(contrib_path, 'tests')
    os.makedirs(tests_path, exist_ok=True)
    print(f"Created {tests_path}/")

init_py_exists(contrib_path)

Checks if an 'init.py' file exists in the specified directory.

Args:

  • contrib_path (str): The path to the directory to check.

Returns:

  • bool: True if the 'init.py' file exists in the directory, False otherwise.
Source code in scripts/utils.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def init_py_exists(contrib_path: str) -> bool:
    """
    Checks if an '__init__.py' file exists in the specified directory.

    Args:

    - contrib_path (str): The path to the directory to check.

    Returns:

    - bool: True if the '__init__.py' file exists in the directory, False otherwise.

    """
    return os.path.exists(os.path.join(contrib_path, '__init__.py'))

list_directories(path)

List all subdirectories in the given path.

Args:

  • path (str): The directory path to list subdirectories from.

Returns:

  • set: A set of subdirectory names.
Source code in scripts/utils.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def list_directories(path):
    """
    List all subdirectories in the given path.

    Args:

    - path (str): The directory path to list subdirectories from.

    Returns:

    - set: A set of subdirectory names.

    """
    if not os.path.exists(path):
        return set()
    return {name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name))}

list_subdirs(path)

List all subdirectories in the given path.

Args:

  • path (str): The directory path to list subdirectories from.

Returns:

  • set: A set of subdirectory names.
Source code in scripts/utils.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def list_subdirs(path):
    """
    List all subdirectories in the given path.

    Args:

    - path (str): The directory path to list subdirectories from.

    Returns:

    - set: A set of subdirectory names.

    """
    if not os.path.exists(path):
        return set()
    return {name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name))}

main_py_exists(contrib_path, name)

Checks if a Python file with the specified name exists in the given directory.

Args:

  • contrib_path (str): The path to the directory where the file is expected to be located.
  • name (str): The name of the Python file (without the .py extension).

Returns:

  • bool: True if the file exists, False otherwise.
Source code in scripts/utils.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def main_py_exists(contrib_path: str, name: str) -> bool:
    """
    Checks if a Python file with the specified name exists in the given directory.

    Args:

    - contrib_path (str): The path to the directory where the file is expected to be located.
    - name (str): The name of the Python file (without the .py extension).

    Returns:

    - bool: True if the file exists, False otherwise.

    """
    return os.path.exists(os.path.join(contrib_path, f"{name}.py"))

pyproject_file_exists(contrib_path)

Checks if a 'pyproject.toml' file exists in the specified directory.

Args:

  • contrib_path (str): The path to the directory where the function will look for the 'pyproject.toml' file.

Returns:

  • bool: True if the 'pyproject.toml' file exists in the specified directory, False otherwise.
Source code in scripts/utils.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def pyproject_file_exists(contrib_path: str) -> bool:
    """
    Checks if a 'pyproject.toml' file exists in the specified directory.

    Args:

    - contrib_path (str): The path to the directory where the function will look for the 'pyproject.toml' file.

    Returns:

    - bool: True if the 'pyproject.toml' file exists in the specified directory, False otherwise.

    """
    return os.path.exists(os.path.join(contrib_path, 'pyproject.toml'))

read_pyproject_metadata(pyproject_path)

Reads a pyproject.toml file and extracts the [project] section.

Args:

  • pyproject_path (str): Path to the pyproject.toml file.

Returns:

  • Optional[dict]: A dictionary containing metadata from the [project] section, or None if the file or section is missing.
Source code in scripts/utils.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def read_pyproject_metadata(pyproject_path: str) -> Optional[dict]:
    """
    Reads a pyproject.toml file and extracts the [project] section.

    Args:

    - pyproject_path (str): Path to the pyproject.toml file.

    Returns:

    - Optional[dict]: A dictionary containing metadata from the [project] section,
                      or None if the file or section is missing.
    """
    if not os.path.exists(pyproject_path):
        return None

    with open(pyproject_path, 'rb') as f:
        data = tomllib.load(f)

    return data.get("project")

readme_exists(contrib_path)

Checks if a README.md file exists in the specified directory.

Args:

  • contrib_path (str): The path to the directory where the README.md file is expected.

Returns:

  • bool: True if the README.md file exists in the specified directory, False otherwise.
Source code in scripts/utils.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def readme_exists(contrib_path: str) -> bool:
    """
    Checks if a README.md file exists in the specified directory.

    Args:

    - contrib_path (str): The path to the directory where the README.md file is expected.

    Returns:

    - bool: True if the README.md file exists in the specified directory, False otherwise.

    """
    return os.path.exists(os.path.join(contrib_path, 'README.md'))

sync_contrib_docs()

Synchronize the docs/contrib directory with the contrib directory.

Source code in scripts/utils.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def sync_contrib_docs():
    """
    Synchronize the `docs/contrib` directory with the `contrib` directory.
    """
    # List subdirectories in contrib and docs/contrib
    contrib_dirs = list_directories(CONTRIB_DIR)
    docs_contrib_dirs = list_directories(DOCS_CONTRIB_DIR)

    print("Subdirectories in contrib:")
    print(contrib_dirs)

    print("\nSubdirectories in docs/contrib:")
    print(docs_contrib_dirs)

    # Remove directories in docs/contrib that do not exist in contrib
    for doc_dir in docs_contrib_dirs - contrib_dirs:
        doc_dir_path = os.path.join(DOCS_CONTRIB_DIR, doc_dir)
        print(f"Removing obsolete directory: {doc_dir_path}")
        shutil.rmtree(doc_dir_path)

    # List directories in contrib that do not exist in docs/contrib
    missing_in_docs = contrib_dirs - docs_contrib_dirs
    print("\nDirectories in contrib missing in docs/contrib:")
    print(missing_in_docs)

test_file_exists(contrib_path, name)

Check if a test file with a specific name exists in the given directory.

Args:

  • contrib_path (str): The path to the directory where the test file is expected to be located.
  • name (str): The base name of the test file (without the "test_" prefix and ".py" extension).

Returns:

  • bool: True if the test file exists, False otherwise.
Source code in scripts/utils.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def test_file_exists(contrib_path: str, name: str) -> bool:
    """
    Check if a test file with a specific name exists in the given directory.

    Args:

    - contrib_path (str): The path to the directory where the test file is expected to be located.
    - name (str): The base name of the test file (without the "test_" prefix and ".py" extension).

    Returns:

    - bool: True if the test file exists, False otherwise.

    """
    return os.path.exists(os.path.join(contrib_path, f"test_{name}.py"))

validate_contrib_metadata(contrib_name, base_path=CONTRIB_DIR)

Validate the pyproject.toml metadata for a given contribution.

Args:

  • contrib_name (str): Name of the contribution folder.

Returns:

  • bool: True if metadata is valid, False otherwise.
Source code in scripts/utils.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
def validate_contrib_metadata(contrib_name: str, base_path: str = CONTRIB_DIR) -> bool:
    """
    Validate the pyproject.toml metadata for a given contribution.

    Args:

    - contrib_name (str): Name of the contribution folder.

    Returns:

    - bool: True if metadata is valid, False otherwise.
    """
    pyproject_path = os.path.join(base_path, contrib_name, "pyproject.toml")
    metadata = read_pyproject_metadata(pyproject_path)

    if metadata is None:
        print(f"Missing or invalid pyproject.toml in {contrib_name}")
        return False

    missing_fields = [field for field in REQUIRED_FIELDS if field not in metadata]

    if missing_fields:
        print(f"Missing required fields in {contrib_name}: {', '.join(missing_fields)}")
        return False

    print(f"Metadata for {contrib_name} is valid.")
    return True

write_pyproject_file(contrib_path, name, metadata=None)

Generate a pyproject.toml file with customizable metadata for a Python project.

This function creates a pyproject.toml file in the specified directory with the provided project metadata, including name, description, version, license, author information, and dependencies.

Args:

  • contrib_path (str): The directory path where the pyproject.toml file will be created.
  • name (str): The name of the project. This will also be used as the default description if none is provided.
  • metadata (dict, optional): A dictionary containing project metadata, such as:
    • description (str): A brief description of the project.
    • version (str): The version of the project.
    • license (str): The license type or text for the project.
    • author_name (str): The name of the author.
    • author_email (str): The email address of the author.
    • dependencies (list[str]): A list of project dependencies.

Returns:

  • None: This function does not return a value. It writes the pyproject.toml file to the specified directory.

Raises:

  • OSError: If there is an issue writing the file to the specified directory.

Example:

``` python
write_pyproject_file(
    contrib_path="/path/to/project",
    name="my_project",
    metadata={
        "description": "A sample Python project",
        "version": "0.1.0",
        "license": "MIT",
        "author_name": "John Doe",
        "author_email": "john.doe@example.com",
        "dependencies": ["numpy", "pandas"]
    }
)
```
Source code in scripts/utils.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def write_pyproject_file(
    contrib_path: str,
    name: str,
    metadata: Optional[dict] = None
) -> None:
    """
    Generate a `pyproject.toml` file with customizable metadata for a Python project.

    This function creates a `pyproject.toml` file in the specified directory with
    the provided project metadata, including name, description, version, license,
    author information, and dependencies.

    Args:

    - contrib_path (str): The directory path where the `pyproject.toml` file will be created.
    - name (str): The name of the project. This will also be used as the default description if none is provided.
    - metadata (dict, optional): A dictionary containing project metadata, such as:
        - description (str): A brief description of the project.
        - version (str): The version of the project.
        - license (str): The license type or text for the project.
        - author_name (str): The name of the author.
        - author_email (str): The email address of the author.
        - dependencies (list[str]): A list of project dependencies.

    Returns:

    - None: This function does not return a value. It writes the `pyproject.toml` file to the specified directory.

    Raises:

    - OSError: If there is an issue writing the file to the specified directory.

    Example:

        ``` python
        write_pyproject_file(
            contrib_path="/path/to/project",
            name="my_project",
            metadata={
                "description": "A sample Python project",
                "version": "0.1.0",
                "license": "MIT",
                "author_name": "John Doe",
                "author_email": "john.doe@example.com",
                "dependencies": ["numpy", "pandas"]
            }
        )
        ```
    """
    metadata = metadata or {}
    description = metadata.get("description", name)
    version = metadata.get("version", "1.0.0")
    license_str = metadata.get("license", "CeCILL-C FREE SOFTWARE LICENSE AGREEMENT")
    author_name = metadata.get("author_name", "Contributor Name")
    author_email = metadata.get("author_email", "contributor1@example.com")
    dependencies = metadata.get("dependencies", [])

    pyproject_toml_file_path = os.path.join(contrib_path, 'pyproject.toml')
    if dependencies:
        deps_str = "\n".join([f'"{dep}",' for dep in dependencies])
        deps_section = f" [\n{deps_str}\n]"
    else:
        deps_section = " []"

    content = f"""[project]
name = "{name}"
description = "{description}"
version = "{version}"
license = "{license_str}"
authors = [{{ name = "{author_name}", email = "{author_email}" }}]
dependencies = {deps_section}
"""

    with open(pyproject_toml_file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"Created {pyproject_toml_file_path}")