Skip to content

Commit b933c9b

Browse files
committed
Correctly handle print_info() for api_main()
1 parent 577ff1d commit b933c9b

File tree

3 files changed

+35
-30
lines changed

3 files changed

+35
-30
lines changed

src/ctypesgen/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@
5555
# Helper modules
5656
from . import messages
5757

58+
# Entry points
59+
from .__main__ import main, api_main
60+
5861
__version__ = version.VERSION.partition("-")[-1]
5962
VERSION = __version__
6063
PYPDFIUM2_SPECIFIC = True

src/ctypesgen/__main__.py

+12-6
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import argparse
88
import itertools
99
from pathlib import Path
10+
from pprint import pformat
1011

1112
from ctypesgen import (
1213
messages as msgs,
@@ -16,7 +17,9 @@
1617
printer_python,
1718
printer_json,
1819
)
19-
20+
from ctypesgen.printer_python import (
21+
txtpath, PRIVATE_PATHS,
22+
)
2023

2124
# -- Argparse-based entry point --
2225

@@ -25,7 +28,8 @@
2528
def main(given_argv=sys.argv[1:]):
2629
args = get_parser().parse_args(given_argv)
2730
postparse(args)
28-
main_impl(args, given_argv)
31+
cmd_str = " ".join(["ctypesgen"] + [shlex.quote(txtpath(a)) for a in given_argv])
32+
main_impl(args, cmd_str)
2933

3034
def postparse(args):
3135
args.cppargs = list( itertools.chain(*args.cppargs) )
@@ -49,9 +53,11 @@ def api_main(args):
4953
real_args = defaults.copy()
5054
real_args.update(args)
5155
real_args = argparse.Namespace(**real_args)
52-
given_argv = "Unknown API Call".split(" ") # FIXME
5356

54-
return main_impl(real_args, given_argv=given_argv)
57+
args_str = str(pformat(args))
58+
for p, x in PRIVATE_PATHS:
59+
args_str = args_str.replace(p, x)
60+
return main_impl(real_args, f"ctypesgen.api_main(\n{args_str}\n)")
5561

5662

5763
# Adapted from https://stackoverflow.com/a/59395868/15547292
@@ -70,7 +76,7 @@ def _get_parser_requires(parser):
7076

7177
# -- Main implementation --
7278

73-
def main_impl(args, given_argv):
79+
def main_impl(args, cmd_str):
7480

7581
assert args.headers or args.system_headers, "Either --headers or --system-headers required."
7682

@@ -105,7 +111,7 @@ def main_impl(args, given_argv):
105111
raise RuntimeError("No target members found.")
106112
printer = {"py": printer_python, "json": printer_json}[args.output_language].WrapperPrinter
107113
msgs.status_message(f"Printing to {args.output}.")
108-
printer(args.output, args, data, given_argv)
114+
printer(args.output, args, data, cmd_str)
109115

110116
msgs.status_message("Wrapping complete.")
111117

src/ctypesgen/printer_python.py

+20-24
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import shlex
21
import shutil
32
from pathlib import Path
43
from textwrap import indent
@@ -22,20 +21,34 @@ def paragraph_ctx(txt):
2221
file.write(f"\n# -- End {txt} --")
2322
return paragraph_ctx
2423

24+
PRIVATE_PATHS = [(str(Path.home()), "~")]
25+
if Path.cwd() != Path("/"): # don't strip unix root
26+
PRIVATE_PATHS += [(str(Path.cwd()), ".")]
27+
# sort descending by length to avoid interference
28+
PRIVATE_PATHS.sort(key=lambda x: len(x[0]), reverse=True)
29+
30+
def txtpath(s):
31+
# Returns a path string suitable for embedding into the output, with private paths stripped
32+
s = str(s)
33+
for p, x in PRIVATE_PATHS:
34+
if s.startswith(p):
35+
return x + s[len(p):]
36+
return s
37+
2538

2639
# Important: Concerning newlines handling, please read docs/dev_comments.md
2740

2841
class WrapperPrinter:
2942

30-
def __init__(self, outpath, opts, data, argv):
43+
def __init__(self, outpath, opts, data, cmd_str):
3144

3245
self.opts = opts
3346

3447
with outpath.open("w", encoding="utf-8") as self.file:
3548

3649
self.paragraph_ctx = ParagraphCtxFactory(self.file)
3750

38-
self.print_info(argv)
51+
self.print_info(cmd_str)
3952
self.file.write(
4053
"\n\nimport ctypes"
4154
"\nfrom ctypes import *"
@@ -65,26 +78,11 @@ def __init__(self, outpath, opts, data, argv):
6578

6679
for fp in opts.inserted_files:
6780
self.file.write("\n\n\n")
68-
self._embed_file(fp, f"inserted file '{self._txtpath(fp)}'")
81+
self._embed_file(fp, f"inserted file '{txtpath(fp)}'")
6982

7083
self.file.write("\n")
7184

7285

73-
PRIVATE_PATHS_TABLE = [(str(Path.home()), "~")]
74-
if Path.cwd() != Path("/"): # don't strip unix root
75-
PRIVATE_PATHS_TABLE += [(str(Path.cwd()), ".")]
76-
# sort descending by length to avoid interference
77-
PRIVATE_PATHS_TABLE.sort(key=lambda x: len(x[0]), reverse=True)
78-
79-
@classmethod
80-
def _txtpath(cls, s):
81-
# Returns a path string suitable for embedding into the output, with private paths stripped
82-
s = str(s)
83-
for p, x in cls.PRIVATE_PATHS_TABLE:
84-
if s.startswith(p):
85-
return x + s[len(p):]
86-
return s
87-
8886
def _embed_file(self, fp, desc):
8987
with self.paragraph_ctx(desc), open(fp, "r") as src_fh:
9088
self.file.write("\n\n")
@@ -99,13 +97,11 @@ def _srcinfo(self, src):
9997
if fp in ("<built-in>", "<command line>"):
10098
self.file.write(f"# {fp}\n")
10199
else:
102-
self.file.write(f"# {self._txtpath(fp)}: {lineno}\n")
100+
self.file.write(f"# {txtpath(fp)}: {lineno}\n")
103101

104102

105-
def print_info(self, argv):
106-
argv = [self._txtpath(a) for a in argv]
107-
argv_str = ' '.join([shlex.quote(a) for a in argv])
108-
self.file.write(f'R"""\nAuto-generated by:\nctypesgen {argv_str}\n"""')
103+
def print_info(self, cmd_str):
104+
self.file.write(f'R"""\nAuto-generated by:\n{cmd_str}\n"""')
109105

110106

111107
def print_loader(self, opts):

0 commit comments

Comments
 (0)