-2

I have a Go project, where I wanted to generate a Go report card (https://goreportcard.com/)

One of the things that this report card is that it runs

 gofmt -s

On all files.

My repo contains around 25 Go files, the only flag that is raised is this one, on six files:

Line 1: warning: file is not gofmted with -s (gofmt)

I've been googling around on gofmt, but I really can't find what this actually means.

Here is an example of a file that raises the error:

package services

import (
    "github.com/heyjoakim/devops-21/models"
    log "github.com/sirupsen/logrus"
)

var d = GetDBInstance()

// GetUserID returns user ID for username
func GetUserID(username string) (uint, error) {
    var user models.User
    getUserIDErr := d.db.First(&user, "username = ?", username).Error
    if getUserIDErr != nil {
        log.WithFields(log.Fields{
            "err": getUserIDErr,
            "username": username,
        }).Error("Error in GetUserID")
    }
    return user.UserID, getUserIDErr
}

and here is a file that does not raise the error:

package services

import (
    "strconv"

    "github.com/heyjoakim/devops-21/models"
    log "github.com/sirupsen/logrus"
)

    func UpdateLatest(latest int) {
        var c models.Config
    
        err := d.db.First(&c, "key = ?", "latest").Error
        if err != nil {
            log.WithField("err", err).Error("Latest does not exist: DB err")
            c.ID = 0
            c.Key = "latest"
            c.Value = strconv.Itoa(latest)
            d.db.Create(&c)
        } else {
            err := d.db.Model(&models.Config{}).Where("key = ?", "latest").Update("Value", latest).Error
            if err != nil {
                log.WithField("err", err).Error("UpdateLatest: DB err")
            }
        }
    }

I really don't see why one raises some error on line 1, and the other doesn't?

What does this flag mean?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
crypto_confuse
  • 463
  • 1
  • 4
  • 9

1 Answers1

1

The command gofmt -s myfile.go prints the formatted file to stdout. The -s flag applies simplifications to the formatted file.

Run gofmt -s -d myfile.go to view the differences between the original file and the formatted file.

Run gofmt -s -w myfile.go to update the file to the desired formatting.

Replace myfile.go with . to operate on all files in the directory.

The documentation for the gofmt command is here.

Your files are not formatted. Run gofmt -s -w . in the directory to fix the files.