...

Source file src/github.com/xanzy/go-gitlab/strings.go

Documentation: github.com/xanzy/go-gitlab

     1  //
     2  // Copyright 2021, Sander van Harmelen
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  //
    16  
    17  package gitlab
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"reflect"
    23  )
    24  
    25  // Stringify attempts to create a reasonable string representation of types in
    26  // the Gitlab library.  It does things like resolve pointers to their values
    27  // and omits struct fields with nil values.
    28  func Stringify(message interface{}) string {
    29  	var buf bytes.Buffer
    30  	v := reflect.ValueOf(message)
    31  	stringifyValue(&buf, v)
    32  	return buf.String()
    33  }
    34  
    35  // stringifyValue was heavily inspired by the goprotobuf library.
    36  func stringifyValue(buf *bytes.Buffer, val reflect.Value) {
    37  	if val.Kind() == reflect.Ptr && val.IsNil() {
    38  		buf.WriteString("<nil>")
    39  		return
    40  	}
    41  
    42  	v := reflect.Indirect(val)
    43  
    44  	switch v.Kind() {
    45  	case reflect.String:
    46  		fmt.Fprintf(buf, `"%s"`, v)
    47  	case reflect.Slice:
    48  		buf.WriteByte('[')
    49  		for i := 0; i < v.Len(); i++ {
    50  			if i > 0 {
    51  				buf.WriteByte(' ')
    52  			}
    53  
    54  			stringifyValue(buf, v.Index(i))
    55  		}
    56  
    57  		buf.WriteByte(']')
    58  		return
    59  	case reflect.Struct:
    60  		if v.Type().Name() != "" {
    61  			buf.WriteString(v.Type().String())
    62  		}
    63  
    64  		buf.WriteByte('{')
    65  
    66  		var sep bool
    67  		for i := 0; i < v.NumField(); i++ {
    68  			fv := v.Field(i)
    69  			if fv.Kind() == reflect.Ptr && fv.IsNil() {
    70  				continue
    71  			}
    72  			if fv.Kind() == reflect.Slice && fv.IsNil() {
    73  				continue
    74  			}
    75  
    76  			if sep {
    77  				buf.WriteString(", ")
    78  			} else {
    79  				sep = true
    80  			}
    81  
    82  			buf.WriteString(v.Type().Field(i).Name)
    83  			buf.WriteByte(':')
    84  			stringifyValue(buf, fv)
    85  		}
    86  
    87  		buf.WriteByte('}')
    88  	default:
    89  		if v.CanInterface() {
    90  			fmt.Fprint(buf, v.Interface())
    91  		}
    92  	}
    93  }
    94  

View as plain text