How to use the publish.exceptions function in publish

To help you get started, we’ve selected a few publish examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github AuHau / ipfs-publish / tests / unit / test_publishing.py View on Github external
def test_publish_repo_bins_fails(self, mocker):
        mocker.patch.object(git.Repo, 'clone_from')
        mocker.patch.object(shutil, 'rmtree')

        ipfs_client_mock = mocker.Mock(spec=ipfshttpclient.Client)
        ipfs_client_mock.add.return_value = [{'Hash': 'some-hash'}]

        mocker.patch.object(ipfshttpclient, 'connect')
        ipfshttpclient.connect.return_value = ipfs_client_mock

        mocker.patch.object(subprocess, 'run')
        subprocess.run.return_value = subprocess.CompletedProcess(None, 1)

        repo: publishing.GenericRepo = factories.RepoFactory(build_bin='some_cmd', after_publish_bin='some_other_cmd')

        with pytest.raises(exceptions.RepoException):
            repo.publish_repo()
github AuHau / ipfs-publish / publish / cli.py View on Github external
def entrypoint(args: typing.Sequence[str], obj: typing.Optional[dict] = None):
    """
    CLI entry point, where exceptions are handled.
    """
    try:
        cli(args, obj=obj or {})
    except exceptions.IpfsPublishException as e:
        logger.error(str(e).strip())
        logger.debug(traceback.format_exc())
        exit(1)
    except Exception as e:
        if os.environ.get(ENV_NAME_PASS_EXCEPTIONS) == 'True':
            raise

        logger.error(str(e).strip())
        logger.debug(traceback.format_exc())
        exit(1)
github AuHau / ipfs-publish / publish / publishing.py View on Github external
def validate_branch(git_url: str, name: str) -> bool:
    """
    Validate that branch name exists in the Git repository defined by git_url.

    :param git_url:
    :param name:
    :return:
    """
    if name == DEFAULT_BRANCH_PLACEHOLDER:
        return True

    result = subprocess.run('git -c core.askpass=\'echo\' ls-remote ' + git_url, shell=True, capture_output=True)
    if result.returncode != 0:
        raise exceptions.RepoException(f'Error while fetching Git\'s remote refs! {result.stderr.decode("utf-8")}')

    refs_list = result.stdout.decode("utf-8").split('\n')
    regex = re.compile(r'refs/heads/(.*)')

    for entry in refs_list:
        match = regex.search(entry)

        if match is not None and match.group(1) == name:
            return True

    return False
github AuHau / ipfs-publish / publish / republisher.py View on Github external
def convert_lifetime(value: str) -> datetime.timedelta:
    if re.match(LIFETIME_SYNTAX_CHECK_REGEX, value, re.IGNORECASE) is None:
        raise exceptions.PublishingException('Unknown lifetime syntax!')

    matches = re.findall(LIFETIME_SYNTAX_REGEX, value, re.IGNORECASE)
    base = datetime.timedelta()
    for match in matches:
        unit = LIFETIME_MAPPING[match[1].lower()]

        base += datetime.timedelta(**{unit: int(match[0])})

    return base
github AuHau / ipfs-publish / publish / config.py View on Github external
def _verify_data(self, data):
        if not data.get('host') or not data.get('port'):
            raise exceptions.ConfigException('\'host\' and \'port\' are required items in configuration file!')
github AuHau / ipfs-publish / publish / helpers.py View on Github external
def setup_logging(verbosity: int) -> None:
    """
    Setups the logging package based on passed verbosity
    :param verbosity: Verbosity level
    :return:
    """
    if ENV_NAME_VERBOSITY_LEVEL in os.environ:
        try:
            verbosity = max(verbosity, int(os.environ[ENV_NAME_VERBOSITY_LEVEL]))
        except ValueError:
            raise exceptions.IpfsPublishException(f'The env. variable {ENV_NAME_VERBOSITY_LEVEL} has to hold integer!')

    if verbosity == -1:
        sys.stdout = NoOutput()
        sys.stderr = NoOutput()
        return

    if verbosity == 0:
        logging_level = logging.ERROR
    elif verbosity == 1:
        logging_level = logging.INFO
    else:
        logging_level = logging.DEBUG

    logging.basicConfig(stream=sys.stderr, level=logging_level)

    for package, threshold_verbosity in VERBOSITY_PACKAGES.items():
github AuHau / ipfs-publish / publish / publishing.py View on Github external
def validate_time_span(lifetime: str):
    """
    Function validating lifetime syntax
    :param lifetime:
    :return:
    """
    try:
        convert_lifetime(lifetime)
        return True
    except exceptions.PublishingException:
        return False
github AuHau / ipfs-publish / publish / publishing.py View on Github external
def convert_lifetime(value: str) -> datetime.timedelta:
    """
    Converts lifetime string into timedelta object
    :param value:
    :return:
    """
    if re.match(LIFETIME_SYNTAX_CHECK_REGEX, value, re.IGNORECASE) is None:
        raise exceptions.PublishingException('Unknown lifetime syntax!')

    matches = re.findall(LIFETIME_SYNTAX_REGEX, value, re.IGNORECASE)
    base = datetime.timedelta()
    for match in matches:
        unit = LIFETIME_MAPPING[match[1].lower()]

        base += datetime.timedelta(**{unit: int(match[0])})

    return base
github AuHau / ipfs-publish / publish / publishing.py View on Github external
logger.info(f'Unpinning hash: {self.last_ipfs_addr}')
            ipfs.pin.rm(self.last_ipfs_addr)

        publish_dir = path / (self.publish_dir[1:] if self.publish_dir.startswith('/') else self.publish_dir)
        logger.info(f'Adding directory {publish_dir} to IPFS')
        result = ipfs.add(publish_dir, recursive=True, pin=self.pin)
        cid = f'/ipfs/{result[-1]["Hash"]}/'
        self.last_ipfs_addr = cid
        logger.info(f'Repo successfully added to IPFS with hash: {cid}')

        if self.ipns_key is not None:
            self.publish_name(cid)

        try:
            self.update_dns(cid)
        except exceptions.ConfigException:
            pass

        if self.after_publish_bin:
            self._run_bin(path, self.after_publish_bin, cid)

        self._cleanup_repo(path)
github AuHau / ipfs-publish / publish / http.py View on Github external
def handler_dispatcher(repo: typing.Union[publishing.GenericRepo, publishing.GithubRepo]) -> 'GenericHandler':
    """
    Dispatch request to proper Handler based on what kind of repo the request is directed to.
    :param repo: Name of the repo
    :return:
    """
    if type(repo) is publishing.GenericRepo:
        return GenericHandler(repo)
    elif type(repo) is publishing.GithubRepo:
        return GithubHandler(repo)
    else:
        raise exceptions.HttpException('Unknown Repo\'s class!')