コード例 #1
0
ファイル: ingest.py プロジェクト: gnebbia/travis_tests
def ingest(args: Dict[str, str], config: Dict[str, str]):
    """
    Import an entire kb knowledge base.

    Arguments:
    args:           - a dictionary containing the following fields:
                      file -> a string representing the path to the archive
                        to be imported
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB           - the main path of KB
    """
    if args["file"].endswith(".tar.gz"):
        answer = input("You are about to import a whole knowledge base "
                       "are you sure you want to wipe your previous "
                       " kb data ? [YES/NO]")
        if answer.lower() == "yes":
            print("Previous kb knowledge base data wiped...")
            try:
                fs.remove_directory(config["PATH_KB"])
            except FileNotFoundError:
                pass
            tar = tarfile.open(args["file"], "r:gz")
            tar.extractall(Path.home())
            tar.close()
            print("kb archive {fname} imported".format(fname=args["file"]))
    else:
        print("Please provide a file exported through kb with kb.tar.gz extension")
コード例 #2
0
ファイル: delete.py プロジェクト: gnebbia/travis_tests
def delete_by_id(id: int, config: Dict[str, str]):
    """
    Edit the content of an artifact by id.

    Arguments:
    id:             - the ID (the one you see with kb list)
                      associated to the artifact to delete
    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
    """
    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:
        return

    db.delete_artifact_by_id(conn, artifact_id)

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

    try:
        Path(category_path, artifact.title).unlink()
    except FileNotFoundError:
        pass

    if fs.count_files(category_path) == 0:
        fs.remove_directory(category_path)

    print("Artifact {category}/{title} removed!".format(
        category=artifact.category, title=artifact.title))
コード例 #3
0
def erase(args: Dict[str, str], config: Dict[str, str]):
    """
    Erase the entire kb knowledge base (or only the database).

    Arguments:
    args:           - a dictionary containing the following fields:
                      db -> a boolean, if true, only the database
                        will be deleted
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB           - the main path of KB
                      PATH_KB_DB        - the database path of KB
                      PATH_KB_HIST      - the history menu path of KB
    """
    if args["db"]:
        answer = input(
            "Are you sure you want to erase the kb database ? [YES/NO]")
        if answer.lower() == "yes":
            try:
                fs.remove_file(config["PATH_KB_DB"])
                fs.remove_file(config["PATH_KB_HIST"])
                print("kb database deleted successfully!")
            except FileNotFoundError:
                pass
    else:
        answer = input(
            "Are you sure you want to erase the whole kb knowledge base ? [YES/NO]"
        )
        if answer.lower() == "yes":
            try:
                fs.remove_directory(config["PATH_KB"])
                print("kb knowledge base deleted successfully!")
            except FileNotFoundError:
                pass
コード例 #4
0
def delete_base(args: Dict[str, str], config: Dict[str, str]):
    """
    Implementation of delete a knowledge bases

    Arguments:
    args        -   contains the name of the knowledge base to delete
    config      -   the configuration dictionary that must contain
                    at least the following key:
                    PATH_KB_INITIAL_BASES, the path to where the .toml file containing kb information is stored
    """

    initial_bases_path = config["PATH_KB_INITIAL_BASES"]
    name = args.get("name", "")

    # Get bases.tooml file
    data = toml.load(initial_bases_path)
    current = data['current']

    if current == name:
        return -1  # Cannot delete current knowledgebase

    if not does_base_exist(name, config):
        return -2  # Cannot delete a knowledgebase if it doesn't exist

    base_path = str(Path(config["PATH_BASE"], name))

    data['bases'] = remove_base_from_list(name, data)

    write_base_list(initial_bases_path, data)

    # remove the directory with the artifacts etc in...
    fs.remove_directory(base_path)
    return 0
コード例 #5
0
def erase_kb(erase_what, config: Dict[str, str]):
    """
    Erase the entire kb knowledge base (or only the database).

    Arguments:
    eraseOnlyDB:    - a string containing the following fields:
                      if "db", only the database will be deleted
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB           - the main path of KB
                      PATH_KB_DB        - the database path of KB
                      PATH_KB_HIST      - the history menu path of KB
    """

    if erase_what == "db":
        try:
            fs.remove_file(config["PATH_KB_DB"])
            fs.remove_file(config["PATH_KB_HIST"])
            response = -200
        except FileNotFoundError:
            response = -404
    else:
        try:
            fs.remove_directory(config["PATH_KB"])
            response = -200
        except FileNotFoundError:
            response = -404
    return (response)
コード例 #6
0
ファイル: sync.py プロジェクト: gnebbia/kb
def sync(args: Dict[str, str], config: Dict[str, str]):
    """
    Synchronize the knowledge base with a remote repository.

    Arguments:
    args:           - a dictionary containing the following fields:
                      file -> a string representing the wished output
                        filename
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB           - the main path of KB
    """

    operation = args["operation"]

    if operation == "init":
        if is_local_git_repo_initialized(config["PATH_KB_GIT"]):
            print("Warning: a git repository already exists...")
            cancel_repo = input(
                "Do you want to re-init your repository ? [Type YES in that case] ")
            if cancel_repo == "YES":
                fs.remove_directory(config["PATH_KB_GIT"])
                git_init(config["PATH_KB"])
            else:
                print("Maybe you wanted to type \"kb sync push\" or \"kb sync pull\"!")
        else:
            git_init(config["PATH_KB"])
    elif operation == "push":
        if not is_local_git_repo_initialized(config["PATH_KB_GIT"]):
            print("Warning: You did not initialize any repository...")
            print("try: kb sync init")
            return
        git_push(config["PATH_KB"])
    elif operation == "pull":
        if not is_local_git_repo_initialized(config["PATH_KB_GIT"]):
            print("Warning: no local git repository has been instantiated!")
            cancel_repo = input(
                "Do you want to remove possible local kb files and sync from a remote repository? [Type YES in that case] ")
            if cancel_repo == "YES":
                try:
                    fs.remove_directory(config["PATH_KB"])
                except BaseException:
                    pass
                git_clone(config["PATH_KB"])
        else:
            git_pull(config["PATH_KB_GIT"])
    elif operation == "info":
        if not is_local_git_repo_initialized(config["PATH_KB_GIT"]):
            print("No local git repository has been instantiated!")
            return
        show_info(config["PATH_KB"])
    else:
        print("Error: No valid operation has been specified")
        return
コード例 #7
0
def delete(args: Dict[str, str], config: Dict[str, str]):
    """
    Delete a list of artifacts from the kb knowledge base.

    Arguments:
    args:           - a dictionary containing the following fields:
                      id -> a list of IDs (the ones you see with kb list)
                        associated to the artifacts we want to delete
                      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
    """
    initializer.init(config)

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

    if args["id"]:
        for i in args["id"]:
            artifact_id = history.get_artifact_id(config["PATH_KB_HIST"], i)
            artifact = db.get_artifact_by_id(conn, artifact_id)

            if not artifact:
                continue

            db.delete_artifact_by_id(conn, artifact_id)

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

            Path(category_path, artifact.title).unlink()
            if fs.count_files(category_path) == 0:
                fs.remove_directory(category_path)

            print("Artifact {category}/{title} removed!".format(
                category=artifact.category, title=artifact.title))
        sys.exit(0)

    # else if a title is specified
    elif args["title"]:
        artifacts = db.get_artifacts_by_filter(conn, title=args["title"],
                                               category=args["category"],
                                               is_strict=True)
        if len(artifacts) == 1:
            artifact = artifacts.pop()
            db.delete_artifact_by_id(conn, artifact.id)
            print("Artifact {}/{} removed!".format(artifact.category, artifact.title))
        else:
            print(
                "There is more than one artifact with that title, please specify a category")
コード例 #8
0
ファイル: ingest.py プロジェクト: timothyb0912/kb
def ingest_kb(args: Dict[str, str], config: Dict[str, str]):
    """
    Import an entire kb knowledge base.

    Arguments:
    args:           - a dictionary containing the following fields:
                      file -> a string representing the path to the archive
                        to be imported
    config:         - a configuration dictionary containing at least
                      the following keys:
                      PATH_KB           - the main path of KB
    """

    tar = tarfile.open(args["file"], "r:gz")
    t = tar.getmembers()[0]  # GET TAR METADATA STORED IN PAX HEADERS
    tar.extractall(Path(config["PATH_KB"]))
    tar.close()
    """
    Version 1 (pre 0.1.6 multi kb version) export files don't contain any metadata. 
    This means that the original export files assume that the destination is ".kb"
    
    This will not work in post 0.1.6. Therefore, they need to be moved to fit in with 
    this schema.
    
    For 0.1.6 and above exports, a simple untar will work.

    NOTE THAT THE EXPORTS ARE NOT BACKWARDLY COMPATIBLE.

    """

    if t.pax_headers.get('kb-export-format-version', '1') == '1':
        # Version 1 import file detected
        kb_path_base = kb_path_base = config["PATH_KB"]

        # Move data, templates and db into newly created directory (and optionally recent.hist)
        fs.move_file(str(Path(kb_path_base, '.kb', 'data')),
                     str(Path(kb_path_base, 'data')))
        fs.move_file(str(Path(kb_path_base, '.kb', 'templates')),
                     str(Path(kb_path_base, 'templates')))
        fs.move_file(str(Path(kb_path_base, '.kb', 'kb.db')),
                     str(Path(kb_path_base, 'kb.db')))
        fs.move_file(str(Path(kb_path_base, '.kb', 'recent.hist')),
                     str(Path(kb_path_base, 'recent.hist')))
        fs.remove_directory(str(Path(kb_path_base, '.kb')))

    else:
        # Version 2 import file detected
        pass

    return -200