go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/exec/execmock/gob_name.go (about)

     1  // Copyright 2023 The LUCI Authors.
     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 execmock
    16  
    17  import (
    18  	"fmt"
    19  	"reflect"
    20  )
    21  
    22  // gobName computes the serializable name for the Runner type.
    23  //
    24  // This is copied from gob.Register, minus the bug documented there.
    25  func gobName(value any) string {
    26  	// Default to printed representation for unnamed types
    27  	rt := reflect.TypeOf(value)
    28  	if rt.Kind() == reflect.Interface || rt.Kind() == reflect.Func {
    29  		panic(fmt.Sprintf("invalid Runner In or Out kind: %s", rt.Kind()))
    30  	}
    31  	name := rt.String()
    32  
    33  	// But for named types (or pointers to them), qualify with import path (but see inner comment).
    34  	// Dereference one pointer looking for a named type.
    35  	star := ""
    36  	if rt.Name() == "" {
    37  		if pt := rt; pt.Kind() == reflect.Ptr {
    38  			star = "*"
    39  			// This is intentionally different from gob.Register.
    40  			// See the comment there for why.
    41  			rt = pt.Elem()
    42  		}
    43  	}
    44  	if rt.Name() != "" {
    45  		if rt.PkgPath() == "" {
    46  			name = fmt.Sprintf("%s%s", star, rt.Name())
    47  		} else {
    48  			name = fmt.Sprintf("%s%s.%s", star, rt.PkgPath(), rt.Name())
    49  		}
    50  	}
    51  	return name
    52  }