Skip to content

Commit

Permalink
style: optimize variable naming
Browse files Browse the repository at this point in the history
  • Loading branch information
justlorain committed Jan 26, 2025
1 parent fef6025 commit 0e7eac2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 16 deletions.
22 changes: 12 additions & 10 deletions internal/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
17 changes: 11 additions & 6 deletions internal/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,21 +196,23 @@ 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()
if len(l) == 0 {
break
}
}

afterBlankLine := make([]byte, 0)
// NOTE: scanner will not scan from the beginning
for scanner.Scan() {
Expand All @@ -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++
Expand Down Expand Up @@ -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++
Expand Down

0 comments on commit 0e7eac2

Please sign in to comment.