async def init_db(ctx: Context, safe): config = ctx.obj["config"] location = ctx.obj["location"] app = ctx.obj["app"] dirname = os.path.join(location, app) if not os.path.isdir(dirname): os.mkdir(dirname) click.secho(f"Success create app migrate location {dirname}", fg=Color.green) else: return click.secho(f"Inited {app} already", fg=Color.yellow) Migrate.write_old_models(config, app, location) await Tortoise.init(config=config) connection = get_app_connection(config, app) await generate_schema_for_client(connection, safe) schema = get_schema_sql(connection, safe) version = await Migrate.generate_version() await Aerich.create(version=version, app=app) with open(os.path.join(dirname, version), "w") as f: content = { "upgrade": schema, } json.dump(content, f, ensure_ascii=False, indent=2) return click.secho(f'Success generate schema for app "{app}"', fg=Color.green)
async def create(self): await self.connection.call( "lovelace/dashboards/create", title=self.manifest["title"], url_path=self.manifest["url_path"], ) await self.update() click.secho(f"{self.kind}/{self.description} was created.", fg="green")
async def shutdown(signal_inst: signal): """ try to shut down gracefully """ click.secho(f"Received exit signal {signal_inst.name}...") tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] [task.cancel() for task in tasks] click.secho("Canceling outstanding tasks") await asyncio.gather(*tasks)
async def delete(self): remote = await self.get_remote() if not remote: # Already deleted return await self.connection.call( "config/area_registry/delete", area_id=remote["area_id"] ) click.secho(f"{self.kind}/{self.description} was deleted.", fg="green")
async def heads(ctx: Context): app = ctx.obj["app"] versions = Migrate.get_all_version_files() is_heads = False for version in versions: if not await Aerich.exists(version=version, app=app): click.secho(version, fg=Color.green) is_heads = True if not is_heads: click.secho("No available heads,try migrate", fg=Color.green)
async def migrate(ctx: Context, name): config = ctx.obj["config"] location = ctx.obj["location"] app = ctx.obj["app"] ret = await Migrate.migrate(name) if not ret: return click.secho("No changes detected", fg=Color.yellow) Migrate.write_old_models(config, app, location) click.secho(f"Success migrate {ret}", fg=Color.green)
async def select_pool(ctx): click.clear() click.echo("==================") click.echo(" Download Pools ") click.echo("==================") click.echo("") click.echo("Please give me the URLs and/or pool ID.") click.echo("When you're done, you can give me an empty line.") pools = [] while True: # fmt: off response = click.prompt("", prompt_suffix="> ", default="", show_default=False) # fmt: on if not response or not response.strip(): if not pools: continue break pool_id = get_pool_id(response) if not pool_id: click.secho("Please send valid URL or pool ID!") continue obj = await get_pool(ctx, pool_id) if obj: print_pool(obj) pools.append(obj) # noqa else: click.secho(f'Pool "{pool_id}" was not found.') # noqa output = click.prompt("Where will the images be saved? ", type=click.Path(), default=".") jobs = click.prompt( "How many concurrent jobs will be done? " "(If you don't know what that means, just leave it as is.)", type=int, default=4, ) type_ = click.prompt( "Which quality do you want to download? ", type=click.Choice(["sample", "file", "preview"]), default="file", ) await ctx.invoke(pool, pool_id=-1, output=output, jobs=jobs, type=type_, pools=pools)
async def apply(self): """Apply target state to a resource in Home Assistant, creating it if it doesn't exist.""" remote = await self.get_remote() if remote and self.update_policy == "recreate": await self.delete() remote = None if not await self.get_remote(): click.secho(f"Creating {self.description}", fg="green") await self.create() return await self.update()
async def delete(self): if self.manifest["url_path"] is None: click.secho(f"Cannot delete root dashboard", fg="red") return remote = await self.get_remote() if not remote: # Already deleted return await self.connection.call( "lovelace/dashboards/delete", dashboard_id=remote["id"] ) click.secho(f"{self.kind}/{self.description} was deleted.", fg="green")
async def init( ctx: Context, tortoise_orm, location, ): config = ctx.obj["config"] name = ctx.obj["name"] parser.add_section(name) parser.set(name, "tortoise_orm", tortoise_orm) parser.set(name, "location", location) with open(config, "w") as f: parser.write(f) if not os.path.isdir(location): os.mkdir(location) click.secho(f"Success create migrate location {location}", fg=Color.green) click.secho(f"Success generate config file {config}", fg=Color.green)
async def upgrade(ctx: Context): config = ctx.obj["config"] app = ctx.obj["app"] migrated = False for version in Migrate.get_all_version_files(): if not await Aerich.exists(version=version, app=app): async with in_transaction(get_app_connection_name(config, app)) as conn: file_path = os.path.join(Migrate.migrate_location, version) with open(file_path, "r") as f: content = json.load(f) upgrade_query_list = content.get("upgrade") for upgrade_query in upgrade_query_list: await conn.execute_query(upgrade_query) await Aerich.create(version=version, app=app) click.secho(f"Success upgrade {version}", fg=Color.green) migrated = True if not migrated: click.secho("No migrate items", fg=Color.yellow)
async def downgrade(ctx: Context): app = ctx.obj["app"] config = ctx.obj["config"] last_version = await Migrate.get_last_version() if not last_version: return click.secho("No last version found", fg=Color.yellow) file = last_version.version async with in_transaction(get_app_connection_name(config, app)) as conn: file_path = os.path.join(Migrate.migrate_location, file) with open(file_path, "r") as f: content = json.load(f) downgrade_query_list = content.get("downgrade") if not downgrade_query_list: return click.secho(f"No downgrade item dound", fg=Color.yellow) for downgrade_query in downgrade_query_list: await conn.execute_query(downgrade_query) await last_version.delete() return click.secho(f"Success downgrade {file}", fg=Color.green)
async def init_db(ctx: Context, safe): config = ctx.obj["config"] location = ctx.obj["location"] app = ctx.obj["app"] dirname = os.path.join(location, app) if not os.path.isdir(dirname): os.mkdir(dirname) click.secho(f"Success create app migrate location {dirname}", fg=Color.green) else: return click.secho(f'Already inited app "{app}"', fg=Color.yellow) Migrate.write_old_models(config, app, location) await Tortoise.init(config=config) connection = get_app_connection(config, app) await generate_schema_for_client(connection, safe) return click.secho(f'Success generate schema for app "{app}"', fg=Color.green)
async def upgrade(ctx: Context): app = ctx.obj["app"] config = ctx.obj["config"] available_versions = Migrate.get_all_version_files(is_all=False) if not available_versions: return click.secho("No migrate items", fg=Color.yellow) async with in_transaction(get_app_connection_name(config, app)) as conn: for file in available_versions: file_path = os.path.join(Migrate.migrate_location, file) with open(file_path, "r") as f: content = json.load(f) upgrade_query_list = content.get("upgrade") for upgrade_query in upgrade_query_list: await conn.execute_query(upgrade_query) with open(file_path, "w") as f: content["migrate"] = True json.dump(content, f, indent=2, ensure_ascii=False) click.secho(f"Success upgrade {file}", fg=Color.green)
async def init( ctx: Context, tortoise_orm, location, ): config_file = ctx.obj["config_file"] name = ctx.obj["name"] if os.path.exists(config_file): return click.secho("You have inited", fg=Color.yellow) parser.add_section(name) parser.set(name, "tortoise_orm", tortoise_orm) parser.set(name, "location", location) with open(config_file, "w") as f: parser.write(f) if not os.path.isdir(location): os.mkdir(location) click.secho(f"Success create migrate location {location}", fg=Color.green) click.secho(f"Success generate config file {config_file}", fg=Color.green)
async def get(ctx, kind, name): """Describe a Home Assistant resource as a manifest.""" resource_cls = Resource.class_for_kind(kind) if not resource_cls: click.secho(f"Unknown kind {kind!r}", fg="red") return connection = await get_connection(ctx.obj["config"]) try: area = resource_cls(connection, {}) state = await area.get_remote() if not state: click.secho(f"Object {type}/{name} could not be found", fg="red") return click.echo(state) finally: await connection.close()
async def all_info(ctx, self, *args, **kwargs): if ctx.invoked_subcommand: # type: ignore return print() # all: Iterable[PkgTing] = await self._tingistry.get_all_pkgs() index_ids = self._bring.index_ids pkgs = await self._bring.get_alias_pkg_map() pkgs_info = await get_values_for_pkgs(pkgs.values(), "info") index_info = {} for pkg, info in pkgs_info.items(): index_info.setdefault(pkg.bring_index.id, {})[pkg] = info for idx_id in index_ids: click.secho(idx_id, bold=True) click.echo() table = create_info_table_string(index_info[idx_id]) click.echo(reindent(table, 2)) click.echo()
try: for resource in resources: await resource.delete() finally: await connection.close() if __name__ == "__main__": try: main(_anyio_backend="asyncio") except KeyboardInterrupt: pass except ManifestError as e: click.secho("Exiting due to an error with the supplied manifest", fg="red") click.echo(str(e)) except HomeAssistantError as e: click.secho( "Exiting due to an error communicating with the Home Assistant instance", fg="red", ) click.echo(str(e)) except ApplicationError as e: click.secho("Exiting due to an error", fg="red") click.echo(str(e))
def heads(ctx: Context): for version in Migrate.get_all_version_files(is_all=False): click.secho(version, fg=Color.green)
def test_secho_non_text(runner, value, expect): with runner.isolation() as (out, _): click.secho(value, nl=False, color=True, bg="magenta") result = out.getvalue() assert result == expect
def history(ctx): for version in Migrate.get_all_version_files(): click.secho(version, fg=Color.green)
def hello(name): click.secho(f"Hello, {name}!", fg="green")
def error(message): click.secho("[ERR] " + str(message), fg="red")
def history(ctx): versions = Migrate.get_all_version_files() for version in versions: click.secho(version, fg=Color.green) if not versions: click.secho("No history,try migrate", fg=Color.green)
def warning(message): click.secho("[WARN] " + str(message), fg="yellow")
def verbose(message): ctx = click.get_current_context() if ctx.obj["verbose"]: click.secho("[VERB] " + str(message), fg="blue")
def test_secho(runner): with runner.isolation() as outstreams: click.secho(None, nl=False) bytes = outstreams[0].getvalue() assert bytes == b''
def invalid_input(ctx): click.secho("Invalid input!")
def cli(): click.secho("hello world", fg="blue")
def cli(): click.secho('hello world', fg='blue')