Ejemplo n.º 1
0
def get_valid_python_script():

    while True:
        # do (get file)
        filepath = input("enter the filepath of the python script you want to call through git\n(e.g. C:/Scripts/destroy_repo.py): ")
        # while (file is not real python script)
        if (pathlib_Path(filepath).suffix != '.py' and not pathlib_Path(filepath).exists):
            continue
        else:
            break

    return filepath
Ejemplo n.º 2
0
def rtap(rel_path: str) -> str:
    """Convert relative path to absolute path

    Args:
        rel_path (str): relative path to be converted

    Returns:
        str: absolute path to file
    """
    assert isinstance(rel_path, str), TypeError("rel_path must be a str")
    current_dir = pathlib_Path(__file__).parent
    rel_path = pathlib_Path(rel_path)
    abs_path = current_dir / rel_path

    return abs_path.resolve()
Ejemplo n.º 3
0
def run_ngrok():
    ngrok_config = pathlib_Path(".config/ngrok.yml")
    if ngrok_config.exists():
        pid = check_process("ngrok")
        for p in pid:
            kill_process(p, signal.SIGKILL)
        # Continue
        run_command('./ngrok tcp -config=.config/ngrok.yml 443 > /dev/null 2>&1 &')
        while True:
            tcp = sys_url('curl -s -N http://127.0.0.1:4040/status | grep -o "tcp://[0-9]*.tcp.ngrok.io:[0-9]*"').read()
            if re.match("tcp://[0-9]*.tcp.ngrok.io:[0-9]*", tcp) != None:
                print("\n{0}Ngrok TCP: {1}{2}".format(GREEN, DEFAULT, tcp))
                break
    else:
        while True:
            token = entry_token(title="SET NGROK AUTHTOKEN", text="Register at https://ngrok.com", width=450, height=140)        
            if token is None:
                continue
            else:
                ngrok_config.touch(mode=0o777, exist_ok=True)
                ngrok_config = open('.config/ngrok.yml','w')
                ngrok_config.write("authtoken: " + token)
                ngrok_config.close()        
                run_ngrok() 
                break
Ejemplo n.º 4
0
def run():
    # get args
    parser = argparse.ArgumentParser()
    parser.add_argument('--updater_exe', nargs=1, required=True, type=lambda x: x if x.endswith(".exe") else err())
    parser.add_argument('--stage2_exe', nargs=1, required=True, type=lambda x: x if x.endswith(".exe") else err())
    parser.add_argument('--repo_dir', nargs=1, required=True)
    args = parser.parse_args()
    #
    preload_repo(args.updater_exe[0], args.stage2_exe[0], pathlib_Path(args.repo_dir[0]))
Ejemplo n.º 5
0
    def __init__(
        self,
        output_folder='output/',
        output_files_prefix='Collect',
        log_lvl=1,
    ):
        # Name of the folder used to store every file : logs and gathered tweets
        # NOTE This folder will be created inside the current active directory
        self.__sub_path__ = pathlib_Path(output_folder)
        # If subpath doesn't exist, mkdir
        # This folder will be used to store every files generated (log, txt, json)
        self.__sub_path__.mkdir(parents=True, exist_ok=True)
        # Prefix used for files name generation
        self.__output_files_prefix__ = output_files_prefix

        #https://docs.python.org/3.6/library/logging.html#logging-levels
        self.__log_lvl__ = [0, 10, 20, 30, 40, 50][log_lvl]
        # Log_lvl 0 from command-line mean "NONE", and not "NOTSET"
        # In case of "NONE", we raise a flag that will allow to skip all log events
        self.__noLogs__ = (self.__log_lvl__ == 0)

        if (not self.__noLogs__):

            self.__logger__ = logging.getLogger(__name__)
            self.__logger__.setLevel(self.__log_lvl__)

            self.__formatter__ = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

            # self.__FileHandler__ = logging.FileHandler(self.generate_file_name()+'.log')
            # https://docs.python.org/3.6/library/logging.handlers.html#rotatingfilehandler
            self.__FileHandler__ = RotatingFileHandler(
                self.generate_file_name() + '.log',
                mode='a',
                maxBytes=2 * 1024 * 1024,  # 2Mb max size for log files
                backupCount=5,
                encoding="utf-8",
                delay=0)

            self.__FileHandler__.setLevel(self.__log_lvl__)
            self.__FileHandler__.setFormatter(self.__formatter__)

            self.__ConsoleHandler__ = logging.StreamHandler()
            self.__ConsoleHandler__.setLevel(self.__log_lvl__)
            self.__ConsoleHandler__.setFormatter(self.__formatter__)

            self.__logger__.addHandler(self.__FileHandler__)
            self.__logger__.addHandler(self.__ConsoleHandler__)
 def __init__(
     self,
     output_folder='output/',
     output_files_prefix='Collect',
     #files_max_size = 2*1024*1024, # 2Mb
     #files_max_number = 5 # Number of different files before rollover
 ):
     # Name of the folder used to store every file : logs and gathered tweets
     # NOTE This folder will be created inside the current active directory
     self.__subPath__ = pathlib_Path(output_folder)
     # If subpath doesn't exist, mkdir
     # This folder will be used to store every files generated (log, txt, json)
     self.__subPath__.mkdir(parents=True, exist_ok=True)
     # Prefix used for files name generation
     self.__outputFilesPrefix__ = output_files_prefix
     self.__outputFilesBase__ = self.generate_file_name()
Ejemplo n.º 7
0
def find_files(root_dir: pathlib_Path,
               include_subdirs: bool = True) -> Coroutine[str, None, str]:
    """Find files in the given directory.

    Args:
        root_dir (pathlib_Path): The directory to look for files
        include_subdirs (bool): Whether to include subdirectories in the search

    Returns:
        Coroutine[str]: [description]
    """
    root_dir = pathlib_Path(root_dir)

    def find_toplevel_objects(
            root_dir: pathlib_Path) -> Coroutine[str, None, str]:
        for child in root_dir.iterdir():
            yield child.resolve()

    for obj in find_toplevel_objects(root_dir):
        if include_subdirs is True and obj.is_dir():
            yield obj
            yield from find_toplevel_objects(obj)
        else:  # don't yield obj twice
            yield obj
Ejemplo n.º 8
0
    # Files management
    from time import strftime
    from os import path as os_path
    from pathlib import Path as pathlib_Path

    # This python script directory -> where to look for config files etc
    #PROJECT_DIR = os_path.dirname(os_path.abspath(__file__))
    PROJECT_DIR = os_path.dirname(os_path.realpath(__file__))

    #------------------------------------------------
    # APP CONFIG
    # TODO: import those from json file
    #------------------------------------------------
    # Name of the folder used to store every file : logs and gathered tweets
    # NOTE This folder will be created inside the current active directory
    sub_path = pathlib_Path("output/")
    # JSON file containing CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
    #   Create an App to get them : https://apps.twitter.com/
    # Path is relative to this python script directory
    # If no path and just a name, must be in the same directory as this script
    twitter_oauth_path = 'oauth.json'
    # Prefix used for files name generation
    output_files_prefix = 'Collect'
    # Log Level Config - For now it is done with Command-Line (see later)

    # Tweek to look for the oauth file in the same directory as this python file
    # TODO There must be a better way !
    twitter_oauth_path = os_path.join(PROJECT_DIR, twitter_oauth_path)
    # If subpath doesn't exist, mkdir
    # This folder will be used to store every files generated (log, txt, json)
    sub_path.mkdir(parents=True, exist_ok=True)
Ejemplo n.º 9
0
## Copyright 2019 Dynatrace LLC
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
##     http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------
"""Filenames used by compose module tests
"""
from os.path import dirname as os_path_dirname
from pathlib import Path as pathlib_Path

CONFIG_SAMPLE_DIR = pathlib_Path(os_path_dirname(__file__)) / "config-samples"
COMPOSE_SMALL = CONFIG_SAMPLE_DIR / "compose-small.yaml"
COMPOSE_BIG = CONFIG_SAMPLE_DIR / "compose-big.yaml"
COMPOSE_CYCLE = CONFIG_SAMPLE_DIR / "compose-cycle.yaml"
COMPOSE_TRICKY = CONFIG_SAMPLE_DIR / "compose-tricky.yaml"

TEA_TASKS_DIR = pathlib_Path(os_path_dirname(__file__)) / "tea-tasks"
BOIL_WATER = TEA_TASKS_DIR / "boil_water.py"
POUR_WATER = TEA_TASKS_DIR / "pour_water.py"
PREP_INFUSER = TEA_TASKS_DIR / "prep_infuser.py"
STEEP_TEA = TEA_TASKS_DIR / "steep_tea.py"
Ejemplo n.º 10
0
 def __init__(self, repodir: str, repo: git.Repo):
     self.repodir = pathlib_Path(repodir)
     self.repo = repo