refactor(json): add ability to delete author using the new json author file

This commit is contained in:
Slug-Boi
2025-04-02 18:25:14 +02:00
parent ec2f361583
commit 39781da299
2 changed files with 30 additions and 31 deletions
+23 -29
View File
@@ -1,11 +1,9 @@
package utils package utils
import ( import (
"bufio" "encoding/json"
"bytes"
"fmt" "fmt"
"os" "os"
"regexp"
"strings" "strings"
) )
@@ -71,47 +69,43 @@ func CheckAuthorFile() string {
func DeleteOneAuthor(author string) { func DeleteOneAuthor(author string) {
author_file := Find_authorfile() author_file := Find_authorfile()
if _, exists := Users[author]; !exists {
fmt.Println("User not found")
return
}
// open author_file // open author_file
file, err := os.OpenFile(author_file, os.O_RDWR, 0644) file, err := os.OpenFile(author_file, os.O_RDWR, 0666)
if err != nil { if err != nil {
fmt.Println("Error opening file: ", err) fmt.Println("Error opening file: ", err)
return return
} }
defer file.Close() // check that users aren't empty
if len(Users) < 1 {
// create regex to capture author line fmt.Println("No users to remove")
regexp, err := regexp.Compile(fmt.Sprintf("^(.+\\|%s\\|.+|%s\\|.+\\|.+)$", author, author))
if err != nil {
fmt.Println("Error compiling regex: ", err)
return return
} }
var b []byte usr := Users[author]
buf := bytes.NewBuffer(b)
// create a scanner for the file // Remove the user from the Author struct (try both short and long name)
scanner := bufio.NewScanner(file) delete(Authors.Authors, usr.Shortname)
delete(Authors.Authors, usr.Longname)
// write the header to the buffer
scanner.Scan()
buf.WriteString(scanner.Text() + "\n")
// check if author matches the regex and skip
for scanner.Scan() {
line := scanner.Text()
if regexp.MatchString(line) {
continue
}
buf.WriteString(line + "\n")
// marshal the struct back to json
data, err := json.MarshalIndent(Authors, "", " ")
if err != nil {
fmt.Println("Error marshalling json: ", err)
return
} }
// remove the last newline character
buf.Truncate(buf.Len() - 1)
// write the data to the file
file.Truncate(0) file.Truncate(0)
file.Seek(0, 0) file.Seek(0, 0)
buf.WriteTo(file) file.Write(data)
file.Close()
RemoveUser(author) RemoveUser(author)
} }
+5
View File
@@ -23,6 +23,9 @@ type Author struct {
Authors map[string]User Authors map[string]User
} }
// purely used for editing the author file later
var Authors = Author{}
var Users = map[string]User{} var Users = map[string]User{}
var DefExclude = []string{} var DefExclude = []string{}
var Groups = map[string][]User{} var Groups = map[string][]User{}
@@ -57,6 +60,8 @@ func Define_users(author_file string) {
os.Exit(2) os.Exit(2)
} }
Authors = auth
for _, usr := range auth.Authors { for _, usr := range auth.Authors {
Users[usr.Shortname] = usr Users[usr.Shortname] = usr
Users[usr.Longname] = usr Users[usr.Longname] = usr