nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: gobuffalo/buffalo
Pull request #2238 (2022-04-15 16:09:34)

HTTPError Error() avoid nil pointer dereference on nil Cause
The default renderer `Error()` method does not check for a `nil` `error` on the underlying `HTTPError` type. A `nil pointer dereference` can be triggered by calling for example on the default renderer: `c.Render(500, nil)`.

This PR changes the `HTTPError` `Error()` method to use `fmt.Sprint()` instead of calling `Error()` on the underlying `error` in `Cause`.


Patch:
diff --git a/errors.go b/errors.go
index f9859541..228bd386 100644
--- a/errors.go
+++ b/errors.go
@@ -30,7 +30,10 @@ func (h HTTPError) Unwrap() error {
 
 // Error returns the cause of the error as string.
 func (h HTTPError) Error() string {
-	return h.Cause.Error()
+	if h.Cause != nil {
+		return h.Cause.Error()
+	}
+	return "unknown cause"
 }
 
 // ErrorHandler interface for handling an error for a


Test patch:
diff --git a/errors_test.go b/errors_test.go
index 7042ade2..bf55f600 100644
--- a/errors_test.go
+++ b/errors_test.go
@@ -143,6 +143,18 @@ func Test_defaultErrorHandler_XML_production(t *testing.T) {
 	r.Contains(b, `</response>`)
 }
 
+func Test_defaultErrorHandler_nil_error(t *testing.T) {
+	r := require.New(t)
+	app := New(Options{})
+	app.GET("/", func(c Context) error {
+		return c.Error(http.StatusInternalServerError, nil)
+	})
+
+	w := httptest.New(app)
+	res := w.JSON("/").Get()
+	r.Equal(http.StatusInternalServerError, res.Code)
+}
+
 func Test_PanicHandler(t *testing.T) {
 	app := New(Options{})
 	app.GET("/string", func(c Context) error {
Repository: gobuffalo/pop
Pull request #539 (2020-04-18 15:51:28)

Expose sqlx Unsafe option (attempt 2)
This is just a copy of #368 as it has not been properly merged and is having conflicts now. Overall, it appears as it still can be considered for merge, so I'm making this new PR as I don't have other means to fix it. I don't think @solongordon would be against it from his side as we are from the same company.


Patch:
diff --git a/connection.go b/connection.go
index d922445..7155123 100644
--- a/connection.go
+++ b/connection.go
@@ -111,6 +111,9 @@ func (c *Connection) Open() error {
 	if details.ConnMaxLifetime > 0 {
 		db.SetConnMaxLifetime(details.ConnMaxLifetime)
 	}
+	if details.Unsafe {
+		db = db.Unsafe()
+	}
 	c.Store = &dB{db}
 
 	if d, ok := c.Dialect.(afterOpenable); ok {
diff --git a/connection_details.go b/connection_details.go
index cb172fd..6a132e1 100644
--- a/connection_details.go
+++ b/connection_details.go
@@ -42,7 +42,9 @@ type ConnectionDetails struct {
 	IdlePool int
 	// Defaults to 0 "unlimited". See https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime
 	ConnMaxLifetime time.Duration
-	Options         map[string]string
+	// Defaults to `false`. See https://godoc.org/github.com/jmoiron/sqlx#DB.Unsafe
+	Unsafe  bool
+	Options map[string]string
 	// Query string encoded options from URL. Example: "sslmode=disable"
 	RawOptions string
 }


Test patch:
diff --git a/config_test.go b/config_test.go
index 24f6816..9ac0c78 100644
--- a/config_test.go
+++ b/config_test.go
@@ -36,6 +36,7 @@ mysql:
   port: "3306"
   user: "root"
   password: "root"
+  unsafe: true
   options:
     readTimeout: 5s`)
 	conns, err := ParseConfig(config)
@@ -48,5 +49,17 @@ mysql:
 	r.Equal("3306", conns["mysql"].Port)
 	r.Equal(envy.Get("MYSQL_USER", "root"), conns["mysql"].User)
 	r.Equal(envy.Get("MYSQL_PASSWORD", "root"), conns["mysql"].Password)
+	r.True(conns["mysql"].Unsafe)
 	r.Equal("5s", conns["mysql"].Options["readTimeout"])
 }
+
+func Test_ParseConfigUnsafeDefault(t *testing.T) {
+	// Ensure that the default `unsafe` value is false.
+	r := require.New(t)
+	config := strings.NewReader(`
+mysql:
+  dialect: "mysql"`)
+	conns, err := ParseConfig(config)
+	r.NoError(err)
+	r.False(conns["mysql"].Unsafe)
+}
Repository: gobuffalo/pop
Pull request #612 (2020-12-23 05:57:16)

Fix migration table name
Fixes https://github.com/gobuffalo/pop/issues/587


Patch:
diff --git a/connection_details.go b/connection_details.go
index 76c165b..29c0ae4 100644
--- a/connection_details.go
+++ b/connection_details.go
@@ -179,6 +179,10 @@ func (cd *ConnectionDetails) OptionsString(s string) string {
 	}
 	if cd.Options != nil {
 		for k, v := range cd.Options {
+			if k == "migration_table_name" {
+				continue
+			}
+
 			s = fmt.Sprintf("%s&%s=%s", s, k, v)
 		}
 	}


Test patch:
diff --git a/connection_details_test.go b/connection_details_test.go
index 4121745..877c841 100644
--- a/connection_details_test.go
+++ b/connection_details_test.go
@@ -84,3 +84,22 @@ func Test_ConnectionDetails_Finalize_NoDB_NoURL(t *testing.T) {
 	err := cd.Finalize()
 	r.Error(err)
 }
+
+func Test_ConnectionDetails_OptionsString_Postgres(t *testing.T) {
+	r := require.New(t)
+	cd := &ConnectionDetails{
+		Dialect:  "postgres",
+		Database: "database",
+		Host:     "host",
+		Port:     "1234",
+		User:     "user",
+		Password: "pass",
+		Options: map[string]string{
+			"migration_table_name": "migrations",
+			"sslmode":              "require",
+		},
+	}
+
+	r.Equal("sslmode=require", cd.OptionsString(""))
+	r.Equal("migrations", cd.MigrationTableName())
+}
Repository: gobuffalo/pop
Pull request #630 (2021-03-31 18:43:14)

Allow passing args to `Order`
Allow passing arguments to Order clauses.

aeneasr: What does this address? Also, could you please add a test case?
duckbrain: This addresses that there is currently no way to safely pass arguments to `ORDER BY` clauses.

An actual use case I have is for a primitive ranking of search results, where results that match `name ILIKE '%query'` are sorted before results that have the search query elsewhere in the string.
aeneasr: Thank you for the explanation!
aeneasr: If you merge the development branch into yours the tests should pass!

Patch:
diff --git a/query.go b/query.go
index b9af399..ba981ef 100644
--- a/query.go
+++ b/query.go
@@ -145,19 +145,19 @@ func (q *Query) Where(stmt string, args ...interface{}) *Query {
 // Order will append an order clause to the query.
 //
 // 	c.Order("name desc")
-func (c *Connection) Order(stmt string) *Query {
-	return Q(c).Order(stmt)
+func (c *Connection) Order(stmt string, args ...interface{}) *Query {
+	return Q(c).Order(stmt, args...)
 }
 
 // Order will append an order clause to the query.
 //
 // 	q.Order("name desc")
-func (q *Query) Order(stmt string) *Query {
+func (q *Query) Order(stmt string, args ...interface{}) *Query {
 	if q.RawSQL.Fragment != "" {
 		log(logging.Warn, "Query is setup to use raw SQL")
 		return q
 	}
-	q.orderClauses = append(q.orderClauses, clause{stmt, []interface{}{}})
+	q.orderClauses = append(q.orderClauses, clause{stmt, args})
 	return q
 }
 


Test patch:
diff --git a/query_test.go b/query_test.go
index 7df5a99..8966836 100644
--- a/query_test.go
+++ b/query_test.go
@@ -118,6 +118,34 @@ func Test_Order(t *testing.T) {
 	a.Equal(ts("SELECT enemies.A FROM enemies AS enemies ORDER BY id desc, name desc"), sql)
 }
 
+func Test_Order_With_Args(t *testing.T) {
+	if PDB == nil {
+		t.Skip("skipping integration tests")
+	}
+	r := require.New(t)
+	transaction(func(tx *Connection) {
+		u1 := &Song{Title: "A"}
+		u2 := &Song{Title: "B"}
+		u3 := &Song{Title: "C"}
+		err := tx.Create(u1)
+		r.NoError(err)
+		err = tx.Create(u2)
+		r.NoError(err)
+		err = tx.Create(u3)
+		r.NoError(err)
+
+		var songs []Song
+		err = tx.Where("id in (?)", []uuid.UUID{u1.ID, u2.ID, u3.ID}).
+			Order("title > ? DESC", "A").Order("title").
+			All(&songs)
+		r.NoError(err)
+		r.Len(songs, 3)
+		r.Equal("B", songs[0].Title)
+		r.Equal("C", songs[1].Title)
+		r.Equal("A", songs[2].Title)
+	})
+}
+
 func Test_GroupBy(t *testing.T) {
 	if PDB == nil {
 		t.Skip("skipping integration tests")
Repository: goccy/go-yaml
Pull request #37 (2019-11-12 10:55:15)

Comments must be separated from other tokens by white space characters
ref: https://yaml.org/spec/1.2/spec.html#id2780069

仕様の方もコードの方も読み込みきれてないので、実装があってるかどうか少し不安なのですが、コメントは `#`の前にスペースが必要だと思います


Patch:
diff --git a/scanner/scanner.go b/scanner/scanner.go
index 63a3d92..47e9c88 100644
--- a/scanner/scanner.go
+++ b/scanner/scanner.go
@@ -476,13 +476,15 @@ func (s *Scanner) scan(ctx *Context) (pos int) {
 				return
 			}
 		case '#':
-			s.addBufferedTokenIfExists(ctx)
-			token, progress := s.scanComment(ctx)
-			ctx.addToken(token)
-			s.progressColumn(ctx, progress)
-			s.progressLine(ctx)
-			pos += progress
-			return
+			if ctx.bufferedSrc() == "" || ctx.previousChar() == ' ' {
+				s.addBufferedTokenIfExists(ctx)
+				token, progress := s.scanComment(ctx)
+				ctx.addToken(token)
+				s.progressColumn(ctx, progress)
+				s.progressLine(ctx)
+				pos += progress
+				return
+			}
 		case '\'', '"':
 			if ctx.bufferedSrc() == "" {
 				token, progress := s.scanQuote(ctx, c)


Test patch:
diff --git a/parser/parser_test.go b/parser/parser_test.go
index 2abd84b..c3cbc3b 100644
--- a/parser/parser_test.go
+++ b/parser/parser_test.go
@@ -259,6 +259,14 @@ d: e # comment
 a:
  b: c
 d: e
+`,
+		},
+		{
+			`
+a: b#notcomment
+`,
+			`
+a: b#notcomment
 `,
 		},
 		{
Repository: goccy/go-yaml
Pull request #52 (2019-12-04 15:00:17)

Fix parsing error of document like  `a: 0 - 1`
T/O


Patch:
diff --git a/scanner/context.go b/scanner/context.go
index d7f70df..0ca04e1 100644
--- a/scanner/context.go
+++ b/scanner/context.go
@@ -8,26 +8,28 @@ import (
 
 // Context context at scanning
 type Context struct {
-	idx         int
-	size        int
-	src         []rune
-	buf         []rune
-	obuf        []rune
-	tokens      token.Tokens
-	isRawFolded bool
-	isLiteral   bool
-	isFolded    bool
-	literalOpt  string
+	idx          int
+	size         int
+	src          []rune
+	buf          []rune
+	obuf         []rune
+	tokens       token.Tokens
+	isRawFolded  bool
+	isLiteral    bool
+	isFolded     bool
+	isSingleLine bool
+	literalOpt   string
 }
 
 func newContext(src []rune) *Context {
 	return &Context{
-		idx:    0,
-		size:   len(src),
-		src:    src,
-		tokens: token.Tokens{},
-		buf:    make([]rune, 0, len(src)),
-		obuf:   make([]rune, 0, len(src)),
+		idx:          0,
+		size:         len(src),
+		src:          src,
+		tokens:       token.Tokens{},
+		buf:          make([]rune, 0, len(src)),
+		obuf:         make([]rune, 0, len(src)),
+		isSingleLine: true,
 	}
 }
 
diff --git a/scanner/scanner.go b/scanner/scanner.go
index fdcffe8..dc68659 100644
--- a/scanner/scanner.go
+++ b/scanner/scanner.go
@@ -303,6 +303,7 @@ func (s *Scanner) scanNewLine(ctx *Context, c rune) {
 	}
 	ctx.addBuf(' ')
 	ctx.addOriginBuf(c)
+	ctx.isSingleLine = false
 	s.progressLine(ctx)
 }
 
@@ -378,6 +379,13 @@ func (s *Scanner) scan(ctx *Context) (pos int) {
 				s.progressColumn(ctx, 1)
 				continue
 			}
+			if ctx.bufferedSrc() != "" && ctx.isSingleLine {
+				// '-' is literal
+				ctx.addBuf(c)
+				ctx.addOriginBuf(c)
+				s.progressColumn(ctx, 1)
+				continue
+			}
 			nc := ctx.nextChar()
 			if nc == ' ' {
 				s.addBufferedTokenIfExists(ctx)


Test patch:
diff --git a/parser/parser_test.go b/parser/parser_test.go
index 5577f96..1e6d556 100644
--- a/parser/parser_test.go
+++ b/parser/parser_test.go
@@ -158,6 +158,14 @@ r: s
 - b
 - c - d - e
 - f
+`,
+		},
+		{
+			`
+a: 0 - 1
+`,
+			`
+a: 0 - 1
 `,
 		},
 		{`
Repository: goccy/go-yaml
Pull request #57 (2019-12-11 07:56:09)

Remove unnecessary spaces at right side
T/O


Patch:
diff --git a/scanner/context.go b/scanner/context.go
index 0ca04e1..0f500fa 100644
--- a/scanner/context.go
+++ b/scanner/context.go
@@ -64,6 +64,17 @@ func (c *Context) addOriginBuf(r rune) {
 	c.obuf = append(c.obuf, r)
 }
 
+func (c *Context) removeRightSpaceFromBuf() int {
+	trimmedBuf := strings.TrimRight(string(c.obuf), " ")
+	buflen := len([]rune(trimmedBuf))
+	diff := len(c.obuf) - buflen
+	if diff > 0 {
+		c.obuf = c.obuf[:buflen]
+		c.buf = []rune(c.bufferedSrc())
+	}
+	return diff
+}
+
 func (c *Context) isDocument() bool {
 	return c.isLiteral || c.isFolded || c.isRawFolded
 }
diff --git a/scanner/scanner.go b/scanner/scanner.go
index dc68659..d8bb770 100644
--- a/scanner/scanner.go
+++ b/scanner/scanner.go
@@ -296,6 +296,19 @@ func (s *Scanner) scanNewLine(ctx *Context, c rune) {
 		s.savedPos = s.pos()
 		s.savedPos.Column -= len([]rune(ctx.bufferedSrc()))
 	}
+
+	// if the following case, origin buffer has unnecessary two spaces.
+	// So, `removeRightSpaceFromOriginBuf` remove them, also fix column number too.
+	// ---
+	// a:[space][space]
+	//   b: c
+	removedNum := ctx.removeRightSpaceFromBuf()
+	if removedNum > 0 {
+		s.column -= removedNum
+		s.offset -= removedNum
+		s.savedPos.Column -= removedNum
+	}
+
 	if ctx.isEOS() {
 		s.addBufferedTokenIfExists(ctx)
 	} else if s.isAnchor {


Test patch:
diff --git a/parser/parser_test.go b/parser/parser_test.go
index 1e6d556..272c560 100644
--- a/parser/parser_test.go
+++ b/parser/parser_test.go
@@ -440,6 +440,35 @@ a: |
 
    ccccccc
 d: eeeeeeeeeeeeeeeee
+`,
+		},
+		{
+			`
+a: b    
+  c
+`,
+			`
+a: b c
+`,
+		},
+		{
+			`
+a:    
+  b: c
+`,
+			`
+a:
+  b: c
+`,
+		},
+		{
+			`
+a: b    
+c: d
+`,
+			`
+a: b
+c: d
 `,
 		},
 	}
Repository: goccy/go-yaml
Pull request #62 (2019-12-14 03:05:06)

Supports default value in decoding for struct
resolve https://github.com/goccy/go-yaml/issues/61

Do not create a new value with `reflect.New`, reuse the argument of `Decode ()` .


Patch:
diff --git a/decode.go b/decode.go
index 3718e01..dd739d1 100644
--- a/decode.go
+++ b/decode.go
@@ -529,7 +529,6 @@ func (d *Decoder) decodeStruct(dst reflect.Value, src ast.Node) error {
 		return nil
 	}
 	structType := dst.Type()
-	structValue := reflect.New(structType)
 	structFieldMap, err := structFieldMap(structType)
 	if err != nil {
 		return errors.Wrapf(err, "failed to create struct field map")
@@ -555,7 +554,7 @@ func (d *Decoder) decodeStruct(dst reflect.Value, src ast.Node) error {
 		}
 		structField := structFieldMap[field.Name]
 		if structField.IsInline {
-			fieldValue := structValue.Elem().FieldByName(field.Name)
+			fieldValue := dst.FieldByName(field.Name)
 			if !fieldValue.CanSet() {
 				return xerrors.Errorf("cannot set embedded type as unexported field %s.%s", field.PkgPath, field.Name)
 			}
@@ -593,7 +592,7 @@ func (d *Decoder) decodeStruct(dst reflect.Value, src ast.Node) error {
 			continue
 		}
 		delete(unknownFields, structField.RenderName)
-		fieldValue := structValue.Elem().FieldByName(field.Name)
+		fieldValue := dst.FieldByName(field.Name)
 		if fieldValue.Type().Kind() == reflect.Ptr && src.Type() == ast.NullType {
 			// set nil value to pointer
 			fieldValue.Set(reflect.Zero(fieldValue.Type()))
@@ -617,7 +616,7 @@ func (d *Decoder) decodeStruct(dst reflect.Value, src ast.Node) error {
 		fieldValue.Set(d.castToAssignableValue(newFieldValue, fieldValue.Type()))
 	}
 	if d.validator != nil {
-		if err := d.validator.Struct(structValue.Interface()); err != nil {
+		if err := d.validator.Struct(dst.Interface()); err != nil {
 			ev := reflect.ValueOf(err)
 			if ev.Type().Kind() == reflect.Slice {
 				for i := 0; i < ev.Len(); i++ {
@@ -641,7 +640,6 @@ func (d *Decoder) decodeStruct(dst reflect.Value, src ast.Node) error {
 			return errors.ErrSyntax(fmt.Sprintf(`unknown field "%s"`, key), node.GetToken())
 		}
 	}
-	dst.Set(structValue.Elem())
 	if foundErr != nil {
 		return errors.Wrapf(foundErr, "failed to decode value")
 	}


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 2d882fb..e42ada5 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -1194,6 +1194,35 @@ b_yaml: b_yaml_value
 	}
 }
 
+func TestDecoder_DefaultValues(t *testing.T) {
+	v := struct {
+		A string `yaml:"a"`
+		B string `yaml:"b"`
+		c string // private
+	}{
+		B: "defaultBValue",
+		c: "defaultCValue",
+	}
+
+	const src = `---
+a: a_value
+`
+	if err := yaml.NewDecoder(strings.NewReader(src)).Decode(&v); err != nil {
+		t.Fatalf(`parsing should succeed: %s`, err)
+	}
+	if v.A != "a_value" {
+		t.Fatalf("v.A should be `a_value`, got `%s`", v.A)
+	}
+
+	if v.B != "defaultBValue" {
+		t.Fatalf("v.B should be `defaultValue`, got `%s`", v.B)
+	}
+
+	if v.c != "defaultCValue" {
+		t.Fatalf("v.c should be `defaultCValue`, got `%s`", v.c)
+	}
+}
+
 func Example_YAMLTags() {
 	yml := `---
 foo: 1
Repository: goccy/go-yaml
Pull request #91 (2020-03-07 01:17:08)

Fix empty map encoding style
Hi @goccy !!  

I want to encode "empty map" like "[empty slice](https://github.com/goccy/go-yaml/pull/81)" ( like go-yaml/yaml ).

| | go-yaml/yaml | encoding/json | goccy/go-yaml v1.4.0 | 
| --- | --- | --- | --- |
| empty map | `a: {}` | `{"a": {}}` | `a: \n{}` |
| play.golang.org | [here](https://play.golang.org/p/K3AyEvSBa4l) | [here](https://play.golang.org/p/3HzSIobVtDl) | [here](https://play.golang.org/p/t-EX0RvQ-Vk) |

```go
package main

import (
	"fmt"

	"github.com/goccy/go-yaml"
)

func main() {
	tests := []struct {
		value interface{}
	}{
		{
			value: struct {
				A map[string]string `yaml:"a"`
			}{
				A: map[string]string{"b":"c"},
			},
		},
		{
			value: struct {
				A map[string]string `yaml:"a"`
			}{
				A: map[string]string{},
			},
		},
	}
	
	for _, tt := range tests {
		d, _ := yaml.Marshal(tt.value)
		fmt.Printf("%s\n", string(d))
	}
}
```

### before

```
a:
  b: c

a:
{}
```

### after

```
a:
  b: c

a: {}
```

Thank you for your GREAT Go-libs !! ( go-yaml 👍 go-graphviz 👍 )


Patch:
diff --git a/encode.go b/encode.go
index 21b33eb..ca93249 100644
--- a/encode.go
+++ b/encode.go
@@ -299,7 +299,11 @@ func (e *Encoder) encodeMapSlice(value MapSlice, column int) (ast.Node, error) {
 }
 
 func (e *Encoder) encodeMap(value reflect.Value, column int) ast.Node {
-	node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle)
+	isFlowStyle := e.isFlowStyle
+	if value.Len() == 0 {
+		isFlowStyle = true
+	}
+	node := ast.Mapping(token.New("", "", e.pos(column)), isFlowStyle)
 	keys := []string{}
 	for _, k := range value.MapKeys() {
 		keys = append(keys, k.Interface().(string))


Test patch:
diff --git a/encode_test.go b/encode_test.go
index 09cb2c5..23ea618 100644
--- a/encode_test.go
+++ b/encode_test.go
@@ -234,6 +234,14 @@ func TestEncoder(t *testing.T) {
 				1, []string{},
 			},
 		},
+		{
+			"a: {}\n",
+			struct {
+				A map[string]interface{}
+			}{
+				map[string]interface{}{},
+			},
+		},
 		{
 			"a: b\nc: d\n",
 			struct {
Repository: goccy/go-yaml
Pull request #92 (2020-03-07 03:08:31)

Fix handling of dash character
ref #88

`ctx.isSingleLine` condition was not required ...


Patch:
diff --git a/scanner/scanner.go b/scanner/scanner.go
index 2622847..0b287bb 100644
--- a/scanner/scanner.go
+++ b/scanner/scanner.go
@@ -259,7 +259,9 @@ func (s *Scanner) scanComment(ctx *Context) (tk *token.Token, pos int) {
 func (s *Scanner) scanLiteral(ctx *Context, c rune) {
 	ctx.addOriginBuf(c)
 	if ctx.isEOS() {
-		ctx.addBuf(c)
+		if c != '\r' && c != '\n' {
+			ctx.addBuf(c)
+		}
 		value := ctx.bufferedSrc()
 		ctx.addToken(token.New(string(value), string(ctx.obuf), s.pos()))
 		ctx.resetBuffer()
@@ -421,7 +423,7 @@ func (s *Scanner) scan(ctx *Context) (pos int) {
 				s.progressColumn(ctx, 1)
 				continue
 			}
-			if ctx.existsBuffer() && ctx.isSingleLine {
+			if ctx.existsBuffer() {
 				// '-' is literal
 				ctx.addBuf(c)
 				ctx.addOriginBuf(c)


Test patch:
diff --git a/parser/parser_test.go b/parser/parser_test.go
index 73a89ff..f4747c3 100644
--- a/parser/parser_test.go
+++ b/parser/parser_test.go
@@ -470,6 +470,33 @@ c: d
 			`
 a: b
 c: d
+`,
+		},
+		{
+			`
+- ab - cd
+- ef - gh
+`,
+			`
+- ab - cd
+- ef - gh
+`,
+		},
+		{
+			`
+- 0 - 1
+ - 2 - 3
+`,
+			`
+- 0 - 1 - 2 - 3
+`,
+		},
+		{
+			`
+a - b - c: value
+`,
+			`
+a - b - c: value
 `,
 		},
 	}
Repository: goccy/go-yaml
Pull request #93 (2020-03-07 06:11:44)

Support "c-directives-end marker only" document.
Hi @goccy !

I did a minor fix. 

| | go-yaml/yaml | goccy/go-yaml v1.4.1 | 
| --- | --- | --- | 
| `---\n` | can decode | panic | 
| play.golang.org | [here](https://play.golang.org/p/lM7J0n6wpoP) | [here](https://play.golang.org/p/-cQ7iqGMnB) |

### `---\n` is valid YAML ?

I referred to "9.1.4. Explicit Documents" in https://yaml.org/spec/1.2/spec.pdf

Thank you !!


Patch:
diff --git a/parser/parser.go b/parser/parser.go
index 75734cc..ea14aab 100644
--- a/parser/parser.go
+++ b/parser/parser.go
@@ -335,6 +335,9 @@ func (p *parser) parseDocument(ctx *context) (*ast.Document, error) {
 }
 
 func (p *parser) parseToken(ctx *context, tk *token.Token) (ast.Node, error) {
+	if tk == nil {
+		return nil, nil
+	}
 	if tk.NextType() == token.MappingValueType {
 		return p.parseMappingValue(ctx)
 	}


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 254ab30..323d3f8 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -687,6 +687,10 @@ func TestDecoder(t *testing.T) {
 			"%YAML 1.2\n---\n",
 			(*struct{})(nil),
 		},
+		{
+			"---\n",
+			(*struct{})(nil),
+		},
 		{
 			"a: !!binary gIGC\n",
 			map[string]string{"a": "\x80\x81\x82"},
Repository: goccy/go-yaml
Pull request #102 (2020-05-28 08:35:45)

Support decoding for MapItem and MapSlice
```go
yml := `---
a: 1
b: 2
`
var v yaml.MapSlice
yaml.Unmarshal([]byte(yml), &v)
fmt.Println(v) // [{a 1} {b 2}]
```


Patch:
diff --git a/decode.go b/decode.go
index 1fc1300..4a10e89 100644
--- a/decode.go
+++ b/decode.go
@@ -408,8 +408,14 @@ func (d *Decoder) decodeValue(dst reflect.Value, src ast.Node) error {
 	case reflect.Array:
 		return d.decodeArray(dst, src)
 	case reflect.Slice:
+		if mapSlice, ok := dst.Addr().Interface().(*MapSlice); ok {
+			return d.decodeMapSlice(mapSlice, src)
+		}
 		return d.decodeSlice(dst, src)
 	case reflect.Struct:
+		if mapItem, ok := dst.Addr().Interface().(*MapItem); ok {
+			return d.decodeMapItem(mapItem, src)
+		}
 		return d.decodeStruct(dst, src)
 	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
 		v := d.nodeToValue(src)
@@ -882,6 +888,65 @@ func (d *Decoder) decodeSlice(dst reflect.Value, src ast.Node) error {
 	return nil
 }
 
+func (d *Decoder) decodeMapItem(dst *MapItem, src ast.Node) error {
+	mapNode, err := d.getMapNode(src)
+	if err != nil {
+		return errors.Wrapf(err, "failed to get map node")
+	}
+	if mapNode == nil {
+		return nil
+	}
+	mapIter := mapNode.MapRange()
+	if !mapIter.Next() {
+		return nil
+	}
+	key := mapIter.Key()
+	value := mapIter.Value()
+	if key.Type() == ast.MergeKeyType {
+		if err := d.decodeMapItem(dst, value); err != nil {
+			return errors.Wrapf(err, "failed to decode map with merge key")
+		}
+		return nil
+	}
+	*dst = MapItem{
+		Key:   d.nodeToValue(key),
+		Value: d.nodeToValue(value),
+	}
+	return nil
+}
+
+func (d *Decoder) decodeMapSlice(dst *MapSlice, src ast.Node) error {
+	mapNode, err := d.getMapNode(src)
+	if err != nil {
+		return errors.Wrapf(err, "failed to get map node")
+	}
+	if mapNode == nil {
+		return nil
+	}
+	mapSlice := MapSlice{}
+	mapIter := mapNode.MapRange()
+	for mapIter.Next() {
+		key := mapIter.Key()
+		value := mapIter.Value()
+		if key.Type() == ast.MergeKeyType {
+			var m MapSlice
+			if err := d.decodeMapSlice(&m, value); err != nil {
+				return errors.Wrapf(err, "failed to decode map with merge key")
+			}
+			for _, v := range m {
+				mapSlice = append(mapSlice, v)
+			}
+			continue
+		}
+		mapSlice = append(mapSlice, MapItem{
+			Key:   d.nodeToValue(key),
+			Value: d.nodeToValue(value),
+		})
+	}
+	*dst = mapSlice
+	return nil
+}
+
 func (d *Decoder) decodeMap(dst reflect.Value, src ast.Node) error {
 	mapNode, err := d.getMapNode(src)
 	if err != nil {


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 323d3f8..27dacc5 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -566,6 +566,18 @@ func TestDecoder(t *testing.T) {
 			}{1},
 		},
 
+		{
+			"a: 1\n",
+			yaml.MapItem{Key: "a", Value: 1},
+		},
+		{
+			"a: 1\nb: 2\nc: 3\n",
+			yaml.MapSlice{
+				{Key: "a", Value: 1},
+				{Key: "b", Value: 2},
+				{Key: "c", Value: 3},
+			},
+		},
 		{
 			"v:\n- A\n- 1\n- B:\n  - 2\n  - 3\n",
 			map[string]interface{}{