Skip to content

Conversation

@Nixellion
Copy link

@Nixellion Nixellion commented Jan 31, 2024

Without specifying "utf-8" encoding when writing a file the script fails to write text to a file in many cases.

I can't say if it's specific to OS region\language or contents of the file, but this simple change fixes any such issues, tested locally.

Changes in this PR

Add encoding="utf-8" to the file open on write.

cc/ @klen

@Nixellion Nixellion requested a review from klen as a code owner January 31, 2024 12:33
@Nixellion
Copy link
Author

A note, same change required for the

def read(self, name):
        """Read migration from file."""

but it's missing from this PR. I can create another PR with that change if needed

@Nixellion
Copy link
Author

Nixellion commented Nov 7, 2024

Until this PR is implemented a patch can be applied like this, in your own code, by subclassing the Router class:

from peewee_migrate import Router as BadRouter
from peewee_migrate.router import void
from peewee_migrate.template import TEMPLATE

class Router(BadRouter):
    def compile(self, name, migrate="", rollback="", num=None) -> str:  # noqa: A003
        """Create a migration."""
        if num is None:
            num = len(self.todo)

        name = "{:03}_".format(num + 1) + name
        filename = name + ".py"
        path = self.migrate_dir / filename
        with path.open("w", encoding="utf-8") as f:
            f.write(TEMPLATE.format(migrate=migrate, rollback=rollback, name=filename))

        return name
    
    def read(self, name):
        """Read migration from file."""
        path = self.migrate_dir / (name + ".py")
        with path.open("r", encoding="utf-8") as f:
            code = f.read()
            scope = {}
            code = compile(code, "<string>", "exec", dont_inherit=True)
            exec(code, scope, None)
            return scope.get("migrate", void), scope.get("rollback", void)

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.

1 participant