diff --git a/internal/header.go b/internal/header.go index 7a6a045..91ae004 100644 --- a/internal/header.go +++ b/internal/header.go @@ -170,20 +170,22 @@ func matchShebang(b []byte) []byte { return nil } -func assemble(line, header, content []byte, isUpdate bool) []byte { - if line != nil { - // line, content - // get content exclude the first line +func assemble(shebang, header, content []byte, isUpdate bool) []byte { + if shebang != nil { if !isUpdate { - content = content[len(line):] + // get content exclude the shebang + content = content[len(shebang):] } - // add \n if the first line do not end with \n - if line[len(line)-1] != '\n' { - line = append(line, '\n') + + // add \n if the shebang do not end with \n + if shebang[len(shebang)-1] != '\n' { + shebang = append(shebang, '\n') } - header = append(line, header...) + header = append(shebang, header...) } - // line, header, content + // 1. shebang + // 2. header + // 3. content header = append(header, content...) return header } diff --git a/internal/operation.go b/internal/operation.go index 5b9d769..d0959a1 100644 --- a/internal/operation.go +++ b/internal/operation.go @@ -196,14 +196,15 @@ func operationUpdate(path string, d fs.DirEntry, header []byte) func() { return } - // get the first line of the special file - line := matchShebang(content) + // get the shebang of the special file + shebang := matchShebang(content) file, err := os.Open(path) if err != nil { counter.failed++ slog.Error("open file error", slog.String("path", path), slog.String("err", err.Error())) return } + scanner := bufio.NewScanner(file) for scanner.Scan() { l := scanner.Bytes() @@ -211,6 +212,7 @@ func operationUpdate(path string, d fs.DirEntry, header []byte) func() { break } } + afterBlankLine := make([]byte, 0) // NOTE: scanner will not scan from the beginning for scanner.Scan() { @@ -221,8 +223,10 @@ func operationUpdate(path string, d fs.DirEntry, header []byte) func() { if err != nil { slog.Error("file close error") } + // assemble license header and modify the file - b := assemble(line, header, afterBlankLine, true) + b := assemble(shebang, header, afterBlankLine, true) + err = os.WriteFile(path, b, d.Type()) if err != nil { counter.failed++ @@ -293,10 +297,11 @@ func operationAdd(path string, d fs.DirEntry, header []byte) func() { return } - // get the first line of the special file - line := matchShebang(content) + // get the shebang of the special file + shebang := matchShebang(content) // assemble license header and modify the file - b := assemble(line, header, content, false) + b := assemble(shebang, header, content, false) + err = os.WriteFile(path, b, d.Type()) if err != nil { counter.failed++