Example #1
0
def add_file_to_kb(conn, args: Dict[str, str], config: Dict[str, str],
                   fname: str) -> None:
    """
    Adds a file to the kb knowledge base.

    Arguments:
    conn        -   the connection to the database object
    args        -   the args dictionary passed to the add command,
                    it must contain at least the following keys:
                        title, category, tags, status, author
    config      -   the configuration dictionary that must contain
                    at least the following key:
                     PATH_KB_DATA, the path to where artifact are stored
    """
    title = args["title"] or fs.get_basename(fname)
    category = args["category"] or "default"

    category_path = Path(config["PATH_KB_DATA"], category)
    category_path.mkdir(parents=True, exist_ok=True)

    fs.copy_file(fname, Path(category_path, title))

    if not db.is_artifact_existing(conn, title, category):
        fs.copy_file(fname, Path(category_path, title))

    new_artifact = Artifact(id=None,
                            title=title,
                            category=category,
                            path=str(Path(category, title)),
                            tags=args["tags"],
                            status=args["status"],
                            author=args["author"])
    db.insert_artifact(conn, new_artifact)
Example #2
0
def test_copy_file():
    filename_src = Path("tests", "data", "sample_data")
    filename_dst = Path("tests", "data", "sample_data_dest")

    with open(filename_src, 'w') as f:
        f.write('sample data\n')
    assert os.path.exists(filename_src)

    fs.copy_file(filename_src, filename_dst)
    assert os.path.exists(filename_dst)
Example #3
0
File: view.py Project: gnebbia/kb
def view_by_name(title: str, category: str, config: Dict[str, str],
                 open_editor: bool, color_mode: bool):
    """
    View the content of an artifact by name, that is title/category

    Arguments:
    title:          - the title assigned to the artifact(s)
    category:       - the category assigned to the artifact(s)
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB_DB        - the database path of KB
                      PATH_KB_DATA      - the data directory of KB
                      PATH_KB_HIST      - the history menu path of KB
                      EDITOR            - the editor program to call
    open_editor     - a boolean, if True it will open the artifact as
                      a temporary copy in editor
    color_mode      - a boolean, if True the colors on screen will be
                      enabled when printed on stdout
    """
    conn = db.create_connection(config["PATH_KB_DB"])
    artifacts = db.get_artifacts_by_filter(conn,
                                           title=title,
                                           category=category,
                                           is_strict=True)
    if len(artifacts) == 1:
        artifact = artifacts.pop()
        category_path = Path(config["PATH_KB_DATA"], artifact.category)
        artifact_path = Path(category_path, artifact.title)

        if open_editor:
            tmpfname = fs.get_temp_filepath()
            fs.copy_file(artifact_path, tmpfname)

            shell_cmd = shlex.split(config["EDITOR"]) + [tmpfname]
            call(shell_cmd)
            fs.remove_file(tmpfname)
            sys.exit(0)

        # View File
        if fs.is_text_file(artifact_path):
            markers = get_template(artifact, config)
            viewer.view(artifact_path, markers, color=color_mode)
        else:
            opener.open_non_text_file(artifact_path)
    elif len(artifacts) > 1:
        print(
            "There is more than one artifact with that title, please specify a category"
        )
    else:
        print(
            "There is no artifact with that name, please specify a correct artifact name"
        )
Example #4
0
File: view.py Project: gnebbia/kb
def view_by_id(id: int, config: Dict[str, str], open_editor: bool,
               color_mode: bool):
    """
    View the content of an artifact by id.

    Arguments:
    id:             - the ID (the one you see with kb list)
                      associated to the artifact we want to edit
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB_DB        - the database path of KB
                      PATH_KB_DATA      - the data directory of KB
                      PATH_KB_HIST      - the history menu path of KB
                      EDITOR            - the editor program to call
    open_editor     - a boolean, if True it will open the artifact as
                      a temporary copy in editor
    color_mode      - a boolean, if True the colors on screen will be
                      enabled when printed on stdout
    """
    conn = db.create_connection(config["PATH_KB_DB"])
    artifact_id = history.get_artifact_id(config["PATH_KB_HIST"], id)

    artifact = db.get_artifact_by_id(conn, artifact_id)

    if not artifact:
        sys.exit(1)

    category_path = Path(config["PATH_KB_DATA"], artifact.category)
    artifact_path = Path(category_path, artifact.title)

    if open_editor:
        tmpfname = fs.get_temp_filepath()
        fs.copy_file(artifact_path, tmpfname)

        shell_cmd = shlex.split(config["EDITOR"]) + [tmpfname]
        call(shell_cmd)
        fs.remove_file(tmpfname)

        sys.exit(0)

    # View File
    if fs.is_text_file(artifact_path):
        markers = get_template(artifact, config)
        viewer.view(artifact_path, markers, color=color_mode)
    else:
        opener.open_non_text_file(artifact_path)
Example #5
0
def add(args: Dict[str, str], config: Dict[str, str]):
    """
    Add a new template to the templates available in kb.

    Arguments:
    args:           - a dictionary containing the following fields:
                      file -> the path to the template to include in kb templates
                      title -> the title to assign to the kb template added
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB_TEMPLATES         - the path to where the templates of KB
                                                  are stored
    """
    template_path = args["file"]
    if args["title"]:
        dest_path = str(Path(config["PATH_KB_TEMPLATES"]) / args["title"])
    else:
        dest_path = config["PATH_KB_TEMPLATES"]
    fs.copy_file(template_path, dest_path)
Example #6
0
File: add.py Project: kojibhy/kb
def add_file_to_kb(
        conn,
        args: Dict[str, str],
        config: Dict[str, str],
        fname: str
) -> None:
    """
    Adds a file to the kb knowledge base.

    Arguments:
    conn        -   the connection to the database object
    args        -   the args dictionary passed to the add command,
                    it must contain at least the following keys:
                        title, category, tags, status, author
    config      -   the configuration dictionary that must contain
                    at least the following key:
                    PATH_KB_DATA, the path to where artifact are stored
    fname       -   the path of the file to add to kb
    """
    title = args["title"] or fs.get_basename(fname)
    category = args["category"] or "default"
    template = args["template"] or "default"

    category_path = Path(config["PATH_KB_DATA"], category)
    category_path.mkdir(parents=True, exist_ok=True)

    try:
        fs.copy_file(fname, Path(category_path, title))
    except FileNotFoundError:
        print("Error: The specified file does not exist!".format(fname=fname))
        sys.exit(1)

    if not db.is_artifact_existing(conn, title, category):
        fs.copy_file(fname, Path(category_path, title))

    new_artifact = Artifact(
        id=None,
        title=title, category=category,
        path="{category}/{title}".format(category=category, title=title),
        tags=args["tags"],
        status=args["status"], author=args["author"], template=template)
    db.insert_artifact(conn, new_artifact)
Example #7
0
def view(args: Dict[str, str], config: Dict[str, str]):
    """
    View an artifact contained in the knowledge base of kb.

    Arguments:
    args:           - a dictionary containing the following fields:
                      id -> the IDs (the one you see with kb list)
                        associated to the artifact to view
                      title -> the title of the artifact to view
                      category -> the category of the artifact to view
                      editor -> a boolean, if True the file will
                        be opened in a text editor as a temporary file
                        hence the original will not be affected
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB_DB        - the database path of KB
                      PATH_KB_DATA      - the data directory of KB
                      PATH_KB_HIST      - the history menu path of KB
                      PATH_KB_MARKERS   - the file associated to the markers
                      EDITOR            - the editor program to call
    """
    # Check initialization
    initializer.init(config)

    conn = db.create_connection(config["PATH_KB_DB"])

    if args["id"]:
        artifact_id = history.get_artifact_id(
            config["PATH_KB_HIST"], args["id"])

        artifact = db.get_artifact_by_id(conn, artifact_id)

        if not artifact:
            sys.exit(1)

        category_path = Path(config["PATH_KB_DATA"], artifact.category)
        artifact_path = Path(category_path, artifact.title)

        if args["editor"]:
            with tempfile.NamedTemporaryFile() as tmpfname:
                fs.copy_file(artifact_path, tmpfname.name)
                call([config["EDITOR"], tmpfname.name])
            sys.exit(0)

        # View File
        if fs.is_text_file(artifact_path):
            markers = get_markers(config["PATH_KB_MARKERS"])
            color_mode = not args["no_color"]
            viewer.view(artifact_path, markers, color=color_mode)
        else:
            opener.open_non_text_file(artifact_path)

    elif args["title"]:
        artifact = db.get_uniq_artifact_by_filter(conn, title=args["title"],
                                                  category=args["category"],
                                                  is_strict=True)
        if artifact:
            category_path = Path(config["PATH_KB_DATA"], artifact.category)
            artifact_path = Path(category_path, artifact.title)

            content = ""
            if args["editor"]:
                call([config["EDITOR"], artifact_path])
                sys.exit(0)

            # View File
            if fs.is_text_file(artifact_path):
                markers = get_markers(config["PATH_KB_MARKERS"])
                color_mode = not args["no_color"]
                viewer.view(artifact_path, markers, color=color_mode)
            else:
                opener.open_non_text_file(artifact_path)
        else:
            print(
                "There is no artifact with that title, please specify a category")