示例#1
0
def edit(yaml_file, vault_pass):
    tmp_file_name = '.{}.{}.tmp'.format(random_string(),
                                        os.path.basename(yaml_file))
    original_data = yaml.safe_load(open(yaml_file).read())

    unencrypted_data = decrypt_values(deepcopy(original_data),
                                       vault_pass)

    with open(tmp_file_name, 'w') as tmp_file:
        header = ('# NOTE: This is a vault encrypted yaml file. Every value\n'
                  '# in this file will be encrypted regardless if it wasn\'t\n'
                  '# encrypted before. If you do not wish to encrypt a value,\n'
                  '# you should move it to a non vault encrypted file.\n'
                  '---\n')
        tmp_file.write(header)
        yaml.safe_dump(unencrypted_data,
                       tmp_file,
                       default_flow_style=False)
        tmp_file.close()

    try:
        editor.edit(filename=tmp_file_name, use_tty=True)
        encrypted_data = diff_and_encrypt_values(yaml.safe_load(open(tmp_file_name)),
                                           original_data,
                                           vault_pass)
        yaml.safe_dump(encrypted_data,
                       open(yaml_file, 'w'),
                       default_style='|',
                       default_flow_style=False)
    finally:
        if os.path.exists(tmp_file_name):
            os.remove(tmp_file_name)
示例#2
0
文件: utils.py 项目: mnms/share
def open_vim_editor(target='config'):
    """Open vim editor
    :param target: config | master | slave | thriftserver
    """
    cluster_id = config.get_cur_cluster_id()
    full_path = get_full_path_of_props(cluster_id, target)
    editor.edit(full_path)
示例#3
0
def edit(default_editor):
    """Edit your cellpy config file."""

    config_file = _configloc()
    if config_file:
        config_file_str = str(config_file.resolve())

        if default_editor is not None:
            args = [default_editor, config_file_str]
            click.echo(f"[cellpy] (edit) Calling '{default_editor}'")
            try:
                subprocess.call(args)
            except:
                click.echo(f"[cellpy] (edit) Failed!")
                click.echo(
                    "[cellpy] (edit) Try 'cellpy edit -e notepad.exe' if you are on Windows"
                )

        if default_editor is None:
            try:
                import editor

                editor.edit(filename=config_file_str)
            except ImportError:
                click.echo(f"[cellpy] (edit) Failed!")
                click.echo(
                    f"[cellpy] (edit) Searching for editors uses the python-editor package"
                )
                click.echo(f"[cellpy] (edit) Possible fixes:")
                click.echo(
                    f"[cellpy] (edit) - provide a default editor "
                    f"using the -e option (e.g. cellpy edit -e notepad.exe)")
                click.echo(
                    f"[cellpy] (edit) - install teh python-editor package "
                    f"(pip install python-editor)")
示例#4
0
def edit(path):
    """Given a source path, run the EDITOR for it"""

    import editor
    try:
        editor.edit(path)
    except Exception as exc:
        raise CommandError('Error executing editor (%s)' % (exc, ))
示例#5
0
def edit(path):
    """Given a source path, run the EDITOR for it"""

    import editor
    try:
        editor.edit(path)
    except Exception as exc:
        raise CommandError('Error executing editor (%s)' % (exc,))
示例#6
0
def edit_note(day: date):
    """Launches the default $EDITOR or a suitable default. If the note already exists, the editor opens it for editing.
    If the note does not exist, the editor opens a new file using the stand-up template."""
    note = get_note_name(day)
    date_of_note = "Date: " + day.strftime("%m/%d/%Y") + " \n"
    if os.path.exists(note):
        editor.edit(note)
    else:
        editor.edit(note, contents=date_of_note + STANDUP_TEMPLATE_STRING)
示例#7
0
def edit_note(task, dir, ext='txt'):
    id = task[0]
    task = task[1]

    fn = '.'.join([os.path.join(dir, task['uuid']), ext])
    logger.info('editing {0} for id {1}'.format(fn, id))

    editor.edit(filename=fn, use_tty=True)

    logger.info('in sync-mode: adding/updating task annotation.')
    update_annotation(task, fn)
示例#8
0
    def _parseInput(self,
                    title=None,
                    content=None,
                    tags=None,
                    notebook=None,
                    resources=None,
                    note=None):
        result = {
            "title": title,
            "content": content,
            "tags": tags,
            "notebook": notebook,
            "resources": resources if resources else []
        }
        result = tools.strip(result)

        # if get note without params
        if note and title is None and content is None and tags is None and notebook is None:
            content = config.EDITOR_OPEN

        if title is None and note:
            result['title'] = note.title

        if content:
            if content == config.EDITOR_OPEN:
                logging.debug("launch system editor")
                if note:
                    self.getEvernote().loadNoteContent(note)
                    content = editor.edit(note.content)
                else:
                    content = editor.edit()

            elif isinstance(content, str) and os.path.isfile(content):
                logging.debug("Load content from the file")
                content = open(content, "r").read()

            logging.debug("Convert content")
            content = editor.textToENML(content)

            result['content'] = content

        if tags:
            result['tags'] = tools.strip(tags.split(','))

        if notebook:
            notepadGuid = Notebooks().getNoteGUID(notebook)
            if notepadGuid is None:
                newNotepad = Notebooks().create(notebook)
                notepadGuid = newNotepad.guid

            result['notebook'] = notepadGuid
            logging.debug("Search notebook")

        return result
def main():
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} <service name>", file=sys.stderr)
        sys.exit(1)

    service_name = sys.argv[1]

    with open(f'{service_name}.service', 'w') as f:
        f.write(_render_service(service_name))
    editor.edit(filename=f'{service_name}.service')
    with open(f'{service_name}.timer', 'w') as f:
        f.write(_render_timer(service_name))
    editor.edit(filename=f'{service_name}.timer')
示例#10
0
def nbtedit():
    parser = argparse.ArgumentParser(
        description="Edit an nbt file in-place in yaml format.")
    parser.add_argument("filename", type=str, help="filename")
    parser.add_argument("-n",
                        "--no-gzip",
                        action="store_true",
                        help="Don't use gzip")

    options = parser.parse_args()

    struct = parse_nbt(open(options.filename, "rb"),
                       gzipped=not options.no_gzip)

    edit_file = tempfile.NamedTemporaryFile(delete=False,
                                            suffix=".yml",
                                            mode="w")
    edit_file.write(dump_yaml(struct))
    edit_file.close()
    edit_filename = edit_file.name
    editor.edit(edit_filename)

    edit_file = open(edit_filename, "rb")
    new_struct = parse_yaml(edit_file)
    edit_file.close()
    os.remove(edit_filename)

    if new_struct == struct:
        sys.stderr.write("No changes made\n")
        sys.exit()

    save_counter = 0
    while True:
        if save_counter == 0:
            savefile = os.extsep.join([options.filename, "saved"])
        else:
            savefile = os.extsep.join(
                [options.filename,
                 str(save_counter), "saved"])
        if not os.path.exists(savefile):
            break
        save_counter += 1

    shutil.move(options.filename, savefile)
    sys.stderr.write("Saving old file as %s\n" % savefile)
    write_file = open(options.filename, "wb")
    sys.stderr.write("Writing %s\n" % options.filename)
    dump_nbt(new_struct, write_file, gzipped=not options.no_gzip)
    write_file.close()
示例#11
0
    def _parseInput(self, title=None, content=None, tags=None, notebook=None, resources=None, note=None):
        result = {
            "title": title,
            "content": content,
            "tags": tags,
            "notebook": notebook,
            "resources": resources if resources else []
        }
        result = tools.strip(result)

        # if get note without params
        if note and title is None and content is None and tags is None and notebook is None:
            content = config.EDITOR_OPEN

        if title is None and note:
            result['title'] = note.title

        if content:
            if content == config.EDITOR_OPEN:
                logging.debug("launch system editor")
                if note:
                    self.getEvernote().loadNoteContent(note)
                    content = editor.edit(note.content)
                else:
                    content = editor.edit()

            elif isinstance(content, str) and os.path.isfile(content):
                logging.debug("Load content from the file")
                content = open(content, "r").read()

            logging.debug("Convert content")
            content = editor.textToENML(content)

            result['content'] = content

        if tags:
            result['tags'] = tools.strip(tags.split(','))

        if notebook:
            notepadGuid = Notebooks().getNoteGUID(notebook)
            if notepadGuid is None:
                newNotepad = Notebooks().create(notebook)
                notepadGuid = newNotepad.guid
            
            result['notebook'] = notepadGuid
            logging.debug("Search notebook")
            
        return result
示例#12
0
文件: pack.py 项目: neufeldtech/st2
    def run(self, args, **kwargs):
        schema = self.app.client.managers['ConfigSchema'].get_by_ref_or_id(args.name, **kwargs)

        if not schema:
            raise resource.ResourceNotFoundError("%s doesn't have config schema defined" %
                                                 self.resource.get_display_name())

        config = interactive.InteractiveForm(schema.attributes).initiate_dialog()

        message = '---\nDo you want to preview the config in an editor before saving?'
        description = 'Secrets would be shown in plain text.'
        preview_dialog = interactive.Question(message, {'default': 'y', 'description': description})
        if preview_dialog.read() == 'y':
            contents = yaml.safe_dump(config, indent=4, default_flow_style=False)
            modified = editor.edit(contents=contents)
            config = yaml.safe_load(modified)

        message = '---\nDo you want me to save it?'
        save_dialog = interactive.Question(message, {'default': 'y'})
        if save_dialog.read() == 'n':
            raise OperationFailureException('Interrupted')

        result = self.app.client.managers['Config'].update(Config(pack=args.name, values=config))

        return result
示例#13
0
文件: pack.py 项目: Plexxi/st2
    def run(self, args, **kwargs):
        schema = self.app.client.managers["ConfigSchema"].get_by_ref_or_id(args.name, **kwargs)

        if not schema:
            msg = "%s \"%s\" doesn't exist or doesn't have config schema defined."
            raise resource.ResourceNotFoundError(msg % (self.resource.get_display_name(), args.name))

        config = interactive.InteractiveForm(schema.attributes).initiate_dialog()

        message = "---\nDo you want to preview the config in an editor before saving?"
        description = "Secrets would be shown in plain text."
        preview_dialog = interactive.Question(message, {"default": "y", "description": description})
        if preview_dialog.read() == "y":
            try:
                contents = yaml.safe_dump(config, indent=4, default_flow_style=False)
                modified = editor.edit(contents=contents)
                config = yaml.safe_load(modified)
            except editor.EditorError as e:
                print(str(e))

        message = "---\nDo you want me to save it?"
        save_dialog = interactive.Question(message, {"default": "y"})
        if save_dialog.read() == "n":
            raise OperationFailureException("Interrupted")

        result = self.app.client.managers["Config"].update(Config(pack=args.name, values=config))

        return result
示例#14
0
def edit(dataset_id):
    """Edit dataset metadata."""
    edit_dataset(
        dataset_id, lambda dataset: editor.edit(
            contents=bytes(yaml.safe_dump(dataset.editable), encoding='utf-8')
        )
    )
示例#15
0
文件: setup.py 项目: yxw027/where
def edit_config(rundate, pipeline, *args, **kwargs):
    """Update the configuration of a Where analysis

    """
    cfg_path = _config_path(rundate, pipeline, *args, **kwargs)
    ts_before = cfg_path.stat().st_mtime

    # Open config file in an editor
    editor.edit(str(cfg_path))

    if cfg_path.stat().st_mtime != ts_before:
        # Add timestamp and edited note
        add_timestamp(rundate, pipeline, "last update", **kwargs)

        # Add new dependent sections from manual edit
        add_sections(rundate, pipeline, *args, **kwargs)
示例#16
0
def new_entry(s):
    pristine = {
        'title': '',
        'username': '',
        'password': '',
        'url': '',
        'notes': ''
    }
    while True:
        new = editor.edit(
            contents=json.dumps(pristine, sort_keys=True, indent=2))
        print(new)
        confirm = input('save changes? y/n/redo:')
        if confirm == 'y':
            try:
                new_entry = json.loads(new)
                s.add_entry(new_entry)
                s.write()
                print('Entry saved.')
            except json.JSONDecodeError:
                response = input(
                    'Entry is not valid json.  Keep editing? (y/n):')
                if response == 'y':
                    continue
                else:
                    print('aborting..')
                    break
            return
        elif confirm == 'n':
            return
        elif confirm == 'redo':
            continue
示例#17
0
文件: pack.py 项目: LindsayHill/st2
    def run(self, args, **kwargs):
        schema = self.app.client.managers['ConfigSchema'].get_by_ref_or_id(args.name, **kwargs)

        if not schema:
            raise resource.ResourceNotFoundError("%s doesn't have config schema defined" %
                                                 self.resource.get_display_name())

        config = interactive.InteractiveForm(schema.attributes).initiate_dialog()

        message = '---\nDo you want to preview the config in an editor before saving?'
        description = 'Secrets would be shown in plain text.'
        preview_dialog = interactive.Question(message, {'default': 'y', 'description': description})
        if preview_dialog.read() == 'y':
            try:
                contents = yaml.safe_dump(config, indent=4, default_flow_style=False)
                modified = editor.edit(contents=contents)
                config = yaml.safe_load(modified)
            except editor.EditorError as e:
                print(str(e))

        message = '---\nDo you want me to save it?'
        save_dialog = interactive.Question(message, {'default': 'y'})
        if save_dialog.read() == 'n':
            raise OperationFailureException('Interrupted')

        result = self.app.client.managers['Config'].update(Config(pack=args.name, values=config))

        return result
示例#18
0
def _edit(config: dict):
    msg = show_tree(config["tree"], show_done=True).encode("utf-8")
    result = editor.edit(contents=msg).decode("utf-8")
    config["tree"] = read_tree(result)
    __sort(config)
    _show(config, show_done=True)
    __save(config)
示例#19
0
    def run(self, args, **kwargs):
        schema = self.app.client.managers["ConfigSchema"].get_by_ref_or_id(
            args.name, **kwargs
        )

        if not schema:
            msg = "%s \"%s\" doesn't exist or doesn't have a config schema defined."
            raise resource.ResourceNotFoundError(
                msg % (self.resource.get_display_name(), args.name)
            )

        config = interactive.InteractiveForm(schema.attributes).initiate_dialog()

        message = "---\nDo you want to preview the config in an editor before saving?"
        description = "Secrets will be shown in plain text."
        preview_dialog = interactive.Question(
            message, {"default": "y", "description": description}
        )
        if preview_dialog.read() == "y":
            try:
                contents = yaml.safe_dump(config, indent=4, default_flow_style=False)
                modified = editor.edit(contents=contents)
                config = yaml.safe_load(modified)
            except editor.EditorError as e:
                print(six.text_type(e))

        message = "---\nDo you want me to save it?"
        save_dialog = interactive.Question(message, {"default": "y"})
        if save_dialog.read() == "n":
            raise OperationFailureException("Interrupted")

        config_item = Config(pack=args.name, values=config)
        result = self.app.client.managers["Config"].update(config_item, **kwargs)

        return result
示例#20
0
文件: io.py 项目: eugene-eeo/takeit
def get_choices(index):
    index = OrderedDict(index)
    contents = to_b(generate_editor_contents(index))
    output = editor.edit(contents=contents)
    for item in parse_options(to_s(output)):
        if item not in index:
            continue
        yield item, index[item]
示例#21
0
def exception_handler(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
    if crash_log:
        text = editor.edit(filename=os.path.join(log_path(), "log.txt"))
示例#22
0
def modify(number):
    number = int(number)
    reqlist = p.get_req()
    if number > len(reqlist):
        print('Wrong ID number')
    else:
        strreq = editor.edit(contents=reqlist[number - 1].__str__().encode())
        request_line, headers = parse_http(strreq.decode())
        p.ownmodify(request_line, headers)
示例#23
0
 def modify(self, req, req_body):
     str = "{} {} {}\r\n{}\n\r{}\r\n".format(req.command, req.path,
                                             req.request_version,
                                             req.headers, req_body)
     strreq = editor.edit(contents=str.encode())
     request_line, headers_alone = strreq.decode().split('\r\n', 1)
     message = email.message_from_string(headers_alone)
     headers = dict(message.items())
     return request_line, headers
示例#24
0
文件: cli.py 项目: zha0/chepy
def cli_edit_state(fire: object, args: list):
    """Edit the current state

    Args:
        args (object): Cli args
    """
    current_index = fire._current_index
    hold = editor.edit(contents=str(fire.states[current_index])).decode()
    args[current_index] = hold
示例#25
0
 def open(self, **kwargs):
     ''' Open a document for viewing. '''
     key = _sanitize_key(kwargs['key'])
     doc = self.manager.get_doc(key)
     doc.access()
     if kwargs['bib']:
         editor.edit(doc.paths.bib_path)
     elif kwargs['tag']:
         try:
             editor.edit(doc.paths.tag_path)
         # FileNotFoundError is thrown if file doesn't exist and isn't
         # created during the editing process. Just ignore this.
         except FileNotFoundError:
             pass
     else:
         cmd = 'nohup xdg-open {} >/dev/null 2>&1 &'.format(
             doc.paths.pdf_path)
         subprocess.run(cmd, shell=True)
示例#26
0
def copy_prev(day: date):
    """
    This function will allow the option of copying the previous days "What I'm doing today" into the
    "What I did yesterdays" section of  that days notes
    """
    previous_days_note = get_note_name(last_weekday(day))
    note = get_note_name(day)
    date_of_note = "Date: " + day.strftime("%m/%d/%Y") + " \n"
    beginning_format = str(STANDUP_TEMPLATE_STRING.splitlines()[0]) + '\n'
    end_format = '\n'.join(STANDUP_TEMPLATE_STRING.splitlines()[2:])
    copy_text = False
    lines_to_append = []
    # If the previous days notes exists
    if os.path.exists(previous_days_note):
        result = verify_input(
            "Found yesterdays notes, would you like to insert applicable information into your "
            "notes y/n: ")
        # If the user wants to copy previous days notes
        if result:
            # Copy's applicable information from previous days notes
            lines_to_append = get_text(previous_days_note, 't')
            # If the note that wants to be edited already exists
            # It will add "lines_to_append" to "What I did yesterdays" section of notes
            if os.path.exists(note):
                with open(note) as f:
                    data = f.readlines()
                data[1] = data[1] + "".join(lines_to_append)
                with open(note, 'w') as file:
                    file.writelines(data)
            else:
                editor.edit(note,
                            contents=date_of_note + beginning_format +
                            "".join(lines_to_append) + end_format)
                return 0
        if not result:
            response = input(
                "Yesterdays notes will not be copied. Press enter to continue")
    # If previous days notes doesn't exist
    else:
        response = input(
            "Yesterdays notes were not found, nothing will be copied. Press enter to continue: "
        )
    edit_note(day)
示例#27
0
    def fire_editor(self):
        init_content = '#-------------------\n# %s\n#----------------\n### Initial Content\n%s\n### Notes here' % (
            self.LOG_DIR, '\n'.join(self.string_data))

        result = editor.edit(contents=init_content)

        print '[InteractiveLogger] Write file : ', self.LOG_DIR + "/README.md"
        text_file = open(self.LOG_DIR + "/README.md", "a")
        text_file.write(result)
        text_file.close()
示例#28
0
 def edit(self):
     """Open vim to edit config file"""
     cluster_id = config.get_cur_cluster_id()
     path_of_fb = config.get_path_of_fb(cluster_id)
     # path_of_cli = config.get_path_of_cli(cluster_id)
     # if not os.path.exists(path_of_cli['cluster_path']):
     #     logger.debug(
     #         "FileNotExisted: '{}'".format(
     #             path_of_cli['cluster_path']))
     #     os.system('mkdir -p {}'.format(path_of_cli['cluster_path']))
     #     logger.debug("CreateDir: '{}'".format(path_of_cli['cluster_path']))
     # if not os.path.exists(path_of_cli['conf_path']):
     #     logger.debug(
     #         "FileNotExisted: '{}'".format(
     #             path_of_cli['conf_path']))
     #     shutil.copytree(path_of_fb['conf_path'], path_of_cli['conf_path'])
     #     logger.debug("CopyTree: '{}'".format(path_of_cli['cluster_path']))
     editor.edit(path_of_fb['redis_properties'], syntax='sh')
     cluster_util.rsync_fb_conf()
示例#29
0
def editor_preserve_comments(default_text):
    """
    Open pyeditor and preserves comments. Does some encoding stuff.
    """
    if not isinstance(default_text, bytes):
        default_text = default_text.encode("utf-8")
    edited_text = editor.edit(contents=default_text)
    if not isinstance(edited_text, str):
        edited_text = edited_text.decode("utf-8")
    return edited_text
示例#30
0
def __edit_settings(path: Path):
    """
    :param path: the file path to edit
    :return: A helper function to edit_settings()
    """
    if IS_WINDOWS:
        subprocess.call(['start', 'notepad', str(path)])
    elif IS_MAC:
        subprocess.call(['open', '-a', 'TextEdit', str(path)])
    else:
        try:
            import editor
            editor.edit(str(path))
        except Exception as e:
            print('There was an error with the editor library:\n')
            print(str(e))
            print('Using nano as the editor.')
            time.sleep(3)
            subprocess.call(['sudo', 'nano', str(path)])
示例#31
0
def editor_ignore_comments(default_text):
    """
    Open pyeditor but ignore lines starting with "#" when text is returned.

    :param default_text:
    :return:
    """
    edited_text = editor.edit(contents=default_text)
    lines = edited_text.split('\n')
    return "\n".join([line for line in lines if not line.startswith("#")])
示例#32
0
def parse_and_execute_note():
    note_title = None
    keywords = None
    category = None

    parser = optparse.OptionParser()
    parser.add_option('-t',
                      '--title',
                      dest='note_title',
                      help='Enter note title')
    parser.add_option(
        '-k',
        '--keywords',
        dest='keywords',
        help='Enter keywords (separated by comma with no spaces in between')
    parser.add_option('-c',
                      '--category',
                      dest='category',
                      help='Enter category (optional)')

    (options, args) = parser.parse_args()

    if not options.note_title:
        note_title = input("Enter a title for your note : ")
        if note_title == "":
            note_title = None
    else:
        note_title = options.note_title

    if not options.keywords:
        keywords = input("Enter keywords for your note (optional) : ")
        if keywords == "":
            keywords = None
    else:
        keywords = options.keywords

    if not options.category:
        category = input("Enter a category for note (optional) : ")
        if category == "":
            category = None
    else:
        category = options.category

    note_body = editor.edit(
        contents=str.encode("# Enter your content here..."))
    note_body = note_body.decode()
    if note_body == "":
        note_body = None

    obj = Note()
    obj.set_params(note_title, note_body, keywords, category)
    status = obj.save_note()

    if status == 1:
        logger.success("Scribble executed successfully!")
示例#33
0
def main():
    logger = logging.getLogger()
    logger.setLevel(level=logging.INFO)
    argv = sys.argv[1:]
    parameters = parse_argv(argv)
    if parameters['init']:
        logging.info("Initializing token_roi")
        initialize_configuration()
        sys.exit(0)
    try:
        os.chdir(config_dir())
    except FileNotFoundError:
        logging.error("Can't switch cwd to ~/.local/token. Did you "
                      "initialized token_roi?")
        exit(-1)
    if parameters['debug']:
        logger.setLevel(level=logging.DEBUG)
        logging.debug(parameters)
    elif parameters['upload']:
        dbx = dropbox_start()
        dropbox_push_file(dbx, TOKEN_CONF)
        dropbox_push_file(dbx, WALLETS_CONF)
    elif parameters['restore']:
        dbx = dropbox_start()
        dropbox_restore_file(dbx, TOKEN_CONF,
                             rev=select_revision(dbx, TOKEN_CONF))
        dropbox_restore_file(dbx, WALLETS_CONF,
                             rev=select_revision(dbx, WALLETS_CONF))
    elif parameters['edit']:
        editor.edit(filename=token_config_path(), use_tty=True)
        editor.edit(filename=wallet_config_path(), use_tty=True)
    else:
        sum_eth = 0
        token_cash, txt = handle_tokens()
        sum_eth += sum(token_cash)
        eth_balance = '0'
        if parameters['all']:
            sum_eth += sum(handle_wallets())
            eth_balance = "eth sum: {0:.2f}".format(sum_eth)
            print(eth_balance)
        if parameters['email']:
            send_stats(''.join(txt) + eth_balance)
示例#34
0
def main():
    args = sys.argv[1:]
    if len(args) == 1:
        if args[0] == 'p' or args[0] == 'pull':
            git_pull()
        elif args[0] == 'l' or args[0] == 'list':
            subprocess.check_call(['ls', git_dir])
        elif args[0] == 'b' or args[0] == 'backup':
            git_push()
        else:
            maybe_file = os.path.join(git_dir, args[0])
            if os.path.isfile(maybe_file):
                with open(maybe_file, 'r') as f:
                    print(f.read())
    elif len(args) >= 2 and args[0] == 'g' or args[0] == 'grep':
        os.system(f'grep -- {" ".join(args[1:])} {os.path.join(git_dir, "*")}')
    elif len(args) == 2:
        if args[0] == 'init':
            init(args[1])
        elif args[0] == 'e' or args[0] == 'edit':
            # edit file in vim
            filename = os.path.join(git_dir, args[1])
            editor.edit(filename)
            git_push()
        elif args[0] == 'rm':
            filename = os.path.join(git_dir, args[1])
            if not os.path.isfile(filename):
                print(f'No Note with name {argv[1]}')
            else:
                os.remove(filename)
                git_push()
    # doesnt write if note contains only 1 world. should be fine
    elif len(args) > 2:
        filename = os.path.join(git_dir, args[0])
        content = ' '.join(args[1:])
        if os.path.isfile(filename):
            with open(filename, 'a') as f:
                f.write('\n\n' + content)
        else:
            with open(filename, 'w') as f:
                f.write(content)
        git_push()
示例#35
0
    def process_input(self, pressed):
        if pressed == key.CTRL_C:
            raise KeyboardInterrupt()

        if pressed in (key.CR, key.LF, key.ENTER):
            data = editor.edit(contents=self.question.default or '')
            raise errors.EndOfInput(data.decode('utf-8'))

        raise errors.ValidationError('You have pressed unknown key! '
                                     'Press <enter> to open editor or '
                                     'CTRL+C to exit.')
示例#36
0
    def process_input(self, pressed):
        if pressed == key.CTRL_C:
            raise KeyboardInterrupt()

        if pressed in (key.CR, key.LF, key.ENTER):
            data = editor.edit(contents=self.question.default or "")
            raise errors.EndOfInput(data.decode("utf-8"))

        raise errors.ValidationError("You have pressed unknown key! "
                                     "Press <enter> to open editor or "
                                     "CTRL+C to exit.")
示例#37
0
文件: __init__.py 项目: copton/avt
 def edit(self, word):
     return editor.edit(word)
示例#38
0
 def _edit(self, file):
     editor.edit(file)
示例#39
0
 def edit(self):
     changed = json.loads(editor.edit(contents=json.dumps(self, indent=4)))
     return Template(changed)
示例#40
0
import sys
import editor

cont = editor.edit(contents='ABC!',
                   use_tty='use_tty' in sys.argv)
sys.stdout.write(cont)