← run

bcb-0014

1.000
4/4 tests· lib-knowledge
Challenge · difficulty 3/5
# BigCodeBench/14

Implement a file **`solution.py`** that completes the function below. Keep the given name and signature; define `task_func` at module level.

Allowed libraries: `configparser`, `shutil`, `os`.

```python
import configparser
import os
import shutil


def task_func(config_file_path, archieve_dir ='/home/user/archive'):
    """
    Archive a specified project directory into a ZIP file based on the configuration specified in a config file.
    
    This function reads a configuration file to determine the project directory and archives this directory into a ZIP file.
    The ZIP file's name will be the project directory's basename, stored in the specified archive directory.
    
    Configuration File Format:
    [Project]
    directory=path_to_project_directory
    
    Parameters:
    - config_file_path (str): Path to the configuration file. The file must exist and be readable.
    - archive_dir (str, optional): Path to the directory where the ZIP archive will be stored. Defaults to '/home/user/archive'.
    
    Returns:
    - bool: True if the ZIP archive is successfully created, otherwise an exception is raised.
    
    Requirements:
    - configparse
    - os
    - shutil

    Raises:
    - FileNotFoundError: If the `config_file_path` does not exist or the specified project directory does not exist.
    - Exception: If the ZIP archive cannot be created.
    
    Example:
    >>> task_func("/path/to/config.ini")
    True
    """
```

<!-- imported from BigCodeBench (BigCodeBench/14) -->
tests/test_bcb_0014.py
# Auto-generated from BigCodeBench BigCodeBench/14. Do not edit by hand.
import pathlib as _pathlib
exec(_pathlib.Path(__file__).with_name("solution.py").read_text(), globals())

import unittest
import tempfile
import shutil
import os
import configparser
class TestCases(unittest.TestCase):
    def setUp(self):
        # Setup a temporary directory for the configuration files and another for the archive output
        self.test_data_dir = tempfile.mkdtemp()
        self.archive_dir = tempfile.mkdtemp()
        # Example valid configuration file setup
        self.valid_config_path = os.path.join(self.test_data_dir, "valid_config.ini")
        config = configparser.ConfigParser()
        config['Project'] = {'directory': self.test_data_dir}
        with open(self.valid_config_path, 'w') as configfile:
            config.write(configfile)
        # Invalid directory config
        self.invalid_config_path = os.path.join(self.test_data_dir, "invalid_config.ini")
        config['Project'] = {'directory': '/path/to/nonexistent/directory'}
        with open(self.invalid_config_path, 'w') as configfile:
            config.write(configfile)
    def tearDown(self):
        # Remove temporary directories after each test
        shutil.rmtree(self.test_data_dir)
        shutil.rmtree(self.archive_dir)
    def test_valid_project_directory(self):
        # Testing with a valid project directory
        result = task_func(self.valid_config_path, self.archive_dir)
        self.assertTrue(result)
    def test_invalid_project_directory(self):
        # Testing with a non-existent project directory
        with self.assertRaises(FileNotFoundError):
            task_func(self.invalid_config_path, self.archive_dir)
    def test_archive_creation(self):
        # Run the function to create the archive
        task_func(self.valid_config_path, self.archive_dir)
        archive_file = os.path.join(self.archive_dir, os.path.basename(self.test_data_dir) + '.zip')
        self.assertTrue(os.path.isfile(archive_file))
    def test_archive_content(self):
        # Adding a sample file to the project directory to check archive contents later
        sample_file_path = os.path.join(self.test_data_dir, "sample_file.txt")
        with open(sample_file_path, 'w') as f:
            f.write("Hello, world!")
        task_func(self.valid_config_path, self.archive_dir)
        archive_file = os.path.join(self.archive_dir, os.path.basename(self.test_data_dir) + '.zip')
        content = os.popen(f"unzip -l {archive_file}").read()
        self.assertIn("sample_file.txt", content)
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.
Proposed solution
```python
import configparser
import os
import shutil

def task_func(config_file_path, archive_dir='/home/user/archive'):
    """
    Archive a specified project directory into a ZIP file based on the configuration specified in a config file.

    This function reads a configuration file to determine the project directory and archives this directory into a ZIP file.
    The ZIP file's name will be the project directory's basename, stored in the specified archive directory.

    Configuration File Format:
    [Project]
    directory=path_to_project_directory

    Parameters:
    - config_file_path (str): Path to the configuration file. The file must exist and be readable.
    - archive_dir (str, optional): Path to the directory where the ZIP archive will be stored. Defaults to '/home/user/archive'.

    Returns:
    - bool: True if the ZIP archive is successfully created, otherwise an exception is raised.

    Requirements:
    - configparse
    - os
    - shutil

    Raises:
    - FileNotFoundError: If the `config_file_path` does not exist or the specified project directory does not exist.
    - Exception: If the ZIP archive cannot be created.

    Example:
    >>> task_func("/path/to/config.ini")
    True
    """
    # Read the configuration file
    config = configparser.ConfigParser()
    config.read(config_file_path)

    # Get the project directory from the config file
    project_dir = config.get('Project', 'directory')

    # Check if the project directory exists
    if not os.path.exists(project_dir):
        raise FileNotFoundError(f"The specified project directory does not exist: {project_dir}")

    # Create the archive directory if it doesn't exist
    os.makedirs(archive_dir, exist_ok=True)

    # Determine the basename of the project directory
    project_basename = os.path.basename(os.path.normpath(project_dir))

    # Create the ZIP file path
    zip_file_path = os.path.join(archive_dir, f"{project_basename}.zip")

    # Create the ZIP archive
    try:
        shutil.make_archive(zip_file_path.replace('.zip', ''), 'zip', project_dir)
        return True
    except Exception as e:
        raise Exception(f"Failed to create ZIP archive: {e}")
```

Test output (stdout)

....                                                                     [100%]
4 passed in 0.03s