Skip to content

Commit

Permalink
Merge pull request #38 from gowizzard/development
Browse files Browse the repository at this point in the history
fix: Add new private function for read all matches from file.
  • Loading branch information
gowizzard authored Jan 28, 2023
2 parents 7b61179 + 9d385b7 commit c897a0e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 38 deletions.
41 changes: 3 additions & 38 deletions import.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,58 +5,23 @@
package dotenv

import (
"errors"
"os"
"regexp"
"syscall"
)

// data is to save the environ data.
type data struct {
Key []byte
Value []byte
}

// regex is to save the compiled expression.
var regex = regexp.MustCompile(`(?m)^(?P<key>\w+?)=(?:["']|\b)(?P<value>.+?)(?:["']|\b)$`)

// Import is read the environment variable file and use regex to find
// all sub matches. After that we initialize the environment variables to local.
func Import(path string) error {

read, err := os.ReadFile(path)
matches, err := read(path)
if err != nil {
return err
}

if len(read) == 0 {
return errors.New("file is empty")
}

matches := regex.FindAllSubmatch(read, -1)
if matches == nil {
return errors.New("no matches found")
}

for _, value := range matches {

environ := new(data)

names := regex.SubexpNames()
for index := range names {
switch names[index] {
case "key":
environ.Key = value[index]
case "value":
environ.Value = value[index]
}
}

err = syscall.Setenv(string(environ.Key), string(environ.Value))
for index, value := range matches {
err = syscall.Setenv(index, value)
if err != nil {
return err
}

}

return nil
Expand Down
47 changes: 47 additions & 0 deletions read.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2022 Jonas Kwiedor. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package dotenv

import (
"errors"
"os"
"regexp"
)

// regex is to save the compiled expression.
var regex = regexp.MustCompile(`(?m)^(?P<key>\w+?)=(?:["']|\b)(?P<value>.+?)(?:["']|\b)$`)

// read is to read the environment variable file and use regex to find all sub matches.
func read(path string) (map[string]string, error) {

read, err := os.ReadFile(path)
if err != nil {
return nil, err
}

if len(read) == 0 {
return nil, errors.New("file is empty")
}

matches := regex.FindAllSubmatch(read, -1)
if matches == nil {
return nil, errors.New("no matches found")
}

var environ = make(map[string]string)
for _, value := range matches {

index := map[string]int{
"key": regex.SubexpIndex("key"),
"value": regex.SubexpIndex("value"),
}

environ[string(value[index["key"]])] = string(value[index["value"]])

}

return environ, nil

}

0 comments on commit c897a0e

Please sign in to comment.