2023-01-12 23:35:51 +01:00
|
|
|
// Copyright 2023 wanderer <a_mirre at utb dot cz>
|
2022-06-20 03:32:48 +02:00
|
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
|
2022-07-10 20:54:48 +02:00
|
|
|
package util
|
2022-06-20 03:32:48 +02:00
|
|
|
|
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"
|
|
|
|
)
|
2022-06-20 03:32:48 +02:00
|
|
|
|
2022-07-10 20:54:48 +02:00
|
|
|
// SanitiseFName clears spaces from the string that is supposed to be a file
|
2022-07-17 21:50:19 +02:00
|
|
|
// name so that the result is safer to use with e.g. latex.
|
2022-07-10 20:54:48 +02:00
|
|
|
func SanitiseFName(s string) string {
|
2022-07-17 21:50:19 +02:00
|
|
|
return strings.ReplaceAll(s, " ", "--")
|
2022-06-20 03:32:48 +02:00
|
|
|
}
|
2022-06-28 23:40:35 +02:00
|
|
|
|
2022-07-10 20:54:48 +02:00
|
|
|
// CreateFolder creates a folder at the specified path, if it doesn't already
|
2022-06-28 23:40:35 +02:00
|
|
|
// exist.
|
2022-07-10 20:54:48 +02:00
|
|
|
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
|
|
|
|
2022-07-10 20:54:48 +02:00
|
|
|
// CreatePath creates all folders in the provided path, if they don't already
|
2022-06-29 16:54:55 +02:00
|
|
|
// exist.
|
2022-07-10 20:54:48 +02:00
|
|
|
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,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|