math-optim/util/util.go

72 lines
1.5 KiB
Go
Raw Normal View History

2023-01-12 23:35:51 +01:00
// Copyright 2023 wanderer <a_mirre at utb dot cz>
// SPDX-License-Identifier: GPL-3.0-or-later
package util
2022-06-28 23:40:35 +02:00
import (
"errors"
2022-07-13 23:18:31 +02:00
"fmt"
2022-06-28 23:40:35 +02:00
"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, " ", "--")
}
2022-06-28 23:40:35 +02:00
// CreateFolder creates a folder at the specified path, if it doesn't already
2022-06-28 23:40:35 +02:00
// exist.
func CreateFolder(path string) error {
2022-06-28 23:40:35 +02:00
var err error
if _, err = os.Stat(path); errors.Is(err, os.ErrNotExist) {
2022-07-13 23:18:31 +02:00
printUtil("creating folder : " + path + " (if not exists)")
2022-06-28 23:40:35 +02:00
err = os.Mkdir(path, os.ModePerm)
if err != nil {
log.Println(err)
}
}
return err
}
2022-06-29 16:54:55 +02:00
// CreatePath creates all folders in the provided path, if they don't already
2022-06-29 16:54:55 +02:00
// exist.
func CreatePath(path string) error {
2022-06-29 16:54:55 +02:00
var err error
if _, err = os.Stat(path); errors.Is(err, os.ErrNotExist) {
2022-07-13 23:18:31 +02:00
printUtil("creating path : " + path + " (if not exists)")
2022-06-29 16:54:55 +02:00
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
log.Println(err)
}
}
return err
}
2022-07-13 23:18:31 +02:00
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,
)
}
}