github.com/bazelbuild/rules_webtesting@v0.2.0/go/wsl/resolver/resolver.go (about)

     1  // Copyright 2018 Google Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package resolver resolves WSL, WSLPORT, and WSLENV variables in capabilities.
    16  package resolver
    17  
    18  import (
    19  	"errors"
    20  	"fmt"
    21  	"net"
    22  	"os"
    23  	"strconv"
    24  
    25  	"github.com/bazelbuild/rules_webtesting/go/metadata/capabilities"
    26  	"github.com/bazelbuild/rules_webtesting/go/portpicker"
    27  )
    28  
    29  // Resolver returns a capabilities.Resolver for WSL, WSLPORT, and WSLENV capabilities variables.
    30  func New(sessionID string) capabilities.Resolver {
    31  	ports := map[string]string{}
    32  
    33  	return func(p, n string) (string, error) {
    34  		switch p {
    35  		case "WSLPORT":
    36  			portStr, ok := ports[n]
    37  			if ok {
    38  				return portStr, nil
    39  			}
    40  			port, err := portpicker.PickUnusedPort()
    41  			if err != nil {
    42  				return "", err
    43  			}
    44  			portStr = strconv.Itoa(port)
    45  			ports[n] = portStr
    46  			return portStr, nil
    47  		case "WSLENV":
    48  			env, ok := os.LookupEnv(n)
    49  			if !ok {
    50  				return "", fmt.Errorf("environment variable %s is undefined", n)
    51  			}
    52  			return env, nil
    53  		case "WSL":
    54  			switch n {
    55  			case "SESSION_ID":
    56  				return sessionID, nil
    57  			case "HOST_IP":
    58  				ips, err := net.LookupIP("localhost")
    59  				if err != nil {
    60  					return "", err
    61  				}
    62  				if len(ips) == 0 {
    63  					return "", errors.New("no ip found for localhost")
    64  				}
    65  				return ips[0].String(), nil
    66  			default:
    67  				return "", fmt.Errorf("unknown variable WSL:%s", n)
    68  			}
    69  		default:
    70  			return capabilities.NoOPResolver(p, n)
    71  		}
    72  	}
    73  }