@@ -6,30 +6,38 @@ import (
66 "strings"
77)
88
9- // getPaths receives an array of directory entries and transforms it into a array of file paths concatenating the
10- // directory name with a base path.
9+ const (
10+ EnvFile = ".env"
11+ )
12+
13+ // getPaths converts an array of directory entries into an array of file paths by concatenating each
14+ // entry's name with a base path.
1115func getPaths (newDirs []os.DirEntry , basePath string ) []string {
12- var paths []string
16+ paths := make ( []string , len ( newDirs ))
1317
14- for _ , dir := range newDirs {
15- path := filepath .Join (basePath , dir .Name ())
16- paths = append (paths , path )
18+ for i , dir := range newDirs {
19+ paths [i ] = filepath .Join (basePath , dir .Name ())
1720 }
1821
1922 return paths
2023}
2124
22- // loadVarsFromFile receives a path to an .env file, parses it and loads all the variables .
25+ // loadVarsFromFile parses an .env file at the given path and loads its variables into the environment .
2326func loadVarsFromFile (path string ) error {
2427 fileData , err := os .ReadFile (path )
2528 if err != nil {
2629 return err
2730 }
2831
2932 for _ , line := range strings .Split (string (fileData ), "\n " ) {
30- lineContent := strings .Split (line , "=" )
31- if len (lineContent ) == 2 {
32- if err := os .Setenv (lineContent [0 ], lineContent [1 ]); err != nil {
33+ if line == "" || strings .HasPrefix (line , "#" ) {
34+ continue
35+ }
36+
37+ parts := strings .Split (line , "=" )
38+ if len (parts ) == 2 {
39+ key , value := strings .TrimSpace (parts [0 ]), strings .TrimSpace (parts [1 ])
40+ if err := os .Setenv (key , value ); err != nil {
3341 return err
3442 }
3543 }
@@ -38,17 +46,10 @@ func loadVarsFromFile(path string) error {
3846 return nil
3947}
4048
41- // Load reads recursively all the directories of a project until it finds a .env file. Once the .env is found, reads
42- // the file and loads the values as OS ENV values .
49+ // Load recursively scans all directories of a project until it finds a .env file. Once found, it reads
50+ // the file and loads its values as environment variables .
4351func Load () error {
44- var dirsQueue []string
45-
46- dirs , err := os .ReadDir ("./" )
47- if err != nil {
48- return err
49- }
50-
51- dirsQueue = getPaths (dirs , "." )
52+ dirsQueue := []string {"./" }
5253
5354 for len (dirsQueue ) > 0 {
5455 path := dirsQueue [0 ]
@@ -64,7 +65,7 @@ func Load() error {
6465 return err
6566 }
6667 dirsQueue = append (dirsQueue , getPaths (children , path )... )
67- } else if file .Name () == ".env" {
68+ } else if file .Name () == EnvFile {
6869 return loadVarsFromFile (path )
6970 }
7071
0 commit comments