cmerge.nim 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Simple tool to merge C projects into a single C file
  2. import os, sets, pegs
  3. type
  4. ProcessResult = enum prSkipIncludeDir, prAddIncludeDir
  5. proc process(dir, infile: string, outfile: File,
  6. processed: var HashSet[string]): ProcessResult =
  7. if processed.containsOrIncl(infile): return prSkipIncludeDir
  8. let toProcess = dir / infile
  9. if not fileExists(toProcess):
  10. echo "Warning: could not process: ", toProcess
  11. return prAddIncludeDir
  12. echo "adding: ", toProcess
  13. for line in lines(toProcess):
  14. if line =~ peg"""s <- ig '#include' ig '"' {[^"]+} '"' ig
  15. comment <- '/*' !'*/'* '*/' / '//' .*
  16. ig <- (comment / \s+)* """:
  17. # follow the include file:
  18. if process(dir, matches[0], outfile, processed) == prAddIncludeDir:
  19. writeLine(outfile, line)
  20. else:
  21. writeLine(outfile, line)
  22. proc main(dir, outfile: string) =
  23. var o: File
  24. if open(o, outfile, fmWrite):
  25. var processed = initHashSet[string]()
  26. processed.incl(outfile)
  27. for infile in walkFiles(dir / "*.c"):
  28. discard process(dir, extractFilename(infile), o, processed)
  29. close(o)
  30. else:
  31. quit("Cannot open for writing: " & outfile)
  32. if paramCount() != 2:
  33. quit "Usage: cmerge directory outfile"
  34. else:
  35. main(paramStr(1), addFileExt(paramStr(2), "c"))