def dump_pipfile(path: PathLike, pipfile: TOMLDocument) -> None: reorder_container(pipfile, pipfile_section_key, key_type=KeyType.Bare) for name in ("packages", "dev-packages"): try: section = pipfile.item(name) except KeyError: pass else: container = section.value reorder_container(container, pipfile_packages_key, key_type=KeyType.Basic) value = pipfile.as_string() try: with open(path, "r") as fp: old_value = fp.read() except OSError: old_value = "" if value != old_value: diff = difflib.ndiff(old_value.splitlines(True), value.splitlines(True)) print("".join(diff), end="") with open(path, "w") as fp: fp.write(value)
def update_requirements(path: PathLike, pipfile: TOMLDocument) -> None: sources = list(filterfalse(is_default, pipfile.get("source", []))) packages = pipfile.get("packages", {}) requirements = list(starmap(Requirement.from_pipfile, packages.items())) requirements.sort(key=requirement_sort_key) lines = [r.as_line(sources) + os.linesep for r in requirements] with open(path, "w") as fp: fp.writelines(lines)
def data(self): # type: () -> TOMLDocument if self._data is None: if not self._file.exists(): self._data = TOMLDocument() else: self._data = self._file.read() return self._data
def test_pyproject_toml_non_existent(pyproject_toml): pyproject_toml.unlink() pyproject = PyProjectTOML(pyproject_toml) build_system = pyproject.build_system assert pyproject.data == TOMLDocument() assert build_system.requires == ["poetry-core"] assert build_system.build_backend == "poetry.core.masonry.api"
def data(self) -> "TOMLDocument": from tomlkit.toml_document import TOMLDocument if self._data is None: if not self._file.exists(): self._data = TOMLDocument() else: self._data = self._file.read() return self._data
def read_file(file: TOMLDocument): cfgs = [] for key, value in list(file.items()): if key == "automod": if type(value) != Table: raise ConfigurationError( f"Expected a subtable, got {value.__class__.__name__} instead." ) for key, value in list(value.items()): cfgs.append(parse_config(key, value)) return cfgs
def read_config_file(username=None): config_path = CONFIG_BASE_PATH / (username or '') / 'google-music-scripts.toml' config_file = TOMLFile(config_path) try: config = config_file.read() except FileNotFoundError: config = TOMLDocument() write_config_file(config, username=username) return config
def read_config_file(): config_file = TOMLFile(CONFIG_PATH) try: config = config_file.read() except FileNotFoundError: config = TOMLDocument() if 'trackers' not in config: config['trackers'] = SortedDict() write_config_file(config) return config
def _validate(self, data: TOMLDocument) -> None: nonebot_data = data.setdefault("nonebot", tomlkit.table()) if not isinstance(nonebot_data, Table): raise ValueError("'nonebot' in toml file is not a Table!") plugin_data = nonebot_data.setdefault("plugins", tomlkit.table()) if not isinstance(plugin_data, Table): raise ValueError("'nonebot.plugins' in toml file is not a Table!") plugins = plugin_data.setdefault("plugins", tomlkit.array()) if not isinstance(plugins, Array): raise ValueError( "'nonebot.plugins.plugins' in toml file is not a Array!") plugin_dirs = plugin_data.setdefault("plugin_dirs", tomlkit.array()) if not isinstance(plugin_dirs, Array): raise ValueError( "'nonebot.plugins.plugin_dirs' in toml file is not a Array!")
def _verify_journal_paths(config: TOMLDocument) -> None: missing = [] for journal_name, journal_config in config["pen"].get("journals", {}).items(): if "path" in journal_config: path = Path(journal_config["path"]) if not path.exists(): print_err( f"Journal at {path} does not seem to exist anymore. If you" f" moved it, use 'pen import <path>' so that Pen can find it" f" again.") missing.append(journal_name) for journal in missing: del config.get("journals")[journal]
def create(self) -> None: if not self.path.exists(): try: mode = 0o700 # only current user can modify file self.path.parent.mkdir(mode, parents=True, exist_ok=True) self.path.touch(mode) cfg = TOMLDocument() cfg["pen"] = {} self.write(cfg) except Exception as err: try: # clean up if it was created already self.path.unlink() except FileNotFoundError: pass raise RuntimeError( f"Could not create config file at {self.path}") from err
def write_header_comment(from_doc: TOMLDocument, to_doc: TOMLDocument) -> None: """Write header comment from the FROM doc to the TO doc. Only writes comments / whitespace from the beginning of a TOML document. Anything from later in the document is ambiguous and cannot be sorted accurately. """ for _, value in from_doc.body: if isinstance(value, Whitespace): to_doc.add(ws("\n")) elif isinstance(value, Comment): value.trivia.indent = "" to_doc.add(Comment(value.trivia)) else: to_doc.add(ws("\n")) return
def install_command(config: "AppConfig") -> None: time_locale = "" date_order = "" time_first = None journal_dir = os.getenv(PEN_HOME_ENV, "") print_err(_welcome_message) time.sleep(_install_msg_delay) print_err(_returning_prompt) time.sleep(_install_msg_delay) returning = yes_no("Sync existing journals", default=False) print_err(_divider) time.sleep(_install_msg_delay) if returning: git_sync = setup_sync() else: print_err(_sync_message) time.sleep(_install_msg_delay) print_err(_sync_prompt) time.sleep(_install_msg_delay) git_sync = yes_no("Activate git sync", default=True) print_err(_divider) time.sleep(_install_msg_delay) if git_sync: from .gitsync import init init() if not journal_dir: print_err(_pen_dir_returning_prompt if returning else _pen_dir_prompt) time.sleep(_install_msg_delay) journal_dir = ask("Where should we put your journals", default=str(DEFAULT_PEN_HOME)) journal_dir = str(Path(journal_dir).expanduser().absolute()) print_err(_divider) time.sleep(_install_msg_delay) # todo check if journals already exist in journal_directory and import locale_from_env = config.get("locale") if locale_from_env and convert_to_dateparser_locale(locale_from_env): time_locale = locale_from_env print_err(_locale_message.format(time_locale)) print_err(_divider) time.sleep(_install_msg_delay) else: date_options = ["DMY", "MDY", "YMD"] date_order = ask( "What is your preferred date ordering (for Day, Month, Year)", date_options) time.sleep(_install_msg_delay) time_first_answer = ask( "Do you prefer to input the date or time first ('July 5th 9:30' or" " '9:30 July 5th')", ["date", "time"], default="date", ) time_first = time_first_answer == "time" print_err(_divider) time.sleep(_install_msg_delay) print_err(_default_journal_message) time.sleep(_install_msg_delay) default_journal = ask( "How do you want to call your default journal", default="default", validator=lambda s: len(s) >= 1, ) print_err(_divider) time.sleep(_install_msg_delay * 2) new_config = TOMLDocument() new_config["pen"] = {} new_config["pen"]["default_journal"] = default_journal new_config["pen"]["journal_directory"] = journal_dir new_config["pen"]["git_sync"] = git_sync if date_order: new_config["pen"]["date_order"] = date_order if time_first: new_config["pen"]["time_before_date"] = time_first if time_locale: new_config["pen"]["locale"] = time_locale for key, value in new_config["pen"].items(): config.set(key, value) config.save(new_config) print_err("All done! You can now start using pen!") print_err("Hit enter to start writing your first entry...") print_err() input() # just so editor doesn't open immediately after last question
def write(self, data: TOMLDocument) -> None: self.path.parent.mkdir(parents=True, exist_ok=True) with self.path.open("w") as f: f.write(data.as_string())