Created
April 21, 2020 22:22
-
-
Save sporto/459ccbae85eaeae3b43585ff4f252769 to your computer and use it in GitHub Desktop.
Replace text in files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# nim c -r ./scripts/replace.nim ./replacements.csv | |
import strutils, sequtils, os, sugar | |
proc split_line(line: string): seq[string] = | |
line.split("|") | |
proc get_replacements(filename: string): seq[seq[string]] = | |
filename | |
.readFile() | |
.splitLines() | |
.filter(line => not line.isEmptyOrWhitespace) | |
.map(split_line) | |
const EXCLUDE = [ | |
".git", | |
"/deploy", | |
"/scripts", | |
"/Elm/Api", | |
"/webpack", | |
".db", | |
".css", | |
".svg", | |
".png", | |
] | |
proc is_excluded_path(path: string): bool = | |
for exclude in EXCLUDE: | |
if path.contains(exclude): | |
return true | |
false | |
proc get_file_to_replace(): seq[string] = | |
for path in walkDirRec("."): | |
if is_excluded_path(path): | |
continue | |
result.add(path) | |
proc replace_in_file(file_path: string, replacements: seq[seq[string]]): void = | |
echo "processing ", file_path | |
try: | |
var file = file_path.readFile() | |
for replacement in replacements: | |
# echo replacement | |
let fr = replacement[0] | |
let to = replacement[1] | |
file = file.replace(fr, to) | |
file_path.writeFile(file) | |
except IOError: | |
echo getCurrentExceptionMsg() | |
proc main() = | |
let filename = paramStr(1) | |
let replacements = get_replacements(filename) | |
let paths = get_file_to_replace() | |
for path in paths: | |
path.replace_in_file(replacements) | |
when isMainModule: | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment