Fixups + enable the commentFormatting linter (#1866)

* Add a space after // comments

For consistency, the commentFormatting lint checker suggests a space
after each // comment block. This commit handles all the spots in
the code where that is needed.

* Rewrite documentation on functions

Use the Go idiom of commenting:

* First sentence declares the purpose.
* First word is the name being declared

The reason this style is preferred is such that grep is able to find
names the user might be interested in. Consider e.g.,

    go doc -all pkg/ffmpeg | grep -i transcode

in which case a match will tell you the name of the function you are
interested in.

* Remove old code comment-blocks

There are some commented out old code blocks in the code base. These are
either 3 years old, or 2 years old. By now, I don't think their use is
going to come back any time soon, and Git will track old pieces of
deleted code anyway.

Opt for deletion.

* Reorder imports

Split stdlib imports from non-stdlib imports in files we are touching.

* Use a range over an iteration variable

Probably more go-idiomatic, and the code needed comment-fixing anyway.

* Use time.After rather than rolling our own

The idiom here is common enough that the stdlib contains a function for
it. Use the stdlib function over our own variant.

* Enable the commentFormatting linter
This commit is contained in:
SmallCoccinelle
2021-10-20 07:10:46 +02:00
committed by GitHub
parent e14bb8432c
commit 214a15bc40
17 changed files with 47 additions and 72 deletions

View File

@@ -38,8 +38,6 @@ linters:
linters-settings: linters-settings:
gocritic: gocritic:
disabled-checks: disabled-checks:
# Way too many errors to fix regarding comment formatting for now
- commentFormatting
- appendAssign - appendAssign
gofmt: gofmt:

View File

@@ -164,7 +164,7 @@ func (r *queryResolver) Version(ctx context.Context) (*models.Version, error) {
}, nil }, nil
} }
//Gets latest version (git shorthash commit for now) // Latestversion returns the latest git shorthash commit.
func (r *queryResolver) Latestversion(ctx context.Context) (*models.ShortVersion, error) { func (r *queryResolver) Latestversion(ctx context.Context) (*models.ShortVersion, error) {
ver, url, err := GetLatestVersion(ctx, true) ver, url, err := GetLatestVersion(ctx, true)
if err == nil { if err == nil {

View File

@@ -67,8 +67,8 @@ func (e *Encoder) Transcode(probeResult VideoFile, options TranscodeOptions) {
_, _ = e.runTranscode(probeResult, args) _, _ = e.runTranscode(probeResult, args)
} }
//transcode the video, remove the audio // TranscodeVideo transcodes the video, and removes the audio.
//in some videos where the audio codec is not supported by ffmpeg // In some videos where the audio codec is not supported by ffmpeg,
// ffmpeg fails if you try to transcode the audio // ffmpeg fails if you try to transcode the audio
func (e *Encoder) TranscodeVideo(probeResult VideoFile, options TranscodeOptions) { func (e *Encoder) TranscodeVideo(probeResult VideoFile, options TranscodeOptions) {
scale := calculateTranscodeScale(probeResult, options.MaxTranscodeSize) scale := calculateTranscodeScale(probeResult, options.MaxTranscodeSize)
@@ -87,7 +87,7 @@ func (e *Encoder) TranscodeVideo(probeResult VideoFile, options TranscodeOptions
_, _ = e.runTranscode(probeResult, args) _, _ = e.runTranscode(probeResult, args)
} }
//copy the video stream as is, transcode audio // TranscodeAudio will copy the video stream as is, and transcode audio.
func (e *Encoder) TranscodeAudio(probeResult VideoFile, options TranscodeOptions) { func (e *Encoder) TranscodeAudio(probeResult VideoFile, options TranscodeOptions) {
args := []string{ args := []string{
"-i", probeResult.Path, "-i", probeResult.Path,
@@ -99,7 +99,7 @@ func (e *Encoder) TranscodeAudio(probeResult VideoFile, options TranscodeOptions
_, _ = e.runTranscode(probeResult, args) _, _ = e.runTranscode(probeResult, args)
} }
//copy the video stream as is, drop audio // CopyVideo will copy the video stream as is, and drop the audio stream.
func (e *Encoder) CopyVideo(probeResult VideoFile, options TranscodeOptions) { func (e *Encoder) CopyVideo(probeResult VideoFile, options TranscodeOptions) {
args := []string{ args := []string{
"-i", probeResult.Path, "-i", probeResult.Path,

View File

@@ -72,8 +72,8 @@ var validAudioForMkv = []AudioCodec{Aac, Mp3, Vorbis, Opus}
var validAudioForWebm = []AudioCodec{Vorbis, Opus} var validAudioForWebm = []AudioCodec{Vorbis, Opus}
var validAudioForMp4 = []AudioCodec{Aac, Mp3} var validAudioForMp4 = []AudioCodec{Aac, Mp3}
//maps user readable container strings to ffprobe's format_name // ContainerToFfprobe maps user readable container strings to ffprobe's format_name.
//on some formats ffprobe can't differentiate // On some formats ffprobe can't differentiate
var ContainerToFfprobe = map[Container]string{ var ContainerToFfprobe = map[Container]string{
Mp4: Mp4Ffmpeg, Mp4: Mp4Ffmpeg,
M4v: M4vFfmpeg, M4v: M4vFfmpeg,
@@ -155,7 +155,8 @@ func IsValidForContainer(format Container, validContainers []Container) bool {
return false return false
} }
//extend stream validation check to take into account container // IsValidCombo checks if a codec/container combination is valid.
// Returns true on validity, false otherwise
func IsValidCombo(codecName string, format Container, supportedVideoCodecs []string) bool { func IsValidCombo(codecName string, format Container, supportedVideoCodecs []string) bool {
supportMKV := IsValidCodec(Mkv, supportedVideoCodecs) supportMKV := IsValidCodec(Mkv, supportedVideoCodecs)
supportHEVC := IsValidCodec(Hevc, supportedVideoCodecs) supportHEVC := IsValidCodec(Hevc, supportedVideoCodecs)
@@ -227,10 +228,6 @@ type FFProbe string
// Execute exec command and bind result to struct. // Execute exec command and bind result to struct.
func (f *FFProbe) NewVideoFile(videoPath string, stripExt bool) (*VideoFile, error) { func (f *FFProbe) NewVideoFile(videoPath string, stripExt bool) (*VideoFile, error) {
args := []string{"-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", "-show_error", videoPath} args := []string{"-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", "-show_error", videoPath}
//// Extremely slow on windows for some reason
//if runtime.GOOS != "windows" {
// args = append(args, "-count_frames")
//}
out, err := exec.Command(string(*f), args...).Output() out, err := exec.Command(string(*f), args...).Output()
if err != nil { if err != nil {
@@ -256,9 +253,6 @@ func parse(filePath string, probeJSON *FFProbeJSON, stripExt bool) (*VideoFile,
if result.JSON.Error.Code != 0 { if result.JSON.Error.Code != 0 {
return nil, fmt.Errorf("ffprobe error code %d: %s", result.JSON.Error.Code, result.JSON.Error.String) return nil, fmt.Errorf("ffprobe error code %d: %s", result.JSON.Error.Code, result.JSON.Error.String)
} }
//} else if (ffprobeResult.stderr.includes("could not find codec parameters")) {
// throw new Error(`FFProbe [${filePath}] -> Could not find codec parameters`);
//} // TODO nil_or_unsupported.(video_stream) && nil_or_unsupported.(audio_stream)
result.Path = filePath result.Path = filePath
result.Title = probeJSON.Format.Tags.Title result.Title = probeJSON.Format.Tags.Title

View File

@@ -2,8 +2,9 @@ package ffmpeg
import ( import (
"bytes" "bytes"
"github.com/stashapp/stash/pkg/logger"
"os" "os"
"github.com/stashapp/stash/pkg/logger"
) )
// detect file format from magic file number // detect file format from magic file number
@@ -37,11 +38,12 @@ func containsMatroskaSignature(buf, subType []byte) bool {
return buf[index-3] == 0x42 && buf[index-2] == 0x82 return buf[index-3] == 0x42 && buf[index-2] == 0x82
} }
//returns container as string ("" on error or no match) // MagicContainer returns the container type of a file path.
//implements only mkv or webm as ffprobe can't distinguish between them // Returns the zero-value on errors or no-match. Implements mkv or
//and not all browsers support mkv // webm only, as ffprobe can't distinguish between them and not all
func MagicContainer(file_path string) Container { // browsers support mkv
file, err := os.Open(file_path) func MagicContainer(filePath string) Container {
file, err := os.Open(filePath)
if err != nil { if err != nil {
logger.Errorf("[magicfile] %v", err) logger.Errorf("[magicfile] %v", err)
return "" return ""

View File

@@ -295,7 +295,3 @@ func Fatal(args ...interface{}) {
func Fatalf(format string, args ...interface{}) { func Fatalf(format string, args ...interface{}) {
logger.Fatalf(format, args...) logger.Fatalf(format, args...)
} }
//func WithRequest(req *http.Request) *logrus.Entry {
// return logger.WithFields(RequestFields(req))
//}

View File

@@ -10,7 +10,6 @@ func TestConcurrentConfigAccess(t *testing.T) {
i := GetInstance() i := GetInstance()
const workers = 8 const workers = 8
//const loops = 1000
const loops = 200 const loops = 200
var wg sync.WaitGroup var wg sync.WaitGroup
for k := 0; k < workers; k++ { for k := 0; k < workers; k++ {

View File

@@ -22,14 +22,13 @@ func excludeFiles(files []string, patterns []string) ([]string, int) {
return files, 0 return files, 0
} }
for i := 0; i < len(files); i++ { for _, f := range files {
if matchFileSimple(files[i], fileRegexps) { if matchFileSimple(f, fileRegexps) {
logger.Infof("File matched pattern. Excluding:\"%s\"", files[i]) logger.Infof("File matched pattern. Excluding:\"%s\"", f)
exclCount++ exclCount++
} else { } else {
// if pattern doesn't match add file to list // if pattern doesn't match add file to list
results = append(results, files[i]) results = append(results, f)
} }
} }
logger.Infof("Excluded %d file(s) from scan", exclCount) logger.Infof("Excluded %d file(s) from scan", exclCount)

View File

@@ -2,8 +2,9 @@ package manager
import ( import (
"fmt" "fmt"
"github.com/stashapp/stash/pkg/logger"
"testing" "testing"
"github.com/stashapp/stash/pkg/logger"
) )
var excludeTestFilenames = []string{ var excludeTestFilenames = []string{

View File

@@ -3,13 +3,14 @@ package manager
import ( import (
"database/sql" "database/sql"
"errors" "errors"
"github.com/stashapp/stash/pkg/studio"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/stashapp/stash/pkg/studio"
"github.com/stashapp/stash/pkg/models" "github.com/stashapp/stash/pkg/models"
"github.com/stashapp/stash/pkg/tag" "github.com/stashapp/stash/pkg/tag"
) )
@@ -81,8 +82,6 @@ func initParserFields() {
ret["title"] = newParserField("title", ".*", true) ret["title"] = newParserField("title", ".*", true)
ret["ext"] = newParserField("ext", ".*$", false) ret["ext"] = newParserField("ext", ".*$", false)
//I = new ParserField("i", undefined, "Matches any ignored word", false);
ret["d"] = newParserField("d", `(?:\.|-|_)`, false) ret["d"] = newParserField("d", `(?:\.|-|_)`, false)
ret["rating"] = newParserField("rating", `\d`, true) ret["rating"] = newParserField("rating", `\d`, true)
ret["performer"] = newParserField("performer", ".*", true) ret["performer"] = newParserField("performer", ".*", true)

View File

@@ -514,14 +514,8 @@ func (s *singleton) neededGenerate(scenes []*models.Scene, input models.Generate
var totals totalsGenerate var totals totalsGenerate
const timeout = 90 * time.Second const timeout = 90 * time.Second
// create a control channel through which to signal the counting loop when the timeout is reached // Set a deadline.
chTimeout := make(chan struct{}) chTimeout := time.After(timeout)
//run the timeout function in a separate thread
go func() {
time.Sleep(timeout)
chTimeout <- struct{}{}
}()
fileNamingAlgo := config.GetInstance().GetVideoFileNamingAlgorithm() fileNamingAlgo := config.GetInstance().GetVideoFileNamingAlgorithm()
overwrite := false overwrite := false

View File

@@ -432,7 +432,7 @@ func listKeys(i interface{}, addPrefix bool) string {
var query []string var query []string
v := reflect.ValueOf(i) v := reflect.ValueOf(i)
for i := 0; i < v.NumField(); i++ { for i := 0; i < v.NumField(); i++ {
//get key for struct tag // Get key for struct tag
rawKey := v.Type().Field(i).Tag.Get("db") rawKey := v.Type().Field(i).Tag.Get("db")
key := strings.Split(rawKey, ",")[0] key := strings.Split(rawKey, ",")[0]
if key == "id" { if key == "id" {
@@ -450,7 +450,7 @@ func updateSet(i interface{}, partial bool) string {
var query []string var query []string
v := reflect.ValueOf(i) v := reflect.ValueOf(i)
for i := 0; i < v.NumField(); i++ { for i := 0; i < v.NumField(); i++ {
//get key for struct tag // Get key for struct tag
rawKey := v.Type().Field(i).Tag.Get("db") rawKey := v.Type().Field(i).Tag.Get("db")
key := strings.Split(rawKey, ",")[0] key := strings.Split(rawKey, ",")[0]
if key == "id" { if key == "id" {

View File

@@ -106,13 +106,6 @@ func GetDataFromBase64String(encodedString string) ([]byte, error) {
// GetBase64StringFromData returns the given byte slice as a base64 encoded string // GetBase64StringFromData returns the given byte slice as a base64 encoded string
func GetBase64StringFromData(data []byte) string { func GetBase64StringFromData(data []byte) string {
return base64.StdEncoding.EncodeToString(data) return base64.StdEncoding.EncodeToString(data)
// Really slow
//result = regexp.MustCompile(`(.{60})`).ReplaceAllString(result, "$1\n")
//if result[len(result)-1:] != "\n" {
// result += "\n"
//}
//return result
} }
func ServeImage(image []byte, w http.ResponseWriter, r *http.Request) error { func ServeImage(image []byte, w http.ResponseWriter, r *http.Request) error {