mirror of
https://github.com/Eggbertx/gochan.git
synced 2025-08-02 10:56:25 -07:00
Fix anti-patterns pointed out by DeepSource
But not the switch fallthroughs/expression lists, there's no benefit
This commit is contained in:
parent
497a3925e0
commit
55317504a1
17 changed files with 53 additions and 67 deletions
|
@ -7,7 +7,7 @@ import (
|
|||
"github.com/gochan-org/gochan/pkg/gcsql"
|
||||
)
|
||||
|
||||
func versionHandler(foundDatabaseVersion int, targetDatabaseVersion int) error {
|
||||
func versionHandler(foundDatabaseVersion, targetDatabaseVersion int) error {
|
||||
if foundDatabaseVersion < targetDatabaseVersion {
|
||||
for foundDatabaseVersion < targetDatabaseVersion {
|
||||
gclog.Printf(gclog.LStdLog, "Migrating databasefrom version %v to version %v", foundDatabaseVersion, foundDatabaseVersion+1)
|
||||
|
@ -29,7 +29,7 @@ func versionHandler(foundDatabaseVersion int, targetDatabaseVersion int) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func checkMigrationsExist(currentVersion int, target int) error {
|
||||
func checkMigrationsExist(currentVersion, target int) error {
|
||||
for i := currentVersion; i < target; i++ {
|
||||
if _, ok := migrations[i]; !ok {
|
||||
return fmt.Errorf("This version of the migrator does not contain a migration from version %v to %v, please upgrade the migrator", currentVersion, target)
|
||||
|
|
|
@ -90,13 +90,13 @@ func fixPostLinkingOnBoard(boardID int) error {
|
|||
}
|
||||
jumptable := make(map[int]int)
|
||||
for rows.Next() {
|
||||
var old int
|
||||
var new int
|
||||
err = rows.Scan(&old, &new)
|
||||
var oldTable int
|
||||
var newTable int
|
||||
err = rows.Scan(&oldTable, &newTable)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
jumptable[old] = new
|
||||
jumptable[oldTable] = newTable
|
||||
}
|
||||
|
||||
jumpTableFunc := func(intstring string) string {
|
||||
|
|
|
@ -4,7 +4,7 @@ import (
|
|||
"github.com/gochan-org/gochan/pkg/gcsql"
|
||||
)
|
||||
|
||||
func renameTable(tablename string, tableNameNew string) error {
|
||||
func renameTable(tablename, tableNameNew string) error {
|
||||
var sql = "ALTER TABLE DBPREFIX" + tablename + " RENAME TO DBPREFIX" + tableNameNew
|
||||
_, err := gcsql.ExecSQL(sql)
|
||||
return err
|
||||
|
|
|
@ -298,7 +298,7 @@ func BuildCatalog(boardID int) string {
|
|||
// Build builds the board and its thread files
|
||||
// if newBoard is true, it adds a row to DBPREFIXboards and fails if it exists
|
||||
// if force is true, it doesn't fail if the directories exist but does fail if it is a file
|
||||
func buildBoard(board *gcsql.Board, newBoard bool, force bool) error {
|
||||
func buildBoard(board *gcsql.Board, newBoard, force bool) error {
|
||||
var err error
|
||||
if board.Dir == "" {
|
||||
return ErrNoBoardDir
|
||||
|
@ -324,12 +324,10 @@ func buildBoard(board *gcsql.Board, newBoard bool, force bool) error {
|
|||
return errors.New(gclog.Printf(gclog.LErrorLog,
|
||||
dirIsAFileStr, dirPath))
|
||||
}
|
||||
} else {
|
||||
if err = os.Mkdir(dirPath, 0666); err != nil {
|
||||
} else if err = os.Mkdir(dirPath, 0666); err != nil {
|
||||
return errors.New(gclog.Printf(gclog.LErrorLog,
|
||||
genericErrStr, dirPath, err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
if resInfo != nil {
|
||||
if !force {
|
||||
|
@ -341,12 +339,10 @@ func buildBoard(board *gcsql.Board, newBoard bool, force bool) error {
|
|||
dirIsAFileStr, resPath))
|
||||
|
||||
}
|
||||
} else {
|
||||
if err = os.Mkdir(resPath, 0666); err != nil {
|
||||
} else if err = os.Mkdir(resPath, 0666); err != nil {
|
||||
return errors.New(gclog.Printf(gclog.LErrorLog,
|
||||
genericErrStr, resPath, err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
if srcInfo != nil {
|
||||
if !force {
|
||||
|
@ -357,12 +353,10 @@ func buildBoard(board *gcsql.Board, newBoard bool, force bool) error {
|
|||
return errors.New(gclog.Printf(gclog.LErrorLog,
|
||||
dirIsAFileStr, srcPath))
|
||||
}
|
||||
} else {
|
||||
if err = os.Mkdir(srcPath, 0666); err != nil {
|
||||
} else if err = os.Mkdir(srcPath, 0666); err != nil {
|
||||
return errors.New(gclog.Printf(gclog.LErrorLog,
|
||||
genericErrStr, srcPath, err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
if thumbInfo != nil {
|
||||
if !force {
|
||||
|
@ -373,12 +367,10 @@ func buildBoard(board *gcsql.Board, newBoard bool, force bool) error {
|
|||
return errors.New(gclog.Printf(gclog.LErrorLog,
|
||||
dirIsAFileStr, thumbPath))
|
||||
}
|
||||
} else {
|
||||
if err = os.Mkdir(thumbPath, 0666); err != nil {
|
||||
} else if err = os.Mkdir(thumbPath, 0666); err != nil {
|
||||
return errors.New(gclog.Printf(gclog.LErrorLog,
|
||||
genericErrStr, thumbPath, err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
if newBoard {
|
||||
board.CreatedOn = time.Now()
|
||||
|
@ -386,11 +378,9 @@ func buildBoard(board *gcsql.Board, newBoard bool, force bool) error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err = board.UpdateID(); err != nil {
|
||||
} else if err = board.UpdateID(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
BuildBoardPages(board)
|
||||
BuildThreads(true, board.ID, 0)
|
||||
gcsql.ResetBoardSectionArrays()
|
||||
|
|
|
@ -23,7 +23,7 @@ var (
|
|||
)
|
||||
|
||||
// ConnectToDB initializes the database connection and exits if there are any errors
|
||||
func ConnectToDB(host string, dbType string, dbName string, username string, password string, prefix string) {
|
||||
func ConnectToDB(host, dbType, dbName, username, password, prefix string) {
|
||||
var connStr string
|
||||
sqlReplacer = strings.NewReplacer(
|
||||
"DBNAME", dbName,
|
||||
|
|
|
@ -28,7 +28,7 @@ var (
|
|||
// If a version is found, execute the version check. Otherwise check for deprecated info
|
||||
// If no deprecated info is found, check if any databases exist prefixed with config.DBprefix
|
||||
// if no prefixed databases exist, assume this is a new installation
|
||||
func GetCompleteDatabaseVersion() (dbVersion int, dbFlag int, err error) {
|
||||
func GetCompleteDatabaseVersion() (dbVersion, dbFlag int, err error) {
|
||||
versionTableExists, err := doesTableExist("database_version")
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
|
|
|
@ -140,7 +140,7 @@ func GetExistingReplies(topPost int) (posts []Post, err error) {
|
|||
// GetExistingRepliesLimitedRev gets N amount of reply posts to a given thread, ordered by newest first.
|
||||
// Deprecated: This method was created to support old functionality during the database refactor of april 2020
|
||||
// The code should be changed to reflect the new database design
|
||||
func GetExistingRepliesLimitedRev(topPost int, limit int) (posts []Post, err error) {
|
||||
func GetExistingRepliesLimitedRev(topPost, limit int) (posts []Post, err error) {
|
||||
return getPostsExcecution(newestFirstLimited, topPost, limit)
|
||||
}
|
||||
|
||||
|
|
|
@ -160,7 +160,7 @@ func getStaffByID(id int) (*Staff, error) {
|
|||
}
|
||||
|
||||
// NewStaff creates a new staff account from a given username, password and rank
|
||||
func NewStaff(username string, password string, rank int) error {
|
||||
func NewStaff(username, password string, rank int) error {
|
||||
const sql = `INSERT INTO DBPREFIXstaff (username, password_checksum, global_rank)
|
||||
VALUES (?, ?, ?)`
|
||||
_, err := ExecSQL(sql, username, gcutil.BcryptSum(password), rank)
|
||||
|
@ -184,7 +184,7 @@ func getStaffID(username string) (int, error) {
|
|||
}
|
||||
|
||||
// CreateSession inserts a session for a given key and username into the database
|
||||
func CreateSession(key string, username string) error {
|
||||
func CreateSession(key, username string) error {
|
||||
const sql1 = `INSERT INTO DBPREFIXsessions (staff_id,data,expires) VALUES(?,?,?)`
|
||||
const sql2 = `UPDATE DBPREFIXstaff SET last_login = CURRENT_TIMESTAMP WHERE id = ?`
|
||||
staffID, err := getStaffID(username)
|
||||
|
@ -236,7 +236,7 @@ func getBoardIDFromURIOrNil(URI string) *int {
|
|||
}
|
||||
|
||||
// CreateFileBan creates a new ban on a file. If boards = nil, the ban is global.
|
||||
func CreateFileBan(fileChecksum string, staffName string, permaban bool, staffNote string, boardURI string) error {
|
||||
func CreateFileBan(fileChecksum, staffName string, permaban bool, staffNote, boardURI string) error {
|
||||
const sql = `INSERT INTO DBPREFIXfile_ban (board_id, staff_id, staff_note, checksum) VALUES board_id = ?, staff_id = ?, staff_note = ?, checksum = ?`
|
||||
staffID, err := getStaffID(staffName)
|
||||
if err != nil {
|
||||
|
@ -248,7 +248,7 @@ func CreateFileBan(fileChecksum string, staffName string, permaban bool, staffNo
|
|||
}
|
||||
|
||||
// CreateFileNameBan creates a new ban on a filename. If boards = nil, the ban is global.
|
||||
func CreateFileNameBan(fileName string, isRegex bool, staffName string, permaban bool, staffNote string, boardURI string) error {
|
||||
func CreateFileNameBan(fileName string, isRegex bool, staffName string, permaban bool, staffNote, boardURI string) error {
|
||||
const sql = `INSERT INTO DBPREFIXfilename_ban (board_id, staff_id, staff_note, filename, is_regex) VALUES board_id = ?, staff_id = ?, staff_note = ?, filename = ?, is_regex = ?`
|
||||
staffID, err := getStaffID(staffName)
|
||||
if err != nil {
|
||||
|
@ -260,7 +260,7 @@ func CreateFileNameBan(fileName string, isRegex bool, staffName string, permaban
|
|||
}
|
||||
|
||||
// CreateUserNameBan creates a new ban on a username. If boards = nil, the ban is global.
|
||||
func CreateUserNameBan(userName string, isRegex bool, staffName string, permaban bool, staffNote string, boardURI string) error {
|
||||
func CreateUserNameBan(userName string, isRegex bool, staffName string, permaban bool, staffNote, boardURI string) error {
|
||||
const sql = `INSERT INTO DBPREFIXusername_ban (board_id, staff_id, staff_note, username, is_regex) VALUES board_id = ?, staff_id = ?, staff_note = ?, username = ?, is_regex = ?`
|
||||
staffID, err := getStaffID(staffName)
|
||||
if err != nil {
|
||||
|
@ -274,8 +274,8 @@ func CreateUserNameBan(userName string, isRegex bool, staffName string, permaban
|
|||
// CreateUserBan creates either a full ip ban, or an ip ban for threads only, for a given IP.
|
||||
// Deprecated: This method was created to support old functionality during the database refactor of april 2020
|
||||
// The code should be changed to reflect the new database design
|
||||
func CreateUserBan(IP string, threadBan bool, staffName string, boardURI string, expires time.Time, permaban bool,
|
||||
staffNote string, message string, canAppeal bool, appealAt time.Time) error {
|
||||
func CreateUserBan(IP string, threadBan bool, staffName, boardURI string, expires time.Time, permaban bool,
|
||||
staffNote, message string, canAppeal bool, appealAt time.Time) error {
|
||||
const sql = `INSERT INTO DBPREFIXip_ban (board_id, staff_id, staff_note, is_thread_ban, ip, appeal_at, expires_at, permanent, message, can_appeal, issued_at, copy_posted_text, is_active)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,'OLD SYSTEM BAN, NO TEXT AVAILABLE',TRUE)`
|
||||
staffID, err := getStaffID(staffName)
|
||||
|
@ -485,7 +485,7 @@ ON ban.board_id = board.id`
|
|||
// name, filename and checksum may be empty strings and will be treated as not requested if done so
|
||||
// Deprecated: This method was created to support old functionality during the database refactor of april 2020
|
||||
// The code should be changed to reflect the new database design
|
||||
func CheckBan(ip string, name string, filename string, checksum string) (*BanInfo, error) {
|
||||
func CheckBan(ip, name, filename, checksum string) (*BanInfo, error) {
|
||||
ban := new(BanInfo)
|
||||
ipban, err1 := checkIPBan(ip)
|
||||
err1NoRows := (err1 == sql.ErrNoRows)
|
||||
|
@ -631,7 +631,7 @@ func InsertPost(post *Post, bump bool) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func createThread(boardID int, locked bool, stickied bool, anchored bool, cyclical bool) (threadID int, err error) {
|
||||
func createThread(boardID int, locked, stickied, anchored, cyclical bool) (threadID int, err error) {
|
||||
const sql = `INSERT INTO DBPREFIXthreads (board_id, locked, stickied, anchored, cyclical) VALUES (?,?,?,?,?)`
|
||||
//Retrieves next free ID, explicitly inserts it, keeps retrying until succesfull insert or until a non-pk error is encountered.
|
||||
//This is done because mysql doesnt support RETURNING and both LAST_INSERT_ID() and last_row_id() are not thread-safe
|
||||
|
@ -665,7 +665,7 @@ func bumpThread(threadID int) error {
|
|||
return err
|
||||
}
|
||||
|
||||
func appendFile(postID int, originalFilename string, filename string, checksum string, fileSize int, isSpoilered bool, width int, height int, thumbnailWidth int, thumbnailHeight int) error {
|
||||
func appendFile(postID int, originalFilename, filename, checksum string, fileSize int, isSpoilered bool, width, height, thumbnailWidth, thumbnailHeight int) error {
|
||||
const nextIDSQL = `SELECT COALESCE(MAX(file_order) + 1, 0) FROM DBPREFIXfiles WHERE post_id = ?`
|
||||
var nextID int
|
||||
err := QueryRowSQL(nextIDSQL, interfaceSlice(postID), interfaceSlice(&nextID))
|
||||
|
@ -762,7 +762,7 @@ func GetPostPassword(postID int) (password string, err error) {
|
|||
//UpdatePost updates a post with new information
|
||||
// Deprecated: This method was created to support old functionality during the database refactor of april 2020
|
||||
// The code should be changed to reflect the new database design
|
||||
func UpdatePost(postID int, email string, subject string, message template.HTML, messageRaw string) error {
|
||||
func UpdatePost(postID int, email, subject string, message template.HTML, messageRaw string) error {
|
||||
const sql = `UPDATE DBPREFIXposts SET email = ?, subject = ?, message = ?, message_raw = ? WHERE id = ?`
|
||||
_, err := ExecSQL(sql, email, subject, string(message), messageRaw)
|
||||
return err
|
||||
|
@ -905,7 +905,7 @@ func CreateDefaultAdminIfNoStaff() error {
|
|||
return err
|
||||
}
|
||||
|
||||
func createUser(username string, passwordEncrypted string, globalRank int) (userID int, err error) {
|
||||
func createUser(username, passwordEncrypted string, globalRank int) (userID int, err error) {
|
||||
const sqlInsert = `INSERT INTO DBPREFIXstaff (username, password_checksum, global_rank) VALUES (?,?,?)`
|
||||
const sqlSelect = `SELECT id FROM DBPREFIXstaff WHERE username = ?`
|
||||
//Excecuted in two steps this way because last row id functions arent thread safe, username is unique
|
||||
|
|
|
@ -145,7 +145,7 @@ func (board *Board) AbsolutePath(subpath ...string) string {
|
|||
|
||||
// WebPath returns a string that represents the file's path as accessible by a browser
|
||||
// fileType should be "boardPage", "threadPage", "upload", or "thumb"
|
||||
func (board *Board) WebPath(fileName string, fileType string) string {
|
||||
func (board *Board) WebPath(fileName, fileType string) string {
|
||||
var filePath string
|
||||
switch fileType {
|
||||
case "":
|
||||
|
|
|
@ -99,7 +99,7 @@ Example:
|
|||
[]interface{}{&id},
|
||||
[]interface{}{&intVal, &stringVal})
|
||||
*/
|
||||
func QueryRowSQL(query string, values []interface{}, out []interface{}) error {
|
||||
func QueryRowSQL(query string, values, out []interface{}) error {
|
||||
stmt, err := PrepareSQL(query)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
@ -61,9 +61,7 @@ var funcMap = template.FuncMap{
|
|||
// String functions
|
||||
// "arrToString": arrToString,
|
||||
"intToString": strconv.Itoa,
|
||||
"escapeString": func(a string) string {
|
||||
return html.EscapeString(a)
|
||||
},
|
||||
"escapeString": html.EscapeString,
|
||||
"formatFilesize": func(sizeInt int) string {
|
||||
size := float32(sizeInt)
|
||||
if size < 1000 {
|
||||
|
@ -87,7 +85,7 @@ var funcMap = template.FuncMap{
|
|||
},
|
||||
"truncateMessage": func(msg string, limit int, maxLines int) string {
|
||||
var truncated bool
|
||||
split := strings.SplitN(msg, "<br />", -1)
|
||||
split := strings.Split(msg, "<br />")
|
||||
|
||||
if len(split) > maxLines {
|
||||
split = split[:maxLines]
|
||||
|
|
|
@ -10,7 +10,7 @@ import (
|
|||
)
|
||||
|
||||
//TruncateHTML truncates a template.HTML string to a certain visible character limit and line limit
|
||||
func truncateHTML(htmlText template.HTML, characterLimit int, maxLines int) template.HTML {
|
||||
func truncateHTML(htmlText template.HTML, characterLimit, maxLines int) template.HTML {
|
||||
dom, err := x_html.Parse(strings.NewReader(string(htmlText)))
|
||||
if err != nil {
|
||||
gclog.Println(gclog.LErrorLog, err.Error())
|
||||
|
@ -30,9 +30,8 @@ func removeNextSiblings(node *x_html.Node) {
|
|||
node.Parent.RemoveChild(node)
|
||||
}
|
||||
|
||||
func truncateHTMLNodes(node *x_html.Node, charactersLeft int, linesLeft int) (charsLeft int, lineLeft int) {
|
||||
func truncateHTMLNodes(node *x_html.Node, charactersLeft, linesLeft int) (charsLeft, lineLeft int) {
|
||||
//Uses a depth first search to map nodes and remove the rest.
|
||||
|
||||
if node == nil {
|
||||
return charactersLeft, linesLeft
|
||||
}
|
||||
|
|
|
@ -17,7 +17,7 @@ const (
|
|||
sOtherError
|
||||
)
|
||||
|
||||
func createSession(key string, username string, password string, request *http.Request, writer http.ResponseWriter) int {
|
||||
func createSession(key, username, password string, request *http.Request, writer http.ResponseWriter) int {
|
||||
//returns 0 for successful, 1 for password mismatch, and 2 for other
|
||||
domain := request.Host
|
||||
var err error
|
||||
|
|
|
@ -108,7 +108,7 @@ func ServeCaptcha(writer http.ResponseWriter, request *http.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
func getCaptchaImage() (captchaID string, chaptchaB64 string) {
|
||||
func getCaptchaImage() (captchaID, chaptchaB64 string) {
|
||||
if !config.Config.UseCaptcha {
|
||||
return
|
||||
}
|
||||
|
|
|
@ -93,9 +93,9 @@ func MakePost(writer http.ResponseWriter, request *http.Request) {
|
|||
post.Password = gcutil.Md5Sum(password)
|
||||
|
||||
// Reverse escapes
|
||||
nameCookie = strings.Replace(formName, "&", "&", -1)
|
||||
nameCookie = strings.Replace(nameCookie, "\\'", "'", -1)
|
||||
nameCookie = strings.Replace(url.QueryEscape(nameCookie), "+", "%20", -1)
|
||||
nameCookie = strings.ReplaceAll(formName, "&", "&")
|
||||
nameCookie = strings.ReplaceAll(nameCookie, "\\'", "'")
|
||||
nameCookie = strings.ReplaceAll(url.QueryEscape(nameCookie), "+", "%20")
|
||||
|
||||
// add name and email cookies that will expire in a year (31536000 seconds)
|
||||
http.SetCookie(writer, &http.Cookie{Name: "name", Value: nameCookie, MaxAge: yearInSeconds})
|
||||
|
@ -223,8 +223,8 @@ func MakePost(writer http.ResponseWriter, request *http.Request) {
|
|||
}
|
||||
boardDir := _board.Dir
|
||||
filePath = path.Join(config.Config.DocumentRoot, "/"+boardDir+"/src/", post.Filename)
|
||||
thumbPath = path.Join(config.Config.DocumentRoot, "/"+boardDir+"/thumb/", strings.Replace(post.Filename, "."+filetype, "t."+thumbFiletype, -1))
|
||||
catalogThumbPath = path.Join(config.Config.DocumentRoot, "/"+boardDir+"/thumb/", strings.Replace(post.Filename, "."+filetype, "c."+thumbFiletype, -1))
|
||||
thumbPath = path.Join(config.Config.DocumentRoot, "/"+boardDir+"/thumb/", strings.ReplaceAll(post.Filename, "."+filetype, "t."+thumbFiletype))
|
||||
catalogThumbPath = path.Join(config.Config.DocumentRoot, "/"+boardDir+"/thumb/", strings.ReplaceAll(post.Filename, "."+filetype, "c."+thumbFiletype))
|
||||
|
||||
if err = ioutil.WriteFile(filePath, data, 0777); err != nil {
|
||||
gclog.Printf(gclog.LErrorLog, "Couldn't write file %q: %s", post.Filename, err.Error())
|
||||
|
|
|
@ -79,7 +79,7 @@ func getNewFilename() string {
|
|||
}
|
||||
|
||||
// find out what out thumbnail's width and height should be, partially ripped from Kusaba X
|
||||
func getThumbnailSize(w int, h int, size string) (newWidth int, newHeight int) {
|
||||
func getThumbnailSize(w, h int, size string) (newWidth, newHeight int) {
|
||||
var thumbWidth int
|
||||
var thumbHeight int
|
||||
|
||||
|
|
|
@ -38,8 +38,7 @@ func CheckAkismetAPIKey(key string) error {
|
|||
}
|
||||
|
||||
// CheckPostForSpam checks a given post for spam with Akismet. Only checks if Akismet API key is set.
|
||||
func CheckPostForSpam(userIP string, userAgent string, referrer string,
|
||||
author string, email string, postContent string) string {
|
||||
func CheckPostForSpam(userIP, userAgent, referrer, author, email, postContent string) string {
|
||||
if config.Config.AkismetAPIKey != "" {
|
||||
client := &http.Client{}
|
||||
data := url.Values{"blog": {"http://" + config.Config.SiteDomain}, "user_ip": {userIP}, "user_agent": {userAgent}, "referrer": {referrer},
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue