easily manage build commands
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.5 KiB

3 years ago
  1. #!/home/schneider/git/dirbuild/
  2. """dirbuild
  3. Usage:
  4. dirbuild
  5. dirbuild set <command>
  6. dirbuild get
  7. dirbuild build
  8. dirbuild dump
  9. Options:
  10. -h --help Show this screen.
  11. --version Show version.
  12. """
  13. import logging
  14. import os
  15. import sqlite3
  16. from sqlite3.dbapi2 import Cursor
  17. from docopt import docopt
  18. from xdg import BaseDirectory
  19. logger: logging.Logger
  20. def init_logger():
  21. """Initializes the application logger.
  22. :returns: logger
  23. """
  24. global logger
  25. logger = logging.getLogger()
  26. handler = logging.StreamHandler()
  27. formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s")
  28. handler.setFormatter(formatter)
  29. logger.addHandler(handler)
  30. logger.setLevel(logging.DEBUG)
  31. def init_db() -> sqlite3.Connection:
  32. path = BaseDirectory.save_data_path("dirbuild")
  33. logging.debug("Using path for data: %s", path)
  34. db_path = f"{path}/commands.db"
  35. logging.debug("Using database %s", db_path)
  36. conn = sqlite3.connect(db_path)
  37. conn.cursor().execute(
  38. """CREATE TABLE IF NOT EXISTS commands (id INTEGER PRIMARY KEY AUTOINCREMENT, dir TEXT, cmd TEXT)"""
  39. )
  40. return conn
  41. def set_command(cursor: Cursor, cwd: str, command: str):
  42. """Sets a command for the current directory
  43. :db: sqlite Cursor
  44. :cwd: String
  45. :returns: None
  46. """
  47. logger.debug("Setting command '%s' for directory %s", command, cwd)
  48. cursor.execute(
  49. "INSERT INTO commands (dir, cmd) VALUES (?, ?)",
  50. (
  51. cwd,
  52. command,
  53. ),
  54. )
  55. def get_command(cursor: Cursor, cwd: str) -> str:
  56. """Get the command for the current directory"""
  57. return cursor.execute(
  58. "SELECT cmd FROM commands WHERE dir = ? ORDER BY id DESC LIMIT 1", (cwd,)
  59. ).fetchone()[0]
  60. def dump_db(cursor: Cursor):
  61. """Dump all entries of the database"""
  62. for row in cursor.execute("SELECT id, dir, cmd FROM commands"):
  63. print(row)
  64. def main():
  65. """ Main function """
  66. init_logger()
  67. arguments = docopt(__doc__, version="dirbuild v0.1.0")
  68. logger.debug("arguments: %s", arguments)
  69. db = init_db()
  70. if arguments["set"]:
  71. set_command(db.cursor(), os.getcwd(), arguments["<command>"])
  72. elif arguments["get"]:
  73. print(get_command(db.cursor(), os.getcwd()))
  74. elif arguments["dump"]:
  75. dump_db(db.cursor())
  76. else:
  77. cmd = get_command(db.cursor(), str(os.getcwd()))
  78. logger.debug("Executing '%s'", cmd)
  79. os.system(cmd)
  80. db.commit()
  81. db.close()
  82. if __name__ == "__main__":
  83. main()