github.com/ecolytiq/xk6-dotenv@v0.2.2-0.20220902071434-058cfd60158b/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  	"context"
    27  	"os"
    28  
    29  	"github.com/joho/godotenv"
    30  	"go.k6.io/k6/js/modules"
    31  )
    32  
    33  // Register the extensions on module initialization.
    34  func init() {
    35  	modules.Register("k6/x/dotenv", New())
    36  
    37  	load()
    38  }
    39  
    40  type Module struct{}
    41  
    42  func New() *Module {
    43  	return &Module{}
    44  }
    45  
    46  func (m *Module) Parse(ctx context.Context, text string) (interface{}, error) {
    47  	obj, err := godotenv.Unmarshal(text)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	return obj, nil
    53  }
    54  
    55  func (m *Module) Stringify(ctx context.Context, value map[string]string) (string, error) {
    56  	str, err := godotenv.Marshal(value)
    57  	if err != nil {
    58  		return "", err
    59  	}
    60  
    61  	return str, nil
    62  }
    63  
    64  func load() {
    65  	env := os.Getenv(envVar)
    66  
    67  	if env == disabled {
    68  		return
    69  	}
    70  
    71  	if env == "" {
    72  		env = "development"
    73  	}
    74  
    75  	godotenv.Load(".env." + env + ".local") // nolint:errcheck
    76  
    77  	if env != "test" {
    78  		godotenv.Load(".env.local") // nolint:errcheck
    79  	}
    80  
    81  	godotenv.Load(".env." + env) // nolint:errcheck
    82  
    83  	godotenv.Load() // nolint:errcheck
    84  }
    85  
    86  const (
    87  	envVar   = "K6_ENV"
    88  	disabled = "false"
    89  )