-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
file.go
68 lines (59 loc) · 1.32 KB
/
file.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package io
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
// ReadFile read the input file.
func ReadFile(input string) []byte {
b, err := ioutil.ReadFile(input)
if err != nil {
return nil
}
return b
}
// SaveFile saves the diagram into the output directory.
func SaveFile(fileName string, output string, data string) (*os.File, error) {
var file *os.File
cwd, err := filepath.Abs(filepath.Dir(""))
if err != nil {
log.Fatal(err)
}
filePath := cwd + output
// Check if output directory does not exits. In this case create it.
if _, err := os.Stat(filePath); os.IsNotExist(err) {
os.Mkdir(filePath, os.ModePerm)
}
// Create the output file.
file, err = os.Create(filepath.Join(filePath, fileName))
if isError(err) {
return nil, err
}
file, err = os.OpenFile(filepath.Join(filePath, fileName), os.O_RDWR, 0644)
if isError(err) {
return nil, err
}
defer file.Close()
_, err = file.WriteString(data)
if isError(err) {
return nil, err
}
return file, nil
}
// DeleteDiagram deletes a diagram.
func DeleteDiagram(fileName string) error {
err := os.Remove(fileName)
if isError(err) {
return err
}
return nil
}
// isError ia a generic function to check for errors.
func isError(err error) bool {
if err != nil {
fmt.Errorf("Could not save file: %v", err.Error())
}
return (err != nil)
}