Skip to content

Instantly share code, notes, and snippets.

@ZoomTen
Last active August 13, 2023 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZoomTen/0d61266be9e271705691e3ff75c4c2bb to your computer and use it in GitHub Desktop.
Save ZoomTen/0d61266be9e271705691e3ff75c4c2bb to your computer and use it in GitHub Desktop.
Port of pret's scan-includes tool. Not quite perfect, and it's about half as fast.
# requires "regex >= 0.20.2"
import strformat, strutils
import parseopt
import os
import options
import regex
type ProgramOptions = object
strict: bool
var program_options = ProgramOptions(strict: false)
var matches: RegexMatch
let RE_INCLUDE = re"""(?i)\s*(include|incbin)\s+"(.+)""""
proc show_help() =
echo("scan_includes [-h] [-s] filename")
echo()
echo("-h, --help Print usage and exit")
echo("-s, --strict Give up upon encountering nonexistent file")
quit(0)
proc quit(errormsg: string; errorcode = QuitFailure) {.noreturn} =
stderr.write_line(errormsg)
quit(errorcode)
proc scan_file(file_name: string): string =
result = ""
var lnum = 1
for line in lines(file_name):
if line.find(RE_INCLUDE, matches):
let included_file = matches.group_last_capture(1, line)
if matches.group_last_capture(0, line).to_lower() == "include":
if not file_exists(included_file):
if program_options.strict:
quit(fmt"{file_name}:{lnum}: {included_file} not found")
else:
result &= scan_file(included_file) & " "
result &= included_file & " "
lnum += 1
when is_main_module:
var file_name: Option[string] = none(string)
var args = init_opt_parser(command_line_params())
if args.remaining_args().len == 0:
show_help()
while true:
args.next()
case args.kind
of cmdEnd: break
of cmdLongOption:
if args.key == "help":
show_help()
if args.key == "strict":
program_options.strict = true
else:
quit(fmt"I don't recognize --{args.key}...")
of cmdShortOption:
if args.key == "h":
show_help()
if args.key == "s":
program_options.strict = true
else:
quit(fmt"I don't recognize -{args.key}...")
of cmdArgument:
file_name = some(args.key)
break
if file_name.is_none:
quit("No file name specified")
if not file_exists(file_name.get()):
quit(fmt"File {file_name.get()} doesn't exist")
echo scan_file(file_name.get())
quit(0)
#!/usr/bin/sh
choosenim 1.6.14
nim install regex
nim c -d:release scan_includes.nim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment