Home  >  Article  >  Backend Development  >  "Rune text not terminated" error when trying to run gofmt -r using exec.Command

"Rune text not terminated" error when trying to run gofmt -r using exec.Command

WBOY
WBOYforward
2024-02-11 18:10:07663browse

尝试使用 exec.Command 运行 gofmt -r 时出现“符文文字未终止”错误

php Editor Youzi encountered a "rune text not terminated" error when using exec.Command to run gofmt -r. This error may be caused by a symbol in the command not terminating correctly. To solve this problem, we can check that the symbols in the command are paired correctly and make sure that each symbol has the correct terminator. Also, try using escape characters to handle commands that contain special symbols. I hope these methods can help developers who encounter the same problem!

Question content

In the following directory structure,

.
├── foo.go
├── go.mod
└── main.go

I have a foo.go which has a simple type definition:

package main

type foo struct {
    baz string
}

If I run ngofmt -r from the command line to replace the variable names, it works:

> gofmt -r 'foo -> bar' foo.go
package main

type bar struct {
    baz string
}

But if I try to use the program to do this from main.go

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    combinedoutput, err := exec.command("gofmt", "-r", "'foo -> bar'", "foo.go").combinedoutput()
    if err != nil {
        log.fatalf("gofmt foo.go: %v. combined output: %s", err, combinedoutput)
    }
    fmt.println(string(combinedoutput))
}

I get the error:

> go run main.go
2023/01/14 23:42:07 gofmt foo.go: exit status 2. Combined output: parsing pattern 'Foo  at 1:1: rune literal not terminated
exit status 1

Do you know what caused it?

Workaround

You do not need to quote arguments to exec.command; quoting is a feature of the shell and does not apply when making system calls. It's also not necessary, since in the shell quoting is to describe the parameters, but in exec.command the parameters are separated into parameters for the function call.

specific:

exec.command("gofmt", "-r", "'foo -> bar'", "foo.go")

should be

exec.Command("gofmt", "-r", "Foo -> Bar", "foo.go")

The above is the detailed content of "Rune text not terminated" error when trying to run gofmt -r using exec.Command. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete