Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Create the directory automatically if it doesn't exist #70 #73

Merged
merged 5 commits into from
Feb 19, 2024

Conversation

HyoungSooo
Copy link
Contributor

@HyoungSooo HyoungSooo commented Feb 16, 2024

Create PR for #70

This PR is add decorator and test code for create new folder if it dose not exist.

def create_folder_if_not_exists(func: Any) -> Callable[..., int]:
    """Decorator to create folder if it does not exist."""

    def wrapper(*args: Any, **kwargs: Any) -> int:
        try:
            filepath = kwargs["filepath"]
        except KeyError:
            filepath = args[0]
        folder = os.path.dirname(filepath)
        if not os.path.exists(folder) and folder != "":
            os.makedirs(folder)
        return func(*args, **kwargs)

    return wrapper

The reason why the try except statement is used is because other methods that call the write_csv function sometimes pass the filepath into args and sometimes kwarg.

usage

@create_folder_if_not_exists
def write_csv(filepath: Path, records: List[dict], schema: dict, **kwargs: Any) -> int:
    """Write a CSV file."""
    if "properties" not in schema:
        raise ValueError("Stream's schema has no properties defined.")

    keys: List[str] = list(schema["properties"].keys())
    with open(filepath, "w", encoding="utf-8", newline="") as fp:
        writer = csv.DictWriter(fp, fieldnames=keys, dialect="excel", **kwargs)
        writer.writeheader()
        for record_count, record in enumerate(records, start=1):
            writer.writerow(record)

    return record_count

If there is a better way please let me know

@HyoungSooo HyoungSooo changed the title FIX: Create the directory automatically if it doesn't exist #70 chore: Create the directory automatically if it doesn't exist #70 Feb 16, 2024
Copy link

sonarcloud bot commented Feb 19, 2024

Quality Gate Passed Quality Gate passed

Issues
0 New issues

Measures
0 Security Hotspots
No data about Coverage
No data about Duplication

See analysis details on SonarCloud

Copy link
Member

@edgarrmondragon edgarrmondragon left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @HyoungSooo!

@edgarrmondragon edgarrmondragon merged commit 6cae335 into MeltanoLabs:main Feb 19, 2024
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants