|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "bufio" |
| 7 | + "strings" |
| 8 | + "github.com/persata/mysqldumptablepurger/io" |
| 9 | + "github.com/persata/mysqldumptablepurger/parser" |
| 10 | + "regexp" |
| 11 | +) |
| 12 | + |
| 13 | +func RemoveTables(inputPath string, outputPath string, tables []string) { |
| 14 | + fmt.Println("The following tables will be removed: \n") |
| 15 | + |
| 16 | + for _, table := range tables { |
| 17 | + fmt.Println(fmt.Sprintf("- %s", table)) |
| 18 | + } |
| 19 | + |
| 20 | + if _, err := os.Stat(outputPath); err == nil { |
| 21 | + fmt.Println(fmt.Sprintf("\nThe specified output file '%s' already exists, and will be overwritten!", outputPath)) |
| 22 | + } |
| 23 | + |
| 24 | + fmt.Println("\nContinue? Y/n") |
| 25 | + |
| 26 | + reader := bufio.NewReader(os.Stdin) |
| 27 | + c, _ := reader.ReadString('\n') |
| 28 | + |
| 29 | + c = strings.TrimSpace(c) |
| 30 | + |
| 31 | + if c != "Y" { |
| 32 | + fmt.Println("Exiting, no action performed") |
| 33 | + } else { |
| 34 | + fmt.Println("Processing...\n") |
| 35 | + } |
| 36 | + |
| 37 | + s, fr := io.GetScanner(inputPath) |
| 38 | + defer fr.Close() |
| 39 | + |
| 40 | + w, fw := io.GetWriter(outputPath) |
| 41 | + defer fw.Close() |
| 42 | + |
| 43 | + //skipping := false |
| 44 | + |
| 45 | + replaceRegex := regexp.MustCompile(fmt.Sprintf(parser.TableStructureRegexReplace, strings.Join(tables, "|"))) |
| 46 | + |
| 47 | + skipping := false |
| 48 | + |
| 49 | + matchCount := 0 |
| 50 | + |
| 51 | + for s.Scan() { |
| 52 | + currentLine := s.Text() |
| 53 | + |
| 54 | + match := replaceRegex.FindStringSubmatch(currentLine) |
| 55 | + |
| 56 | + if len(match) > 0 { |
| 57 | + matchCount += 1 |
| 58 | + skipping = true |
| 59 | + fmt.Println(fmt.Sprintf("Found section for `%s`, skipping data", match[1])) |
| 60 | + |
| 61 | + w.WriteString(fmt.Sprintf("-- Section for `%s` removed by mysqldumptablepurger", match[1])) |
| 62 | + w.WriteString("\n") |
| 63 | + } |
| 64 | + |
| 65 | + if !skipping { |
| 66 | + w.WriteString(currentLine) |
| 67 | + w.WriteString("\n") |
| 68 | + } |
| 69 | + |
| 70 | + if skipping { |
| 71 | + if strings.HasPrefix(currentLine, parser.EndSkippingPrefix) { |
| 72 | + skipping = false |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + w.Flush() |
| 78 | + |
| 79 | + fmt.Println(fmt.Sprintf("\nExiting, %d tables removed", matchCount)) |
| 80 | +} |
0 commit comments