-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
51 lines (43 loc) · 1.17 KB
/
writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package gomarkdown
import (
"fmt"
"os"
"path/filepath"
"strings"
)
const (
markdownSuffix = ".md"
)
type MarkdownWriter struct {
file *os.File
}
// NewMarkdownWriter creates a new MarkdownWriter instance and opens the file.
// If the directory in the filename does not exist, it will be created.
func NewMarkdownWriter(filename string, append bool) (*MarkdownWriter, error) {
// Ensure the filename ends with .md
if !strings.HasSuffix(filename, markdownSuffix) {
filename += markdownSuffix
}
// Ensure the directory exists by extracting the directory path from the filename
dir := filepath.Dir(filename)
err := os.MkdirAll(dir, 0755)
if err != nil {
return nil, fmt.Errorf("failed to create directories: %v", err)
}
var file *os.File
if append {
// Open the file in append mode
file, err = os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
} else {
// Create or overwrite the file in write mode
file, err = os.Create(filename)
}
if err != nil {
return nil, fmt.Errorf("failed to open file: %v", err)
}
return &MarkdownWriter{file: file}, nil
}
// Close closes the file
func (mw *MarkdownWriter) Close() error {
return mw.file.Close()
}