Skip to content

Commit

Permalink
feat: implement env file parser
Browse files Browse the repository at this point in the history
  • Loading branch information
knoxx committed Aug 1, 2024
0 parents commit 130124d
Show file tree
Hide file tree
Showing 8 changed files with 408 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: CI

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.22.x'
- name: Test
run: go test -v -race -cover -buildvcs ./...
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Sameer Jadav

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
34 changes: 34 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Change these variables as necessary.
PACKAGE_PATH := ./...

# ==================================================================================== #
# HELPERS
# ==================================================================================== #

## help: print this help message
.PHONY: help
help:
@echo 'Usage:'
@sed -n 's/^##//p' ${MAKEFILE_LIST} | column -t -s ':' | sed -e 's/^/ /'

# ==================================================================================== #
# QUALITY CONTROL
# ==================================================================================== #

## test: run all tests with coverage
.PHONY: test
test:
@echo "Running tests..."
@go test -v -race -cover -buildvcs ${PACKAGE_PATH}

# ==================================================================================== #
# DEVELOPMENT
# ==================================================================================== #

## tidy: format code and tidy modfile
.PHONY: tidy
tidy:
@echo "Formatting code..."
@gofumpt -l -w .
@echo "Tidying Go mod..."
@go mod tidy -v
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# GoEnvParse

[![Go Reference](https://pkg.go.dev/badge/github.com/SameerJadav/go-envparse.svg)](https://pkg.go.dev/github.com/SameerJadav/go-envparse) [![CI](https://github.com/SameerJadav/go-envparse/actions/workflows/ci.yml/badge.svg)](https://github.com/SameerJadav/go-envparse/actions/workflows/ci.yml)

GoEnvParse is a Go package for parsing environment variables from `.env` files. It provides a simple and efficient way to load environment variables from `.env` file into your Go applications.

## Features

- Parse environment files from any `io.Reader` source
- Handling of quoted values (double quotes, single quotes, and backticks)
- Variable expansion in non-quoted and double-quoted values
- Error reporting with line numbers for invalid syntax

## Parsing Details

- Double-quoted values are unescaped, including unicode characters
- Single-quoted and backtick-quoted values are treated as literal strings
- Variable expansion is performed in non-quoted and double-quoted values
- Does not support multiline values

## Installation

```shell
go get github.com/SameerJadav/go-envparse
```

## Usage

```go
package main

import (
"log"
"os"

"github.com/SameerJadav/go-envparse"
)

func main() {
file, err := os.Open(".env")
if err != nil {
log.Fatal(err)
}
defer file.Close()

env, err := envparse.Parse(file)
if err != nil {
log.Fatal(err)
}

for key, value := range env {
os.Setenv(key, value)
}
}
```

## Contributing

Contributions are welcome. Please open an issue or submit a pull request.

## License

GoEnvParse is open-source and available under the [MIT License](./LICENSE).
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/SameerJadav/go-envparse

go 1.22.5
105 changes: 105 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package envparse

import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)

// Parse reads an env file from io.Reader, returning a map of keys-value pairs and an error.
//
// Only double-quoted values are escaped. Single-quoted and backquoted values
// are treated as literal strings. Variable expansion (${...} and $...)
// is performed in non-quoted and double-quoted values.
//
// Note: This function does not support multiline values.
// Each key-value pair must be on a single line.
func Parse(r io.Reader) (map[string]string, error) {
result := make(map[string]string)
scanner := bufio.NewScanner(r)
var lineNumber int
var err error

for scanner.Scan() {
lineNumber++

line := strings.TrimSpace(scanner.Text())
if line == "" || line[0] == '#' || !strings.Contains(line, "=") {
continue
}

line = strings.TrimPrefix(line, "export ")

key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}

key = strings.TrimSpace(key)
if key == "" {
continue
}

value = strings.TrimSpace(value)

if quote, start, end, ok := isQuoted(value); ok {
switch quote {
case '"':
value, err = strconv.Unquote(value[start : end+1])
if err != nil {
return nil, fmt.Errorf("failed to unquote value at line %d: %w", lineNumber, err)
}
value = expandVariables(value, result)
case '`':
value, err = strconv.Unquote(value[start : end+1])
if err != nil {
return nil, fmt.Errorf("failed to unquote value at line %d: %w", lineNumber, err)
}
case '\'':
value = value[start+1 : end]
}
} else {
if i := strings.IndexByte(value, '#'); i >= 0 {
value = strings.TrimSpace(value[:i])
}
value = expandVariables(value, result)
}

result[key] = value
}

if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading input: %w", err)
}

return result, nil
}

func isQuoted(value string) (byte, int, int, bool) {
if len(value) < 2 {
return 0, -1, -1, false
}

if quote := value[0]; quote == '"' || quote == '\'' || quote == '`' {
for i := len(value) - 1; i > 0; i-- {
if value[i] == quote && value[i-1] != '\\' {
return quote, 0, i, true
}
}
return quote, 0, -1, false
}

return 0, -1, -1, false
}

func expandVariables(value string, result map[string]string) string {
return os.Expand(value, func(key string) string {
if val, ok := result[key]; ok {
return val
}
return os.Getenv(key)
})
}
90 changes: 90 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package envparse

import (
"os"
"testing"
)

func TestParse(t *testing.T) {
expected := map[string]string{
"SIMPLE_VAR": "value",
"EMPTY": "",
"EMPTY_SINGLE_QUOTES": "",
"EMPTY_DOUBLE_QUOTES": "",
"EMPTY_BACKTICKS": "",
"QUOTED_VAR": "value",
"SINGLE_QUOTED_VAR": "value",
"BACKQUOTED_VAR": "value",
"DOUBLE_QUOTES_SPACED": " double quotes ",
"SINGLE_QUOTES_SPACED": " single quotes ",
"BACKQUOTE_SPACED": " back quotes ",
"UNQUOTED_WITH_SPACES": "this has spaces",
"NESTED_IN_DOUBLE": "This is a 'single quote' and a `backtick` inside double quotes",
"NESTED_IN_SINGLE": "This is a \"double quote\" and a `backtick` inside single quotes",
"NESTED_IN_BACKTICK": "This is a \"double quote\" and a 'single quote' inside backticks",
"ESCAPED_IN_DOUBLE": "This has \"escaped double quotes\"",
"ESCAPED_IN_SINGLE": "This has \\'escaped single quotes\\'",
"MIXED_QUOTES": "Double with 'single' and \"escaped double\" and `backtick`",
"UNQUOTED_NEWLINE": "This is a line\\nAnd this is another line",
"DOUBLE_QUOTED_NEWLINE": "This is in double quotes\nThis is a new line in double quotes",
"SINGLE_QUOTED_NEWLINE": "This is in single quotes\\nThis is a new line in single quotes",
"BACKTICK_QUOTED_NEWLINE": "This is in backticks\\nThis is a new line in backticks",
"VARIABLE_EXPANSION": "value/expansion",
"NESTED_EXPANSION": "value/expansion/nested",
"VARIABLE_EXPANSION_ALT": "value/expansion",
"NESTED_EXPANSION_ALT": "value/expansion/nested",
"DOUBLEQUOTED_VARIABLE_EXPANSION": "value/expansion",
"DOUBLEQUOTED_NESTED_EXPANSION": "value/expansion/nested",
"DOUBLEQUOTED_VARIABLE_EXPANSION_ALT": "value/expansion",
"DOUBLEQUOTED_NESTED_EXPANSION_ALT": "value/expansion/nested",
"SINGLEQUOTED_VARIABLE_EXPANSION": "${SIMPLE_VAR}/expansion",
"SINGLEQUOTED_NESTED_EXPANSION": "${VARIABLE_EXPANSION}/nested",
"SINGLEQUOTED_VARIABLE_EXPANSION_ALT": "$SIMPLE_VAR/expansion",
"SINGLEQUOTED_NESTED_EXPANSION_ALT": "$VARIABLE_EXPANSION/nested",
"BACKQUOTED_VARIABLE_EXPANSION": "${SIMPLE_VAR}/expansion",
"BACKQUOTED_NESTED_EXPANSION": "${VARIABLE_EXPANSION}/nested",
"BACKQUOTED_VARIABLE_EXPANSION_ALT": "$SIMPLE_VAR/expansion",
"BACKQUOTED_NESTED_EXPANSION_ALT": "$VARIABLE_EXPANSION/nested",
"UNMATCHED_DOUBLEQUOTE": "\"value",
"UNMATCHED_SINGLEQUOTE": "'value",
"UNMATCHED_BACKQUOTE": "`value",
"INLINE_COMMENTS": "value",
"INLINE_COMMENTS_DOUBLE_QUOTES": "inline comments outside of #doublequotes",
"INLINE_COMMENTS_SINGLE_QUOTES": "inline comments outside of #singlequotes",
"INLINE_COMMENTS_BACKQUOTES": "inline comments outside of #backticks",
"EXPORTED_VAR": "value",
"EQUAL_SIGNS": "equals==",
"SPACED_KEY": "value",
}

file, err := os.Open("test.env")
if err != nil {
t.Fatal(err)
}
defer file.Close()

result, err := Parse(file)
if err != nil {
t.Fatalf("Parse returned unexpected error: %v", err)
}

if len(result) != len(expected) {
t.Errorf("Map size mismatch: got %d entries, want %d entries", len(result), len(expected))
}

for expectedKey, expectedValue := range expected {
actualValue, ok := result[expectedKey]
if !ok {
t.Errorf("Missing key: %s is not present in the result map, but it was expected", expectedKey)
}
if actualValue != expectedValue {
t.Errorf("Value mismatch for key %s: got %s, want %s", expectedKey, actualValue, expectedValue)
}
}

for key, value := range result {
if _, ok := expected[key]; !ok {
t.Errorf("Unexpected key-value pair: %s=%s is present in the result map, but it was not expected.", key, value)
}
}
}
Loading

0 comments on commit 130124d

Please sign in to comment.