math-optim/util/util.go
surtur fda5f46623
All checks were successful
continuous-integration/drone/push Build is passing
go(util): modify SanitiseFName, add test
2022-07-17 21:50:19 +02:00

72 lines
1.5 KiB
Go

// Copyright 2022 wanderer <a_mirre at utb dot cz>
// SPDX-License-Identifier: GPL-3.0-or-later
package util
import (
"errors"
"fmt"
"log"
"os"
"strings"
)
// SanitiseFName clears spaces from the string that is supposed to be a file
// name so that the result is safer to use with e.g. latex.
func SanitiseFName(s string) string {
return strings.ReplaceAll(s, " ", "--")
}
// CreateFolder creates a folder at the specified path, if it doesn't already
// exist.
func CreateFolder(path string) error {
var err error
if _, err = os.Stat(path); errors.Is(err, os.ErrNotExist) {
printUtil("creating folder : " + path + " (if not exists)")
err = os.Mkdir(path, os.ModePerm)
if err != nil {
log.Println(err)
}
}
return err
}
// CreatePath creates all folders in the provided path, if they don't already
// exist.
func CreatePath(path string) error {
var err error
if _, err = os.Stat(path); errors.Is(err, os.ErrNotExist) {
printUtil("creating path : " + path + " (if not exists)")
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
log.Println(err)
}
}
return err
}
func getUtilLogPrefix() string {
return " ***  util: "
}
func fmtUtilOut(input string) string {
return getUtilLogPrefix() + input
}
func printUtil(input string) {
if _, err := fmt.Fprintln(os.Stderr, fmtUtilOut(input)); err != nil {
fmt.Fprintf(
os.Stdout,
getUtilLogPrefix(),
"error while printing to stderr: %q\n * original message was: %q",
err, input,
)
}
}