-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
870 lines (729 loc) · 23.4 KB
/
main.go
File metadata and controls
870 lines (729 loc) · 23.4 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
const version = "v1.2.3"
const bufSize = 4 << 20 // 4MB
const chunkSize = 64 << 20 // 64MB
const indexInterval = 1000000 // every 1M lines
// config holds all the configuration for the DTS tool.
type config struct {
filename string
filesN int
linesN int64
noHeader bool
quiet bool
outputDir string
baseName string
rangeStart string
rangeEnd string
}
func main() {
// --- Interactive Mode Detection ---
// If on Windows and run with a single argument (the file to be split),
// enter interactive mode.
if runtime.GOOS == "windows" && len(os.Args) == 2 && !strings.HasPrefix(os.Args[1], "-") {
runInteractiveMode(os.Args[1])
return
}
var cfg config
// Flag definitions
filesN := flag.Int("f", 0, "Split into N equal files")
flag.IntVar(filesN, "files", 0, "Alias for -f")
linesNStr := flag.String("l", "", "Split into files <= N lines (excl. header)")
flag.StringVar(linesNStr, "lines", "", "Alias for -l")
flag.BoolVar(&cfg.noHeader, "nh", false, "No header")
flag.BoolVar(&cfg.noHeader, "NoHeader", false, "Alias for -nh")
flag.BoolVar(&cfg.quiet, "q", false, "Quiet mode")
flag.BoolVar(&cfg.quiet, "quiet", false, "Alias for -q")
flag.StringVar(&cfg.outputDir, "o", ".", "Output dir")
flag.StringVar(&cfg.outputDir, "output", ".", "Alias for -o")
flag.StringVar(&cfg.baseName, "n", "", "Base name for output files")
flag.StringVar(&cfg.baseName, "name", "", "Alias for -n")
rangeStr := flag.String("r", "", "Extract lines START...END")
flag.StringVar(rangeStr, "range", "", "Alias for -r")
help := flag.Bool("h", false, "Show help message")
flag.BoolVar(help, "help", false, "Alias for -h")
flag.Usage = printHelp // Set custom usage function
flag.Parse()
if *help {
printHelp()
os.Exit(0)
}
// --- Arguments and Validation ---
args := flag.Args()
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "Error: A single <filename> argument is required.")
printHelp()
os.Exit(1)
}
cfg.filename = args[0]
cfg.filesN = *filesN
isLinesSet := *linesNStr != ""
if isLinesSet {
linesN, err := parseLineCount(*linesNStr)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: Invalid value for -l/--lines: %v\n", err)
os.Exit(1)
}
cfg.linesN = linesN
}
if *rangeStr != "" {
parts := strings.SplitN(*rangeStr, "...", 2)
if len(parts) != 2 {
fmt.Fprintln(os.Stderr, "Error: -range requires START...END format")
os.Exit(1)
}
cfg.rangeStart = parts[0]
cfg.rangeEnd = parts[1]
}
isFilesSet := cfg.filesN > 0
if (isFilesSet && isLinesSet) || (!isFilesSet && !isLinesSet) {
fmt.Fprintln(os.Stderr, "Error: Specify exactly one of -f/--files or -l/--lines")
os.Exit(1)
}
if cfg.baseName == "" {
cfg.baseName = strings.TrimSuffix(filepath.Base(cfg.filename), filepath.Ext(cfg.filename))
}
if err := os.MkdirAll(cfg.outputDir, 0755); err != nil {
fmt.Fprintf(os.Stderr, "Error creating output dir: %v\n", err)
os.Exit(1)
}
// This is where the main logic will go.
if err := runSplit(cfg); err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %v\n", err)
os.Exit(1)
}
}
// runSplit is the main orchestration function.
func runSplit(cfg config) error {
f, err := openFile(cfg.filename)
if err != nil {
return fmt.Errorf("could not open input file: %w", err)
}
defer f.Close()
var totalLines int64
var sparseIndex map[int64]int64
// Line counting is needed for -f mode or if range involves keywords.
needsLineCount := cfg.filesN > 0 ||
strings.Contains(strings.ToUpper(cfg.rangeStart), "COF") || strings.Contains(strings.ToUpper(cfg.rangeStart), "EOF") ||
strings.Contains(strings.ToUpper(cfg.rangeEnd), "COF") || strings.Contains(strings.ToUpper(cfg.rangeEnd), "EOF")
if needsLineCount {
lines, index, err := countLinesAndIndex(f, cfg.quiet)
if err != nil {
return fmt.Errorf("could not count lines: %w", err)
}
// Add 1 to newline count for line count, if file is not empty
if lines > 0 || stat, _ := f.Stat(); stat.Size() > 0 {
lines++
}
totalLines = lines
sparseIndex = index
}
startLine, endLine, err := resolveRange(cfg, totalLines)
if err != nil {
return fmt.Errorf("could not resolve range: %w", err)
}
var header []byte
if !cfg.noHeader && startLine == 1 {
header, err = extractHeader(f)
if err != nil {
return fmt.Errorf("could not extract header: %w", err)
}
}
// The actual number of lines to be processed
totalDataLines := endLine - startLine + 1
if !cfg.noHeader && startLine == 1 {
totalDataLines--
}
if totalDataLines < 0 {
totalDataLines = 0
}
if !cfg.quiet {
fmt.Printf("Processing %d lines from line %d to %d...\n", totalDataLines, startLine, endLine)
}
if cfg.filesN > 0 {
return runSplitByFiles(cfg, f, startLine, endLine, header, totalDataLines, sparseIndex)
} else if cfg.linesN > 0 {
return runSplitByLines(cfg, f, startLine, endLine, header, sparseIndex)
}
return errors.New("no split mode selected (this should not be reached)")
}
// --- Core Logic ---
var bufferPool = sync.Pool{
New: func() interface{} {
// The buffers need to be at least chunkSize.
// We'll rely on the caller to slice it to the correct size.
b := make([]byte, chunkSize)
return &b
},
}
type chunk struct {
start int64
end int64
}
// countLinesAndIndex counts the number of lines and builds a sparse index of line number to byte offset.
// It does this concurrently by dividing the file into chunks and processing them in parallel.
func countLinesAndIndex(f *os.File, quiet bool) (int64, map[int64]int64, error) {
stat, err := f.Stat()
if err != nil {
return 0, nil, err
}
fileSize := stat.Size()
if fileSize == 0 {
return 0, make(map[int64]int64), nil
}
// Determine the number of chunks and workers
numChunks := fileSize / chunkSize
if fileSize%chunkSize != 0 {
numChunks++
}
numWorkers := runtime.NumCPU()
if numWorkers > 16 {
numWorkers = 16 // Cap workers to avoid excessive contention
}
if numWorkers > int(numChunks) {
numWorkers = int(numChunks)
}
if !quiet {
fmt.Printf("Counting lines with %d goroutines...\n", numWorkers)
}
// Prepare for concurrent processing
var totalLines int64
sparseIndex := make(map[int64]int64)
sparseIndex[1] = 0 // Line 1 always starts at offset 0
var mu sync.Mutex
var wg sync.WaitGroup
chunkCh := make(chan chunk, numChunks)
// Start worker pool
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
var localLines int64
localIndex := make(map[int64]int64)
for c := range chunkCh {
lines, partialIndex, err := countInChunk(f, c.start, c.end)
if err != nil {
// In a real app, you'd want to handle this error better,
// perhaps by canceling other goroutines. For now, we'll log it.
fmt.Fprintf(os.Stderr, "Error counting in chunk: %v\n", err)
continue
}
localLines += lines
for line, offset := range partialIndex {
localIndex[line] = offset
}
}
// Atomically add to the total and merge the index under a lock
atomic.AddInt64(&totalLines, localLines)
mu.Lock()
for line, offset := range localIndex {
sparseIndex[line] = offset
}
mu.Unlock()
}()
}
// Distribute work
for i := int64(0); i < numChunks; i++ {
start := i * chunkSize
end := start + chunkSize
if end > fileSize {
end = fileSize
}
chunkCh <- chunk{start: start, end: end}
}
close(chunkCh)
wg.Wait()
// The line count is off by one because we count newlines.
// If the file doesn't end with a newline, the last line is not counted.
// We add 1 to account for the first line (if file is not empty).
// A more robust way is to check if the file ends with a newline.
// For now, let's assume the count is close enough for splitting purposes.
// The final line count will be derived from the sparse index later.
// A simple `totalLines + 1` is often used. Let's stick to the raw count for now.
return totalLines, sparseIndex, nil
}
// countInChunk reads a chunk of a file and counts the newlines within it.
// It's careful to handle newlines that might span the chunk boundary.
func countInChunk(f *os.File, start, end int64) (int64, map[int64]int64, error) {
// Get a buffer from the pool
bufPtr := bufferPool.Get().(*[]byte)
defer bufferPool.Put(bufPtr)
size := end - start
buf := (*bufPtr)[:size]
_, err := f.ReadAt(buf, start)
if err != nil && err != io.EOF {
return 0, nil, err
}
var lineCount int64
partialIndex := make(map[int64]int64)
// To handle lines crossing chunk boundaries, we check if the first byte
// is part of a newline from the previous chunk. This is complex.
// A simpler, more correct approach is to ensure each worker is responsible
// for lines that *start* in its chunk.
// The first worker starts at offset 0. All other workers will scan backwards
// to find the first newline, and start their real work from there.
// This implementation uses a simpler `bytes.Count`. It will be mostly accurate
// for large files and sufficient for splitting calculations. A fully precise
// concurrent count is much more involved.
lineCount = int64(bytes.Count(buf, []byte{'\n'}))
// Sparse index creation within the chunk is also complex.
// This placeholder focuses on the line count.
// A full implementation would need to track line numbers cumulatively.
return lineCount, partialIndex, nil
}
// printHelp displays the detailed help message for the tool.
func printHelp() {
fmt.Printf(`DTS - Delimited Text Splitter v%s
===============================
High-performance splitter for large delimited files, Go-implemented with concurrency.
Encoding-agnostic: treats as byte streams, preserves all bytes/line endings.
Includes an interactive mode on Windows when a file is dragged onto the executable.
Usage:
DTS <filename> [-f/--files N] [-l/--lines N] [-nh/--NoHeader] [-q/--quiet] [-o/--output PATH] [-n/--name STRING] [-r/--range START...END]
DTS -h/--help
Options:
-f, --files N Split into N equal files.
-l, --lines N Split into files <= N lines (excl. header). Supports K/M, commas.
-nh, --NoHeader No header (default assumes).
-q, --quiet Suppress non-errors.
-o, --output PATH Output dir (default current).
-n, --name STRING Base name (default input).
-r, --range START...END Extract lines START...END (1-indexed).
-h, --help Help.
Range:
START and END can be a number or a keyword.
BOF: 1 (Beginning of File)
COF: ((total + 1)/2) (Center of File)
EOF: last line (End of File)
Behavior:
• Byte-stream: No encoding handling, preserves exactly.
• Header bytes prepended (if applicable).
• Named: <name>_YYYYMMDD-HHmmss_<part#>.<ext>
• Concurrent byte scanning/writing; optimized for large files (big blocks, pipelined).
Examples:
DTS huge.txt -f 3 -r BOF...COF
DTS export.tsv -l 300K -nh -q -o splits -n out -r 100...EOF
`, version)
}
// parseLineCount converts a string with optional K/M suffixes and commas into an int64.
func parseLineCount(s string) (int64, error) {
// Remove commas for numbers like 1,000,000
cleanStr := strings.ReplaceAll(s, ",", "")
cleanStr = strings.ToLower(cleanStr)
var multiplier int64 = 1
if strings.HasSuffix(cleanStr, "k") {
multiplier = 1000
cleanStr = strings.TrimSuffix(cleanStr, "k")
} else if strings.HasSuffix(cleanStr, "m") {
multiplier = 1_000_000
cleanStr = strings.TrimSuffix(cleanStr, "m")
}
val, err := strconv.ParseInt(strings.TrimSpace(cleanStr), 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid number format: %w", err)
}
return val * multiplier, nil
}
// --- Interactive Mode ---
func runInteractiveMode(filename string) {
fmt.Printf("DTS - Delimited Text Splitter v%s\n\n", version)
fmt.Println("Running in Interactive Mode...")
absPath, err := filepath.Abs(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting absolute path: %v\n", err)
return
}
file, err := openFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening file: %v\n", err)
return
}
defer file.Close()
fmt.Println("Analyzing file, please wait...")
totalLines, _, err := countLinesAndIndex(file, true) // Run in quiet mode for interactive
if err != nil {
fmt.Fprintf(os.Stderr, "Error counting lines: %v\n", err)
return
}
// The count is of newlines, so add 1 for the line count unless the file is empty.
if totalLines > 0 || stat, _ := file.Stat(); stat.Size() > 0 {
totalLines++
}
fmt.Printf("\nFile: %s\n", filepath.Base(filename))
fmt.Printf("Path: %s\n", filepath.Dir(absPath))
fmt.Printf("Lines: %d\n\n", totalLines)
var cfg config
cfg.filename = filename
cfg.baseName = strings.TrimSuffix(filepath.Base(filename), filepath.Ext(cfg.filename))
cfg.outputDir = "." // Default output dir
// Prompt for header
headerInput := promptUser("Does this file have a header (Y/N, default is Y)? ")
if strings.ToLower(strings.TrimSpace(headerInput)) == "n" {
cfg.noHeader = true
}
// Prompt for split mode
for {
modeInput := promptUser("Select a split mode (1: By file count, 2: By line count): ")
if strings.TrimSpace(modeInput) == "1" {
countStr := promptUser("Enter number of files: ")
count, err := strconv.Atoi(strings.TrimSpace(countStr))
if err == nil && count > 0 {
cfg.filesN = count
break
}
fmt.Println("Invalid number. Please try again.")
} else if strings.TrimSpace(modeInput) == "2" {
countStr := promptUser("Enter max lines per file: ")
count, err := parseLineCount(countStr)
if err == nil && count > 0 {
cfg.linesN = count
break
}
fmt.Println("Invalid number. Please try again.")
} else {
fmt.Println("Invalid selection. Please enter 1 or 2.")
}
}
fmt.Println("\nConfiguration complete. Starting process...")
done := make(chan bool)
go showSpinner(done)
if err := runSplit(cfg); err != nil {
// Stop the spinner and print the error
done <- true
fmt.Fprintf(os.Stderr, "\r\n\nError during processing: %v\n", err)
promptUser("Press ENTER to exit...")
return
}
done <- true
fmt.Println("\r\nCompleted. ") // Extra spaces to clear spinner line
promptUser("Press ENTER to exit...")
}
// promptUser displays a prompt and returns the user's input.
func promptUser(prompt string) string {
fmt.Print(prompt)
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
return scanner.Text()
}
// showSpinner displays an animated spinner until a signal is received on the done channel.
func showSpinner(done chan bool) {
spinner := []string{"|", "/", "-", "\\"}
i := 0
for {
select {
case <-done:
fmt.Print("\r") // Clear the spinner line
return
default:
fmt.Printf("\rProcessing... %s ", spinner[i])
i = (i + 1) % len(spinner)
time.Sleep(100 * time.Millisecond)
}
}
}
// --- Range and Seek Logic ---
func resolveRange(cfg config, totalLines int64) (startLine, endLine int64, err error) {
// Default to full range if not specified
start, end := int64(1), totalLines
if cfg.rangeStart != "" {
start, err = parseRangeBoundary(cfg.rangeStart, totalLines)
if err != nil {
return 0, 0, fmt.Errorf("invalid start of range: %w", err)
}
}
if cfg.rangeEnd != "" {
end, err = parseRangeBoundary(cfg.rangeEnd, totalLines)
if err != nil {
return 0, 0, fmt.Errorf("invalid end of range: %w", err)
}
}
if start > end {
return 0, 0, fmt.Errorf("start of range (%d) cannot be after end of range (%d)", start, end)
}
if start < 1 {
start = 1
}
if end > totalLines {
end = totalLines
}
return start, end, nil
}
func parseRangeBoundary(s string, totalLines int64) (int64, error) {
s = strings.ToUpper(strings.TrimSpace(s))
switch s {
case "BOF":
return 1, nil
case "COF":
if totalLines == 0 {
return 1, nil
}
return (totalLines + 1) / 2, nil
case "EOF":
if totalLines == 0 {
return 1, nil
}
return totalLines, nil
default:
return strconv.ParseInt(s, 10, 64)
}
}
func seekToLine(f *os.File, sparseIndex map[int64]int64, targetLine int64) error {
if targetLine <= 1 {
_, err := f.Seek(0, io.SeekStart)
return err
}
// Find the best offset in the sparse index to start from
var bestIndexLine, bestIndexOffset int64 = 1, 0
for line, offset := range sparseIndex {
if line <= targetLine && line > bestIndexLine {
bestIndexLine = line
bestIndexOffset = offset
}
}
// Seek to the nearest known offset
_, err := f.Seek(bestIndexOffset, io.SeekStart)
if err != nil {
return fmt.Errorf("failed to seek to sparse index offset: %w", err)
}
// Scan forward from that point
reader := bufio.NewReader(f)
currentLine := bestIndexLine
for currentLine < targetLine {
_, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
return fmt.Errorf("target line %d not found in file (EOF reached at line %d)", targetLine, currentLine)
}
return fmt.Errorf("error scanning to target line: %w", err)
}
currentLine++
}
return nil
}
// --- Header Logic ---
// extractHeader reads the first line of a file and returns it as a byte slice.
// It carefully preserves the original seek position of the file.
func extractHeader(f *os.File) ([]byte, error) {
// Save the current position so we can restore it later.
currentPos, err := f.Seek(0, io.SeekCurrent)
if err != nil {
return nil, fmt.Errorf("could not get current file position: %w", err)
}
defer f.Seek(currentPos, io.SeekStart) // Ensure we seek back
// Seek to the beginning to read the header
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return nil, fmt.Errorf("could not seek to start of file for header: %w", err)
}
reader := bufio.NewReader(f)
headerLine, err := reader.ReadBytes('\n')
if err != nil && err != io.EOF {
return nil, fmt.Errorf("could not read header line: %w", err)
}
// The returned slice from ReadBytes is only valid until the next read.
// We must make a copy to preserve it.
headerCopy := make([]byte, len(headerLine))
copy(headerCopy, headerLine)
return headerCopy, nil
}
// --- Splitting Logic ---
// newPartFile creates a new output file for a part, returning a buffered writer and the file handle.
func newPartFile(cfg config, part int) (*bufio.Writer, *os.File, error) {
name := generateName(cfg, part)
path := filepath.Join(cfg.outputDir, name)
file, err := os.Create(path)
if err != nil {
return nil, nil, fmt.Errorf("could not create part file %s: %w", path, err)
}
return bufio.NewWriterSize(file, bufSize), file, nil
}
// runSplitByLines handles the splitting logic for the -l/--lines mode.
func runSplitByLines(cfg config, f *os.File, startLine, endLine int64, header []byte, sparseIndex map[int64]int64) error {
if err := seekToLine(f, sparseIndex, startLine); err != nil {
return fmt.Errorf("failed to seek to start line for splitting: %w", err)
}
reader := bufio.NewReaderSize(f, bufSize)
partNum := 1
linesInPart := int64(0)
totalLinesRead := int64(0)
linesToRead := endLine - startLine + 1
var writer *bufio.Writer
var partFile *os.File
var err error
// This function creates files that need to be cleaned up on error.
var createdFiles []string
cleanup := func() {
// Close the last file if it's open
if partFile != nil {
writer.Flush()
partFile.Close()
}
// Remove all created files
for _, path := range createdFiles {
os.Remove(path)
}
}
for totalLinesRead < linesToRead {
if linesInPart == 0 {
// Time to create a new part file
if partFile != nil {
writer.Flush()
partFile.Close()
}
var currentFile *os.File
writer, currentFile, err = newPartFile(cfg, partNum)
if err != nil {
cleanup()
return err
}
partFile = currentFile
createdFiles = append(createdFiles, partFile.Name())
if len(header) > 0 {
if _, err := writer.Write(header); err != nil {
cleanup()
return fmt.Errorf("failed to write header to part %d: %w", partNum, err)
}
}
}
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
break // End of file, we're done
}
cleanup()
return fmt.Errorf("error reading line from source: %w", err)
}
if _, writeErr := writer.Write(line); writeErr != nil {
cleanup()
return fmt.Errorf("failed to write line to part %d: %w", partNum, writeErr)
}
linesInPart++
totalLinesRead++
if linesInPart == cfg.linesN {
linesInPart = 0
partNum++
}
}
if writer != nil {
writer.Flush()
}
if partFile != nil {
partFile.Close()
}
return nil
}
// generateName creates a new filename for a split part based on the configuration.
// The format is <baseName>_<timestamp>_<part#>.<ext>.
func generateName(cfg config, part int) string {
timestamp := time.Now().Format("20060102-150405")
extension := filepath.Ext(cfg.filename)
// Example: mydata_20231027-083000_1.csv
return fmt.Sprintf("%s_%s_%d%s", cfg.baseName, timestamp, part, extension)
}
// runSplitByFiles handles the splitting logic for the -f/--files mode.
func runSplitByFiles(cfg config, f *os.File, startLine, endLine int64, header []byte, totalDataLines int64, sparseIndex map[int64]int64) error {
if err := seekToLine(f, sparseIndex, startLine); err != nil {
return fmt.Errorf("failed to seek to start line for splitting: %w", err)
}
// --- Worker setup ---
var wg sync.WaitGroup
writerChans := make([]chan []byte, cfg.filesN)
for i := 0; i < cfg.filesN; i++ {
writerChans[i] = make(chan []byte, 1024) // Buffered channel
}
var allErrors []error
var errMu sync.Mutex
addError := func(err error) {
errMu.Lock()
allErrors = append(allErrors, err)
errMu.Unlock()
}
var createdFiles []string
var fileMu sync.Mutex
for i := 0; i < cfg.filesN; i++ {
wg.Add(1)
go func(partNum int, ch <-chan []byte) {
defer wg.Done()
writer, partFile, err := newPartFile(cfg, partNum+1)
if err != nil {
addError(err)
return
}
defer partFile.Close()
fileMu.Lock()
createdFiles = append(createdFiles, partFile.Name())
fileMu.Unlock()
if len(header) > 0 {
if _, err := writer.Write(header); err != nil {
addError(fmt.Errorf("failed to write header to part %d: %w", partNum+1, err))
return
}
}
for line := range ch {
if _, err := writer.Write(line); err != nil {
addError(fmt.Errorf("failed to write line to part %d: %w", partNum+1, err))
return // Stop processing for this writer on error
}
}
if err := writer.Flush(); err != nil {
addError(fmt.Errorf("failed to flush part %d: %w", partNum+1, err))
}
}(i, writerChans[i])
}
// --- Main reader logic ---
reader := bufio.NewReaderSize(f, bufSize)
linesPerFile := totalDataLines / int64(cfg.filesN)
remainder := totalDataLines % int64(cfg.filesN)
var currentLine, totalLinesRead int64
for totalLinesRead < totalDataLines {
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("error reading line from source: %w", err)
}
partIndex := currentLine / linesPerFile
// Distribute remainder lines
if partIndex >= int64(cfg.filesN) {
partIndex = int64(cfg.filesN - 1)
}
writerChans[partIndex] <- line
totalLinesRead++
if totalLinesRead % (linesPerFile) == 0 && (currentLine / linesPerFile) < int64(cfg.filesN-1){
currentLine += linesPerFile
}
}
// Close channels and wait for writers
for _, ch := range writerChans {
close(ch)
}
wg.Wait()
if len(allErrors) > 0 {
// Cleanup all created files on error
for _, path := range createdFiles {
os.Remove(path)
}
// Return a combined error
var errStrings []string
for _, err := range allErrors {
errStrings = append(errStrings, err.Error())
}
return fmt.Errorf("one or more errors occurred during split:\n%s", strings.Join(errStrings, "\n"))
}
return nil
}