github.com/qapquiz/xk6-dotenv@v0.1.2-0.20220614041208-d05c37e5dd7e/dotenv.go (about)

     1  // MIT License
     2  //
     3  // Copyright (c) 2021 Iván Szkiba
     4  //
     5  // Permission is hereby granted, free of charge, to any person obtaining a copy
     6  // of this software and associated documentation files (the "Software"), to deal
     7  // in the Software without restriction, including without limitation the rights
     8  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     9  // copies of the Software, and to permit persons to whom the Software is
    10  // furnished to do so, subject to the following conditions:
    11  //
    12  // The above copyright notice and this permission notice shall be included in all
    13  // copies or substantial portions of the Software.
    14  //
    15  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    16  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    17  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    18  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    19  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    20  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    21  // SOFTWARE.
    22  
    23  package dotenv
    24  
    25  import (
    26  	"os"
    27  
    28  	"github.com/joho/godotenv"
    29  	"go.k6.io/k6/js/modules"
    30  )
    31  
    32  // Register the extensions on module initialization.
    33  func init() {
    34  	modules.Register("k6/x/dotenv", New())
    35  
    36  	load()
    37  }
    38  
    39  type Module struct{}
    40  
    41  func New() *Module {
    42  	return &Module{}
    43  }
    44  
    45  func (m *Module) Parse(text string) (interface{}, error) {
    46  	obj, err := godotenv.Unmarshal(text)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	return obj, nil
    52  }
    53  
    54  func (m *Module) Stringify(value map[string]string) (string, error) {
    55  	str, err := godotenv.Marshal(value)
    56  	if err != nil {
    57  		return "", err
    58  	}
    59  
    60  	return str, nil
    61  }
    62  
    63  func load() {
    64  	env := os.Getenv(envVar)
    65  
    66  	if env == disabled {
    67  		return
    68  	}
    69  
    70  	if env == "" {
    71  		env = "development"
    72  	}
    73  
    74  	godotenv.Load(".env." + env + ".local") // nolint:errcheck
    75  
    76  	if env != "test" {
    77  		godotenv.Load(".env.local") // nolint:errcheck
    78  	}
    79  
    80  	godotenv.Load(".env." + env) // nolint:errcheck
    81  
    82  	godotenv.Load() // nolint:errcheck
    83  }
    84  
    85  const (
    86  	envVar   = "K6_ENV"
    87  	disabled = "false"
    88  )