Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make scripts available via CLI #2426

Merged
merged 2 commits into from
Jul 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 8 additions & 67 deletions homeassistant/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import subprocess
import sys
import threading
import time

from homeassistant.const import (
__version__,
Expand Down Expand Up @@ -110,22 +109,14 @@ def get_arguments():
type=int,
default=None,
help='Enables daily log rotation and keeps up to the specified days')
parser.add_argument(
'--install-osx',
action='store_true',
help='Installs as a service on OS X and loads on boot.')
parser.add_argument(
'--uninstall-osx',
action='store_true',
help='Uninstalls from OS X.')
parser.add_argument(
'--restart-osx',
action='store_true',
help='Restarts on OS X.')
parser.add_argument(
'--runner',
action='store_true',
help='On restart exit with code {}'.format(RESTART_EXIT_CODE))
parser.add_argument(
'--script',
nargs=argparse.REMAINDER,
help='Run one of the embedded scripts')
if os.name == "posix":
parser.add_argument(
'--daemon',
Expand Down Expand Up @@ -196,46 +187,6 @@ def write_pid(pid_file):
sys.exit(1)


def install_osx():
"""Setup to run via launchd on OS X."""
with os.popen('which hass') as inp:
hass_path = inp.read().strip()

with os.popen('whoami') as inp:
user = inp.read().strip()

cwd = os.path.dirname(__file__)
template_path = os.path.join(cwd, 'startup', 'launchd.plist')

with open(template_path, 'r', encoding='utf-8') as inp:
plist = inp.read()

plist = plist.replace("$HASS_PATH$", hass_path)
plist = plist.replace("$USER$", user)

path = os.path.expanduser("~/Library/LaunchAgents/org.homeassistant.plist")

try:
with open(path, 'w', encoding='utf-8') as outp:
outp.write(plist)
except IOError as err:
print('Unable to write to ' + path, err)
return

os.popen('launchctl load -w -F ' + path)

print("Home Assistant has been installed. \
Open it here: http://localhost:8123")


def uninstall_osx():
"""Unload from launchd on OS X."""
path = os.path.expanduser("~/Library/LaunchAgents/org.homeassistant.plist")
os.popen('launchctl unload ' + path)

print("Home Assistant has been uninstalled.")


def closefds_osx(min_fd, max_fd):
"""Make sure file descriptors get closed when we restart.

Expand Down Expand Up @@ -358,23 +309,13 @@ def main():

args = get_arguments()

if args.script is not None:
from homeassistant import scripts
return scripts.run(args.script)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there are two levels of 'argparse', here and in the script, wont duplicate --args be interpreted by the first argparse and never be passed to script.run?

(i.e -c or --config in the script)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, that's why the script arg in main uses the remain option. Try it by
passing help before and after invoking the dB migrate script

On Sat, Jul 2, 2016, 22:38 Johann Kellerman [email protected]
wrote:

In homeassistant/main.py
#2426 (comment)
:

@@ -358,23 +309,13 @@ def main():

 args = get_arguments()
  • if args.script is not None:
  •    from homeassistant import scripts
    
  •    return scripts.run(args.script)
    

If there are two levels of 'argparse', here and in the script, wont
duplicate --args be interpreted by the first argparse and never be passed
to script.run?

(i.e -c or --config in the script)


You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/home-assistant/home-assistant/pull/2426/files/fd92c34a19241ec6d9f8c3cd19b7d3511fd4fc85#r69385902,
or mute the thread
https://github.com/notifications/unsubscribe/ABYJ2iuC-a_PDkAVi_FktFK0pthL3PRSks5qR0rCgaJpZM4JDvUs
.


config_dir = os.path.join(os.getcwd(), args.config)
ensure_config_path(config_dir)

# OS X launchd functions
if args.install_osx:
install_osx()
return 0
if args.uninstall_osx:
uninstall_osx()
return 0
if args.restart_osx:
uninstall_osx()
# A small delay is needed on some systems to let the unload finish.
time.sleep(0.5)
install_osx()
return 0

# Daemon functions
if args.pid_file:
check_pid(args.pid_file)
Expand Down
22 changes: 22 additions & 0 deletions homeassistant/scripts/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Home Assistant command line scripts."""
import importlib
import os


def run(args):
"""Run a script."""
scripts = [fil[:-3] for fil in os.listdir(os.path.dirname(__file__))
if fil.endswith('.py') and fil != '__init__.py']

if not args:
print('Please specify a script to run.')
print('Available scripts:', ', '.join(scripts))
return 1

if args[0] not in scripts:
print('Invalid script specified.')
print('Available scripts:', ', '.join(scripts))
return 1

script = importlib.import_module('homeassistant.scripts.' + args[0])
return script.run(args[1:])
23 changes: 11 additions & 12 deletions ...stant/scripts/convert_db_to_sqlalchemy.py → homeassistant/scripts/db_migrator.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python

"""Script to convert an old-format home-assistant.db to a new format one."""

import argparse
Expand Down Expand Up @@ -46,11 +44,11 @@ def print_progress(iteration, total, prefix='', suffix='', decimals=2,
print("\n")


def main():
def run(args):
"""The actual script body."""
# pylint: disable=too-many-locals,invalid-name,too-many-statements
parser = argparse.ArgumentParser(
description="Home Assistant: Observe, Control, Automate.")
description="Migrate legacy DB to SQLAlchemy format.")
parser.add_argument(
'-c', '--config',
metavar='path_to_config_dir',
Expand All @@ -66,6 +64,9 @@ def main():
type=str,
help="Connect to URI and import (implies --append)"
"eg: mysql://localhost/homeassistant")
parser.add_argument(
'--script',
choices=['db_migrator'])

args = parser.parse_args()

Expand All @@ -76,7 +77,7 @@ def main():
if config_dir != config_util.get_default_config_dir():
print(('Fatal Error: Specified configuration directory does '
'not exist {} ').format(config_dir))
sys.exit(1)
return 1
else:
config_dir = config_util.get_default_config_dir()

Expand All @@ -86,13 +87,13 @@ def main():
if not os.path.exists(src_db):
print("Fatal Error: Old format database '{}' does not exist".format(
src_db))
sys.exit(1)
return 1
if not args.uri and (os.path.exists(dst_db) and not args.append):
print("Fatal Error: New format database '{}' exists already - "
"Remove it or use --append".format(dst_db))
print("Note: --append must maintain an ID mapping and is much slower")
print("and requires sufficient memory to track all event IDs")
sys.exit(1)
print("Note: --append must maintain an ID mapping and is much slower"
"and requires sufficient memory to track all event IDs")
return 1

conn = sqlite3.connect(src_db)
uri = args.uri or "sqlite:///{}".format(dst_db)
Expand Down Expand Up @@ -182,6 +183,4 @@ def main():
print_progress(n, num_rows)
session.commit()
c.close()

if __name__ == "__main__":
main()
return 0
64 changes: 64 additions & 0 deletions homeassistant/scripts/macos.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Script to install/uninstall HA into OS X."""
import os
import time


def install_osx():
"""Setup to run via launchd on OS X."""
with os.popen('which hass') as inp:
hass_path = inp.read().strip()

with os.popen('whoami') as inp:
user = inp.read().strip()

cwd = os.path.dirname(__file__)
template_path = os.path.join(cwd, 'startup', 'launchd.plist')

with open(template_path, 'r', encoding='utf-8') as inp:
plist = inp.read()

plist = plist.replace("$HASS_PATH$", hass_path)
plist = plist.replace("$USER$", user)

path = os.path.expanduser("~/Library/LaunchAgents/org.homeassistant.plist")

try:
with open(path, 'w', encoding='utf-8') as outp:
outp.write(plist)
except IOError as err:
print('Unable to write to ' + path, err)
return

os.popen('launchctl load -w -F ' + path)

print("Home Assistant has been installed. \
Open it here: http://localhost:8123")


def uninstall_osx():
"""Unload from launchd on OS X."""
path = os.path.expanduser("~/Library/LaunchAgents/org.homeassistant.plist")
os.popen('launchctl unload ' + path)

print("Home Assistant has been uninstalled.")


def run(args):
"""Handle OSX commandline script."""
commands = 'install', 'uninstall', 'restart'
if not args or args[0] not in commands:
print('Invalid command. Available commands:', ', '.join(commands))
return 1

if args[0] == 'install':
install_osx()
return 0
elif args[0] == 'uninstall':
uninstall_osx()
return 0
elif args[0] == 'restart':
uninstall_osx()
# A small delay is needed on some systems to let the unload finish.
time.sleep(0.5)
install_osx()
return 0