110 lines
2.3 KiB
Go
110 lines
2.3 KiB
Go
package fileops
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
type DeleteResult struct {
|
|
File string
|
|
DeletedLines []int
|
|
}
|
|
|
|
// DeleteLinesInFile removes all lines matching pattern (fixed string) from the file.
|
|
// Returns the original 1-indexed line numbers that were deleted.
|
|
func DeleteLinesInFile(path, pattern string, dryRun bool) (DeleteResult, error) {
|
|
result := DeleteResult{File: path}
|
|
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
|
|
var kept []string
|
|
scanner := bufio.NewScanner(f)
|
|
lineNum := 0
|
|
for scanner.Scan() {
|
|
lineNum++
|
|
line := scanner.Text()
|
|
if strings.Contains(line, pattern) {
|
|
result.DeletedLines = append(result.DeletedLines, lineNum)
|
|
} else {
|
|
kept = append(kept, line)
|
|
}
|
|
}
|
|
f.Close()
|
|
if err := scanner.Err(); err != nil {
|
|
return result, err
|
|
}
|
|
|
|
if len(result.DeletedLines) == 0 || dryRun {
|
|
return result, nil
|
|
}
|
|
|
|
content := ""
|
|
if len(kept) > 0 {
|
|
content = strings.Join(kept, "\n") + "\n"
|
|
}
|
|
return result, atomicWrite(path, content)
|
|
}
|
|
|
|
// DeleteLinesInFileRegex removes lines matching the regex pattern from the file.
|
|
func DeleteLinesInFileRegex(path, pattern string, dryRun bool) (DeleteResult, error) {
|
|
result := DeleteResult{File: path}
|
|
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
|
|
re, err := compilePattern(pattern)
|
|
if err != nil {
|
|
f.Close()
|
|
return result, err
|
|
}
|
|
|
|
var kept []string
|
|
scanner := bufio.NewScanner(f)
|
|
lineNum := 0
|
|
for scanner.Scan() {
|
|
lineNum++
|
|
line := scanner.Text()
|
|
if re.MatchString(line) {
|
|
result.DeletedLines = append(result.DeletedLines, lineNum)
|
|
} else {
|
|
kept = append(kept, line)
|
|
}
|
|
}
|
|
f.Close()
|
|
if err := scanner.Err(); err != nil {
|
|
return result, err
|
|
}
|
|
|
|
if len(result.DeletedLines) == 0 || dryRun {
|
|
return result, nil
|
|
}
|
|
|
|
content := ""
|
|
if len(kept) > 0 {
|
|
content = strings.Join(kept, "\n") + "\n"
|
|
}
|
|
return result, atomicWrite(path, content)
|
|
}
|
|
|
|
func PrintDeleteResults(results []DeleteResult) {
|
|
totalFiles := 0
|
|
totalLines := 0
|
|
for _, r := range results {
|
|
if len(r.DeletedLines) == 0 {
|
|
continue
|
|
}
|
|
totalFiles++
|
|
totalLines += len(r.DeletedLines)
|
|
nums := formatLineNums(r.DeletedLines)
|
|
fmt.Printf("%s: deleted lines %s\n", r.File, nums)
|
|
}
|
|
fmt.Printf("%d file(s) modified, %d line(s) deleted.\n", totalFiles, totalLines)
|
|
}
|