Python toml.load() Examples
The following are 30
code examples of toml.load().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
toml
, or try the search function
.
Example #1
Source File: oca_towncrier.py From maintainer-tools with GNU Affero General Public License v3.0 | 7 votes |
def _prepare_pyproject_toml(addon_dir, org, repo): """Inject towncrier options in pyproject.toml""" pyproject_path = os.path.join(addon_dir, "pyproject.toml") with _preserve_file(pyproject_path): pyproject = {} if os.path.exists(pyproject_path): with open(pyproject_path) as f: pyproject = toml.load(f) if "tool" not in pyproject: pyproject["tool"] = {} pyproject["tool"]["towncrier"] = { "template": _get_towncrier_template(), "underlines": ["~"], "title_format": "{version} ({project_date})", "issue_format": _make_issue_format(org, repo), "directory": "readme/newsfragments", "filename": "readme/HISTORY.rst", } with open(pyproject_path, "w") as f: toml.dump(pyproject, f) yield
Example #2
Source File: command.py From pinnwand with MIT License | 6 votes |
def main(configuration_path: Optional[str]) -> None: """Pinnwand pastebin software.""" from pinnwand import configuration if configuration_path: import toml with open(configuration_path) as file: configuration_file = toml.load(file) for key, value in configuration_file.items(): setattr(configuration, key, value) from pinnwand import database database.Base.metadata.create_all(database._engine)
Example #3
Source File: project.py From pipenv with MIT License | 6 votes |
def load_lockfile(self, expand_env_vars=True): with io.open(self.lockfile_location, encoding="utf-8") as lock: j = json.load(lock) self._lockfile_newlines = preferred_newlines(lock) # lockfile is just a string if not j or not hasattr(j, "keys"): return j if expand_env_vars: # Expand environment variables in Pipfile.lock at runtime. for i, _ in enumerate(j["_meta"]["sources"][:]): j["_meta"]["sources"][i]["url"] = os.path.expandvars( j["_meta"]["sources"][i]["url"] ) return j
Example #4
Source File: lib.py From mathlib-tools with Apache License 2.0 | 6 votes |
def from_path(cls, path: Path, cache_url: str = '', force_download: bool = False, upgrade_lean: bool = True) -> 'LeanProject': """Builds a LeanProject from a Path object""" try: repo = Repo(path, search_parent_directories=True) except InvalidGitRepositoryError: raise InvalidLeanProject('Invalid git repository') if repo.bare: raise InvalidLeanProject('Git repository is not initialized') is_dirty = repo.is_dirty() try: rev = repo.commit().hexsha except ValueError: rev = '' directory = Path(repo.working_dir) try: config = toml.load(directory/'leanpkg.toml') except FileNotFoundError: raise InvalidLeanProject('Missing leanpkg.toml') return cls(repo, is_dirty, rev, directory, config['package'], config['dependencies'], cache_url, force_download, upgrade_lean)
Example #5
Source File: extension.py From setuptools-rust with MIT License | 6 votes |
def get_lib_name(self): """ Parse Cargo.toml to get the name of the shared library. """ # We import in here to make sure the the setup_requires are already installed import toml cfg = toml.load(self.path) name = cfg.get("lib", {}).get("name") if name is None: name = cfg.get("package", {}).get("name") if name is None: raise Exception( "Can not parse library name from Cargo.toml. " "Cargo.toml missing value for 'name' key " "in both the [package] section and the [lib] section" ) name = re.sub(r"[./\\-]", "_", name) return name
Example #6
Source File: config.py From hypercorn with MIT License | 6 votes |
def from_toml(cls: Type["Config"], filename: FilePath) -> "Config": """Load the configuration values from a TOML formatted file. This allows configuration to be loaded as so .. code-block:: python Config.from_toml('config.toml') Arguments: filename: The filename which gives the path to the file. """ file_path = os.fspath(filename) with open(file_path) as file_: data = toml.load(file_) return cls.from_mapping(data)
Example #7
Source File: test_configuration.py From strawberryfields with Apache License 2.0 | 6 votes |
def test_global(self, monkeypatch, tmpdir): """Tests that the functions integrate correctly when storing account globally.""" with monkeypatch.context() as m: m.setattr(conf, "user_config_dir", lambda *args: tmpdir) conf.store_account( authentication_token, filename="config.toml", location="user_config", **DEFAULT_KWARGS ) filepath = tmpdir.join("config.toml") result = toml.load(filepath) assert result == EXPECTED_CONFIG
Example #8
Source File: run_track.py From cr8 with MIT License | 6 votes |
def run_track(track, result_hosts=None, crate_root=None, output_fmt=None, logfile_info=None, logfile_result=None, failfast=False, sample_mode='reservoir'): """Execute a track file""" with Logger(output_fmt=output_fmt, logfile_info=logfile_info, logfile_result=logfile_result) as log: executor = Executor( track_dir=os.path.dirname(track), log=log, result_hosts=result_hosts, crate_root=crate_root, fail_fast=failfast, sample_mode=sample_mode ) error = executor.execute(toml.load(track)) if error: sys.exit(1)
Example #9
Source File: config.py From robosat with MIT License | 6 votes |
def load_config(path): """Loads a dictionary from configuration file. Args: path: the path to load the configuration from. Returns: The configuration dictionary loaded from the file. """ return toml.load(path)
Example #10
Source File: config.py From openconnect-sso with GNU General Public License v3.0 | 6 votes |
def load(): path = xdg.BaseDirectory.load_first_config(APP_NAME) if not path: return Config() config_path = Path(path) / "config.toml" if not config_path.exists(): return Config() with config_path.open() as config_file: try: return Config.from_dict(toml.load(config_file)) except Exception: logger.error( "Could not load configuration file, ignoring", path=config_path, exc_info=True, ) return Config()
Example #11
Source File: run_track.py From cr8 with MIT License | 6 votes |
def execute(self, track): configurations = list(self._expand_paths(track['configurations'])) versions = track['versions'] error = False for version in versions: self.log.info('# Version: ', version) for c, configuration in enumerate(configurations): self.log.info('## Starting Crate {0}, configuration: {1}'.format( os.path.basename(version), os.path.basename(configuration) )) configuration = toml.load(os.path.join(self.track_dir, configuration)) crate_dir = get_crate(version, self.crate_root) with CrateNode(crate_dir=crate_dir, env=configuration.get('env'), settings=configuration.get('settings')) as node: node.start() _error = self._execute_specs(track['specs'], node.http_url) error = error or _error return error
Example #12
Source File: check.py From pipenv with MIT License | 5 votes |
def check(source_dir): pyproject = pjoin(source_dir, 'pyproject.toml') if isfile(pyproject): log.info('Found pyproject.toml') else: log.error('Missing pyproject.toml') return False try: with open(pyproject) as f: pyproject_data = toml_load(f) # Ensure the mandatory data can be loaded buildsys = pyproject_data['build-system'] requires = buildsys['requires'] backend = buildsys['build-backend'] backend_path = buildsys.get('backend-path') log.info('Loaded pyproject.toml') except (TomlDecodeError, KeyError): log.error("Invalid pyproject.toml", exc_info=True) return False hooks = Pep517HookCaller(source_dir, backend, backend_path) sdist_ok = check_build_sdist(hooks, requires) wheel_ok = check_build_wheel(hooks, requires) if not sdist_ok: log.warning('Sdist checks failed; scroll up to see') if not wheel_ok: log.warning('Wheel checks failed') return sdist_ok
Example #13
Source File: config.py From portray with MIT License | 5 votes |
def toml(location: str) -> dict: """Returns back the configuration found within the projects [TOML](https://github.com/toml-lang/toml#toml) config (if there is one). Generally this is a `pyproject.toml` file at the root of the project with a `[tool.portray]` section defined. """ try: location_exists = os.path.exists(location) if not location_exists: warnings.warn(f'\nNo config file found at location: "{location}"') return {} except Exception as detection_error: warnings.warn(f'\nUnable to check config at "{location}" due to error: {detection_error}') try: toml_config = toml_load(location) tools = toml_config.get("tool", {}) config = tools.get("portray", {}) config["file"] = location if "modules" not in config: if "poetry" in tools and "name" in tools["poetry"]: config["modules"] = [tools["poetry"]["name"]] elif ( "flit" in tools and "metadata" in tools["flit"] and "module" in tools["flit"]["metadata"] ): config["modules"] = [tools["flit"]["metadata"]["module"]] return config except Exception as load_config_error: warnings.warn(f'\nConfig file at "{location}" has errors: {load_config_error}') return {}
Example #14
Source File: config.py From indy-agent with Apache License 2.0 | 5 votes |
def from_file(config_path: str): conf = Config() options = toml.load(config_path) conf.update(options) return conf
Example #15
Source File: mixins.py From RPGenie with MIT License | 5 votes |
def _get_by_ID(ID: int, obj_type: str, file: str, file_format: str=DATA_FORMAT) -> Dict: """ 'Low-level' access to filedata """ with open(file) as f: if file_format == "json": data = json.load(f, parse_int=int, parse_float=float) elif file_format == "toml": data = toml.load(f) else: raise NotImplementedError(f"Missing support for opening files of type: {file_format}") return data[obj_type][str(ID)]
Example #16
Source File: test_proc.py From PyPPL with Apache License 2.0 | 5 votes |
def test_run(caplog, replace_jobmgr, tmp_path): from pyppl.job import Job Job.state = None runtime_config = Config() runtime_config._load({'default': {'dirsig': False}}) pProcRun = Proc(ppldir=tmp_path) pProcRun.input = {'a': [1]} pProcRun.output = 'outfile:file:{{a}}.txt' with pytest.raises(SystemExit): pProcRun.run(runtime_config) assert pProcRun.channel == [ (pProcRun.jobs[0].dir.joinpath('output/1.txt'), ) ] assert 'WORKDIR' in caplog.text assert 'pProcRun: Jobs [Cached: 0, Succ: 0, B.Fail: 0, S.Fail: 0, R.Fail: 0]' in caplog.text pProcRun1 = Proc(ppldir=tmp_path, input='a', output='a:var:1', errhow='ignore') pProcRun2 = Proc(ppldir=tmp_path, input='a', depends=pProcRun1, output='a:var:1', errhow='ignore') pProcRun1.run(runtime_config) pProcRun2.run(runtime_config) # see if depends have been saved in settings with open(pProcRun2.workdir / 'proc.settings.toml') as f: settings = toml.load(f) assert settings['depends'] == ['pProcRun1.notag']
Example #17
Source File: converters.py From Box with MIT License | 5 votes |
def _from_toml(toml_string=None, filename=None, encoding="utf-8", errors="strict"): if filename: _exists(filename) with open(filename, 'r', encoding=encoding, errors=errors) as f: data = toml.load(f) elif toml_string: data = toml.loads(toml_string) else: raise BoxError('from_toml requires a string or filename') return data
Example #18
Source File: __init__.py From lastcast with MIT License | 5 votes |
def load_config(path): ''' Parse config at given absolute path and check for required keys. ''' config = toml.load(path) if 'lastfm' in config: for k in ['api_key', 'api_secret', 'user_name', 'password']: assert k in config['lastfm'], 'Missing required lastfm option: %s' % k if 'librefm' in config: for k in ['password', 'user_name', 'session_key']: assert k in config['librefm'], 'Missing required librefm option: %s' % k return config
Example #19
Source File: project.py From pipenv with MIT License | 5 votes |
def calculate_pipfile_hash(self): # Update the lockfile if it is out-of-date. p = pipfile.load(self.pipfile_location, inject_env=False) return p.hash
Example #20
Source File: project.py From pipenv with MIT License | 5 votes |
def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = json.loads(pfile.lock()) for section in ("default", "develop"): lock_section = lockfile.get(section, {}) for key in list(lock_section.keys()): norm_key = pep423_name(key) lockfile[section][norm_key] = lock_section.pop(key) return lockfile
Example #21
Source File: config.py From isthislegit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def load_config(config_path=None): if config_path is None: config_path = environ.get( 'ISTHISLEGIT_CONFIG', path.join(path.dirname(__file__), 'isthislegit.toml'), ) with open(config_path) as f: return toml.load(f)
Example #22
Source File: project.py From pipenv with MIT License | 5 votes |
def _read_pyproject(self): # type: () -> None pyproject = self.path_to("pyproject.toml") if os.path.exists(pyproject): self._pyproject = toml.load(pyproject) build_system = self._pyproject.get("build-system", None) if not os.path.exists(self.path_to("setup.py")): if not build_system or not build_system.get("requires"): build_system = { "requires": ["setuptools>=40.8.0", "wheel"], "build-backend": get_default_pyproject_backend(), } self._build_system = build_system
Example #23
Source File: build.py From pipenv with MIT License | 5 votes |
def load_system(source_dir): """ Load the build system from a source dir (pyproject.toml). """ pyproject = os.path.join(source_dir, 'pyproject.toml') with open(pyproject) as f: pyproject_data = toml.load(f) return pyproject_data['build-system']
Example #24
Source File: settings.py From python-semantic-release with MIT License | 5 votes |
def _config_from_pyproject(path): if not os.path.isfile(path): return {} try: pyproject = toml.load(path) return pyproject.get("tool", {}).get("semantic_release", {}) except toml.TomlDecodeError: logger.debug("Could not decode pyproject.toml") return {}
Example #25
Source File: envbuild.py From pipenv with MIT License | 5 votes |
def _load_pyproject(source_dir): with open(os.path.join(source_dir, 'pyproject.toml')) as f: pyproject_data = toml.load(f) buildsys = pyproject_data['build-system'] return ( buildsys['requires'], buildsys['build-backend'], buildsys.get('backend-path'), )
Example #26
Source File: sciwing_toml_runner.py From sciwing with MIT License | 5 votes |
def _parse_toml_file(self): """ Parses the toml file and returns the document Returns ------- Dict[str, Any] The dictionary by parsing the toml file """ try: with open(self.toml_filename) as fp: doc = toml.load(fp) return doc except FileNotFoundError: print(f"File {self.toml_filename} is not found")
Example #27
Source File: config.py From aries-protocol-test-suite with Apache License 2.0 | 5 votes |
def load_config(config_file: str): """Load configuration from toml file.""" return toml.load(config_file)['config']
Example #28
Source File: build.py From pex with Apache License 2.0 | 5 votes |
def load_system(source_dir): """ Load the build system from a source dir (pyproject.toml). """ pyproject = os.path.join(source_dir, 'pyproject.toml') with open(pyproject) as f: pyproject_data = toml.load(f) return pyproject_data['build-system']
Example #29
Source File: check.py From pex with Apache License 2.0 | 5 votes |
def check(source_dir): pyproject = pjoin(source_dir, 'pyproject.toml') if isfile(pyproject): log.info('Found pyproject.toml') else: log.error('Missing pyproject.toml') return False try: with open(pyproject) as f: pyproject_data = toml_load(f) # Ensure the mandatory data can be loaded buildsys = pyproject_data['build-system'] requires = buildsys['requires'] backend = buildsys['build-backend'] backend_path = buildsys.get('backend-path') log.info('Loaded pyproject.toml') except (TomlDecodeError, KeyError): log.error("Invalid pyproject.toml", exc_info=True) return False hooks = Pep517HookCaller(source_dir, backend, backend_path) sdist_ok = check_build_sdist(hooks, requires) wheel_ok = check_build_wheel(hooks, requires) if not sdist_ok: log.warning('Sdist checks failed; scroll up to see') if not wheel_ok: log.warning('Wheel checks failed') return sdist_ok
Example #30
Source File: envbuild.py From pex with Apache License 2.0 | 5 votes |
def _load_pyproject(source_dir): with open(os.path.join(source_dir, 'pyproject.toml')) as f: pyproject_data = toml.load(f) buildsys = pyproject_data['build-system'] return ( buildsys['requires'], buildsys['build-backend'], buildsys.get('backend-path'), )