cobble/parser.go

70 lines
1.7 KiB
Go
Raw Normal View History

package main
import (
"bufio"
"bytes"
"os"
)
var commentPrefix = []byte("--")
var requirementPrefix = []byte("requires:")
// Removes the provided prefix from the byte slice and removes
// any spaces leading or trailing the resulting slice.
//
// If the prefix is not present, nothing is removed except
// the leading and trailing spaces.
func cutPrefixAndTrim(b []byte, prefix []byte) []byte {
withoutPrefix, _ := bytes.CutPrefix(b, prefix)
return bytes.TrimSpace(withoutPrefix)
}
2024-07-12 01:15:37 +00:00
func StripComments(sql []byte) []byte {
scanner := bufio.NewScanner(bytes.NewReader(sql))
sqlWithoutComments := []byte{}
for scanner.Scan() {
currentBytes := scanner.Bytes()
if !bytes.HasPrefix(currentBytes, commentPrefix) {
sqlWithoutComments = append(sqlWithoutComments, currentBytes...)
sqlWithoutComments = append(sqlWithoutComments, []byte("\n")...)
}
}
totalLength := len(sqlWithoutComments)
if totalLength > 0 {
return sqlWithoutComments[:totalLength-1]
}
return sqlWithoutComments
}
// Extracts any migration headers present in the migration source file.
// Headers are left in comments of the form:
// -- <header-name>: ...
// Anything else than the known headers is ignored.
func gatherMigrationHeaders(migrationFile *os.File) MigrationHeaders {
scanner := bufio.NewScanner(migrationFile)
requirements := []string{}
for scanner.Scan() {
currentBytes := scanner.Bytes()
if !bytes.HasPrefix(currentBytes, commentPrefix) {
continue
}
commentBytes := cutPrefixAndTrim(currentBytes, commentPrefix)
if bytes.HasPrefix(commentBytes, requirementPrefix) {
reqName := cutPrefixAndTrim(commentBytes, requirementPrefix)
requirements = append(requirements, string(reqName))
}
}
return MigrationHeaders{Requirements: requirements}
}