-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcli_config.go
More file actions
68 lines (58 loc) · 1.88 KB
/
cli_config.go
File metadata and controls
68 lines (58 loc) · 1.88 KB
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 limen
import (
"bytes"
"crypto/md5" // #nosec G501 -- MD5 only for config fingerprint in calculateHash, not for crypto auth.
"encoding/json"
"fmt"
"os"
"path/filepath"
)
// calculateHash computes MD5 hash of the given bytes and returns hex string.
// Used only for deterministic config/schema file fingerprints, not for security.
func calculateHash(data []byte) string {
// #nosec G401 -- MD5 for content fingerprinting of CLI config output, not authentication
return fmt.Sprintf("%x", md5.Sum(data))
}
func (c *Config) serializeSchemasToJSON(schemas SchemaDefinitionMap) ([]byte, error) {
file := struct {
Schemas SchemaDefinitionMap `json:"schemas"`
UseAutoIncrementID bool `json:"useAutoIncrementID"`
}{
Schemas: schemas,
UseAutoIncrementID: c.Schema.IDGenerator == nil,
}
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetIndent("", " ")
if err := encoder.Encode(file); err != nil {
return nil, fmt.Errorf("failed to encode schemas: %w", err)
}
return buf.Bytes(), nil
}
func (c *Config) prepareCLIConfig(schemas SchemaDefinitionMap) error {
if c.CLI == nil || !c.CLI.Enabled {
return nil
}
outputPath := filepath.Join(".", ".limen", "schemas.json")
dir := filepath.Dir(outputPath)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create output directory: %w", err)
}
}
currentJSON, err := c.serializeSchemasToJSON(schemas)
if err != nil {
return fmt.Errorf("failed to serialize schemas: %w", err)
}
if _, err := os.Stat(outputPath); err == nil {
existingData, err := os.ReadFile(outputPath)
if err != nil {
return writeToFile(currentJSON, outputPath)
}
if calculateHash(existingData) == calculateHash(currentJSON) {
// schemas haven't changed, skip write
return nil
}
}
return writeToFile(currentJSON, outputPath)
}