Skip to content

Commit

Permalink
Allow access to additional arguments passed to synthtool (#166)
Browse files Browse the repository at this point in the history
These can be accessed via:

```
from __main__ import extra_args

print(extra_args())
```

or

``1
from synthtool.__main__ import extra_args

print(extra_args())
```
  • Loading branch information
theacodes authored Dec 6, 2018
1 parent 3f73617 commit 27938e0
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion synthtool/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import importlib
import os
import sys
from typing import List, Sequence

import click
import pkg_resources
Expand All @@ -29,11 +30,39 @@
VERSION = "0.0.0+dev"


_extra_args: List[str] = []


def extra_args() -> List[str]:
"""Return any additional arguments specified to synthtool."""
# Return a copy so these don't get modified.
# A little trickery. If __name__ isn't __main__, import __main__ and return
# its extra_args(). This ensures that both `from __main__ import extra_args()`
# and `from synthtool.__main__ import extra_args()` works as expected. This
# is needed because *technically* Python can have two copies of this module
# in sys.modules when it's executed as main. Weird, I know.
if __name__ != "__main__": # pragma: no cover
try:
import __main__

return __main__.extra_args()
except AttributeError:
# __main__ didn't have an extra_args() attribute, so this means
# synthtool is not the main module. Just return what's in this
# module.
pass

return list(_extra_args)


@click.command()
@click.version_option(message="%(version)s", version=VERSION)
@click.argument("synthfile", default="synth.py")
@click.option("--metadata", default="synth.metadata")
def main(synthfile, metadata):
@click.argument("extra_args", nargs=-1)
def main(synthfile: str, metadata: str, extra_args: Sequence[str]):
_extra_args.extend(extra_args)

synthtool.metadata.register_exit_hook(outfile=metadata)

synth_file = os.path.abspath(synthfile)
Expand All @@ -43,7 +72,12 @@ def main(synthfile, metadata):
# https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
spec = importlib.util.spec_from_file_location("synth", synth_file)
synth_module = importlib.util.module_from_spec(spec)

if spec.loader is None:
raise ImportError("Could not import synth.py")

spec.loader.exec_module(synth_module)

else:
synthtool.log.exception(f"{synth_file} not found.")
sys.exit(1)
Expand Down

0 comments on commit 27938e0

Please sign in to comment.