wintercms / laravel-config-writer

Utility to create and update Laravel config and .env files
MIT License
13 stars 8 forks source link

Add proper lexer for .env files #2

Closed jaxwilko closed 1 year ago

jaxwilko commented 1 year ago

This PR is a bit overkill, but resolves the issue reported in https://github.com/wintercms/laravel-config-writer/issues/1.

The problem was previously each line was parsed as a single entity, i.e. a line could be either a comment or a env entry, but never two things.

The new approach provided by this PR is to use a proper Lexer to convert the source into tokens. By doing this, multiple tokens can exist on the same line.

This ensures that the following:

# WINTERCMS

APP_DEBUG=true
APP_URL="http://localhost"

# HELLO WORLD

APP_KEY="changeme" # Change this

APP_EXAMPLE="test"

#ENV_COMMENT="1"

ENV_TEST="1"

#ENV_COMMENT=1

Can be interpreted and updated, preserving the original whitespace and comments.

I've added some additional tests to confirm the newly supported functionality

bennothommo commented 1 year ago

@jaxwilko if this is to be a true lexer and parsing an environment file into an AST, I would suggest making the initial environment variable a token, as well as the equals sign (and possibly even the whitespace between), so you get a true representation of each portion of the code.

Another little edge case to consider - I believe you can set an environment variable with no value whatsoever, which is the same as setting the environment variable as an empty string, but it otherwise exists, so it is not null.

Example:

EMPTY_VAR=
bennothommo commented 1 year ago

@jaxwilko I've added some additional test cases of valid environment variables. If they're too hard, just revert :P

jaxwilko commented 1 year ago

@bennothommo I thought I would have found time for this earlier, but at least it's done now. I've refactored the lexer to do 2 things differently:

LukeTowers commented 1 year ago

LGTM!