def read_edits(f): """Read the edits from the provided file. Arguments: f (file): The file, containing user edits. Returns: A `dict` containing the new alias, command and description. """ d = dict() for line in f: if "=" in line: # Strip out the edited alias, command and description from the # file. entry = [ln.strip() for ln in line.split("=", 1)] d[entry[0].lower()] = entry[1] # Check if the edits are valid, if not, cancel execution and print the # proper error message. err_message = validate_edits(d) if err_message: helpers.exit(err_message) return d
def remove_tomb(ctx, tomb_name): """Removes a tomb from the catacomb. Arguments: tomb_name (str): The name of the new tomb. """ if is_existing_tomb(ctx, tomb_name): os.remove(os.path.join(ctx.obj.catacomb_dir, tomb_name)) else: helpers.exit(errors.TOMB_BURY_UNKNOWN.format(tomb_name))
def update(path, contents): """Updates the file at the given path with the provided contents. Arguments: contents (str): The file contents. """ if not os.path.exists(path): helpers.exit(errors.FILE_UPDATE_UNKNOWN.format(path)) with open(path, "w") as f: f.write(json.dumps(contents, indent=constants.INDENT_NUM_SPACES))
def open_tomb(ctx, tomb_name): """Opens the specified tomb, granting access to its contents/commands to the user. Arguments: tomb_name (str): The name of the new tomb. """ if is_existing_tomb(ctx, tomb_name): ctx.obj.set_open_tomb(tomb_name) else: helpers.exit(errors.TOMB_OPEN_UNKNOWN.format(tomb_name))
def edit(ctx, alias): """Edits a command if it's present in the active tomb. Opens an editor for the user with the details for the specified command, allowing edits to the alias, command and description. Arguments: alias (str): The alias of the command to edit. """ if not tomb_handler.is_existing_command(ctx, alias): helpers.exit(constants.WARN_CMD_NOT_FOUND.format(alias)) editor = os.environ.get("EDITOR", helpers.default_editor()) cmd_info = tomb_handler.get_command(ctx, alias, True) fname = helpers.random_fname() # Creates a temporary file with the current command information, allowing # edits. with open(fname, "w") as temp_file: # Append the initial message to the file. temp_file.write(constants.CMD_EDIT_INIT_MSG.format( alias, cmd_info[0], cmd_info[1])) # Open the file within an editor. call([editor, temp_file.name]) # Reads the changes to the file after the user is done with it. with open(fname, "r") as temp_file: edits = read_edits(temp_file) # Clean up. os.remove(fname) # The edited alias already exists in the active tomb. if edits["alias"] != alias and tomb_handler.is_existing_command( ctx, edits["alias"]): update = click.prompt( constants.CMD_EDIT_OVERWRITE_PROMPT.format(alias)) if update.lower() != "y": # Abort the action. helpers.exit(constants.WARN_ACTION_ABORTED) else: # We need to remove the old command if we're not overwriting it. tomb_handler.remove_command(ctx, alias) elif not tomb_handler.is_existing_command(ctx, edits["alias"]): # Remember to remove the old command if we're adding a new one. tomb_handler.remove_command(ctx, alias) # Update the command. tomb_handler.add_command( ctx, edits["command"], edits["alias"], edits["description"]) formatter.print_success(constants.CMD_EDIT_OK)
def format_cmd(alias, cmd, params): """Formats a command with user provided parameters, similar to the Python `format()` method. Arguments: cmd (str): The command. params (tuple): Parameters to be formatted into the command. Returns: A `string` representing the newly formatted command. """ try: # In the case of more parameters vs placeholders, we will exhaust what # we can (in order) and run the command anyway. If nothing can be # substituted, the formatting will be ignored and the command will be # run as is. return cmd.format(*params) except IndexError: # Not all the placeholders are provided with a value. helpers.exit(constants.WARN_FMT_NUM_PARAMS.format(alias, len(params))) except KeyError: # Placeholders aren't following the correct syntax. helpers.exit(constants.WARN_FMT_PLACEHOLDER_SYNTAX) except ValueError: # Inconsistent use of placeholders in a command. helpers.exit(constants.WARN_FMT_PLACEHOLDER_SYNTAX2) except Exception: # This shouldn't be reachable, but just in case, we'll report it. helpers.exit(errors.INVALID_FORMAT_USE_CMD.format(cmd))
def create(path, contents=None): """Creates a new file at the given path. Arguments: contents (str): The file contents. """ if os.path.exists(path): helpers.exit(errors.FILE_CREATE_OVERWRITE.format(path)) if not contents: # Allow the creation of an empty file. contents = "" with open(path, "w") as f: f.write(json.dumps(contents, indent=constants.INDENT_NUM_SPACES))
def read(path): """Read the file at the given path. Arguments: path (str): The path of the file to read. Returns: A `dict`, representing the contents of the file, if the file exists. """ if not os.path.exists(path): helpers.exit(errors.FILE_READ_UNKNOWN.format(path)) with open(path, "r") as f: contents = json.load(f) return contents