Example #1
0
def list_registered():
    account_info = StoreClientCLI().get_account_information()
    snaps = [
        (
            name,
            info["since"],
            "private" if info["private"] else "public",
            info["price"] or "-",
            "-",
        ) for name, info in account_info["snaps"].get(DEFAULT_SERIES,
                                                      {}).items()
        # Presenting only approved snap registrations, which means name
        # disputes will be displayed/sorted some other way.
        if info["status"] == "Approved"
    ]

    if not snaps:
        echo.warning("There are no registered snaps.")
        return

    tabulated_snaps = tabulate(
        sorted(snaps, key=operator.itemgetter(0)),
        headers=["Name", "Since", "Visibility", "Price", "Notes"],
        tablefmt="plain",
    )
    print(tabulated_snaps)
Example #2
0
def apply_host_provider_flags(build_provider_flags: Dict[str, str]) -> None:
    """Set build environment flags in snapcraft process."""

    # Snapcraft plugins currently check for environment variables,
    # e.g. http_proxy and https_proxy.  Ensure they are set if configured.
    for key, value in build_provider_flags.items():
        if value is None:
            if key in os.environ:
                os.environ.pop(key)
        else:
            os.environ[key] = str(value)

    # Clear false/unset boolean environment flags.
    for option in _PROVIDER_OPTIONS:
        if not option.get("is_flag", False):
            continue

        env_name = option.get("envvar")
        if env_name is None:
            continue

        if not build_provider_flags.get(env_name):
            os.environ.pop(env_name, None)
            continue

    # Log any experimental flags in use.
    if build_provider_flags.get("SNAPCRAFT_ENABLE_EXPERIMENTAL_PACKAGE_REPOSITORIES"):
        warning("*EXPERIMENTAL* package-repositories enabled.")

    if build_provider_flags.get("SNAPCRAFT_ENABLE_EXPERIMENTAL_EXTENSIONS"):
        warning("*EXPERIMENTAL* extensions enabled.")
Example #3
0
def login(
    *,
    store: storeapi.StoreClient,
    packages: Iterable[Dict[str, str]] = None,
    save: bool = True,
    acls: Iterable[str] = None,
    channels: Iterable[str] = None,
    expires: str = None,
    config_fd: TextIO = None,
) -> bool:
    if not store:
        store = storeapi.StoreClient()

    email = ""
    password = ""

    if not config_fd:
        echo.wrapped("Enter your Ubuntu One e-mail address and password.")
        echo.wrapped(
            "If you do not have an Ubuntu One account, you can create one "
            "at https://snapcraft.io/account"
        )
        email = echo.prompt("Email")
        if os.getenv("SNAPCRAFT_TEST_INPUT"):
            # Integration tests do not work well with hidden input.
            echo.warning("Password will be visible.")
            hide_input = False
        else:
            hide_input = True
        password = echo.prompt("Password", hide_input=hide_input)

    try:
        _try_login(
            email,
            password,
            store=store,
            packages=packages,
            acls=acls,
            channels=channels,
            expires=expires,
            config_fd=config_fd,
            save=save,
        )
    # Let StoreAuthenticationError pass through so we get decent error messages
    except storeapi.errors.InvalidCredentialsError:
        return _fail_login(storeapi.constants.INVALID_CREDENTIALS)
    except storeapi.errors.StoreAccountInformationError:
        return _fail_login(storeapi.constants.ACCOUNT_INFORMATION_ERROR)
    except storeapi.errors.NeedTermsSignedError as e:
        return _fail_login(e.message)  # type: ignore

    return True
Example #4
0
 def clean(self, parts, step):
     # clean with no parts deletes the container
     if not step:
         if self._get_container_status():
             print('Deleting {}'.format(self._container_name))
             subprocess.check_call(
                 ['lxc', 'delete', '-f', self._container_name])
         step = 'pull'
     # clean normally, without involving the container
     if step == 'strip':
         echo.warning('DEPRECATED: Use `prime` instead of `strip` '
                      'as the step to clean')
         step = 'prime'
     lifecycle.clean(self._project_options, parts, step)
Example #5
0
def _sanity_check_build_provider_flags(build_provider: str, **kwargs) -> None:
    destructive_mode = kwargs.get("destructive_mode")
    env_provider = os.getenv("SNAPCRAFT_BUILD_ENVIRONMENT")

    # Specifying --provider=host requires the use of --destructive-mode.
    # Exceptions include:
    # (1) SNAPCRAFT_BUILD_ENVIRONMENT=host.
    # (2) Running inside of a container.
    if (
        build_provider == "host"
        and not env_provider == "host"
        and not destructive_mode
        and not common.is_process_container()
    ):
        raise click.BadArgumentUsage(
            "--provider=host requires --destructive-mode to acknowledge side effects"
        )

    if env_provider and env_provider != build_provider:
        raise click.BadArgumentUsage(
            "mismatch between --provider={} and SNAPCRAFT_BUILD_ENVIRONMENT={}".format(
                build_provider, env_provider
            )
        )

    # Error if any sys.argv params are for unsupported providers.
    # Values from environment variables and configuration files only
    # change defaults, so they are safe to ignore due to filtering
    # in get_build_provider_flags().
    for option in _PROVIDER_OPTIONS:
        key: str = option["param_decls"]  # type: ignore
        supported_providers: List[str] = option["supported_providers"]  # type: ignore
        if key in sys.argv and build_provider not in supported_providers:
            raise click.BadArgumentUsage(
                f"{key} cannot be used with build provider {build_provider!r}"
            )

    # Check if running as sudo but only if the host is not managed-host where Snapcraft
    # runs as root already. This effectively avoids the warning when using the default
    # build provider (Multipass) that uses "sudo" to get "root".
    if (
        build_provider != "managed-host"
        and os.getenv("SUDO_USER")
        and os.geteuid() == 0
    ):
        warning(
            "Running with 'sudo' may cause permission errors and is discouraged. Use 'sudo' when cleaning."
        )
Example #6
0
def apply_host_provider_flags(build_provider_flags: Dict[str, str]) -> None:
    """Set build environment flags in snapcraft process."""

    # Snapcraft plugins currently check for environment variables,
    # e.g. http_proxy and https_proxy.  Ensure they are set if configured.
    for key, value in build_provider_flags.items():
        if value is None:
            if key in os.environ:
                os.environ.pop(key)
        else:
            os.environ[key] = str(value)

    # Log any experimental flags in use.
    if build_provider_flags.get(
            "SNAPCRAFT_ENABLE_EXPERIMENTAL_PACKAGE_REPOSITORIES"):
        warning("*EXPERIMENTAL* package-repositories in use")
Example #7
0
def login(
    *,
    store: storeapi.StoreClient,
    packages: Iterable[Dict[str, str]] = None,
    save: bool = True,
    acls: Iterable[str] = None,
    channels: Iterable[str] = None,
    expires: str = None,
    config_fd: TextIO = None,
) -> bool:
    if not store:
        store = storeapi.StoreClient()

    email = ""
    password = ""

    if not config_fd:
        echo.wrapped("Enter your Ubuntu One e-mail address and password.")
        echo.wrapped(
            "If you do not have an Ubuntu One account, you can create one "
            "at https://snapcraft.io/account"
        )
        email = echo.prompt("Email")
        if os.getenv("SNAPCRAFT_TEST_INPUT"):
            # Integration tests do not work well with hidden input.
            echo.warning("Password will be visible.")
            hide_input = False
        else:
            hide_input = True
        password = echo.prompt("Password", hide_input=hide_input)

    _try_login(
        email,
        password,
        store=store,
        packages=packages,
        acls=acls,
        channels=channels,
        expires=expires,
        config_fd=config_fd,
        save=save,
    )

    return True
Example #8
0
def issue_build_provider_warnings(build_provider_flags: Dict[str, str]) -> None:
    # Log any experimental flags in use.
    if build_provider_flags.get("SNAPCRAFT_ENABLE_EXPERIMENTAL_PACKAGE_REPOSITORIES"):
        warning("*EXPERIMENTAL* package-repositories enabled.")

    if build_provider_flags.get("SNAPCRAFT_ENABLE_EXPERIMENTAL_EXTENSIONS"):
        warning("*EXPERIMENTAL* extensions enabled.")

    if build_provider_flags.get("SNAPCRAFT_ENABLE_EXPERIMENTAL_TARGET_ARCH"):
        warning("*EXPERIMENTAL* --target-arch for core20 enabled.")
Example #9
0
def issue_build_provider_warnings(
        build_provider_flags: Dict[str, str]) -> None:
    # Log any experimental flags in use.
    if build_provider_flags.get("SNAPCRAFT_ENABLE_EXPERIMENTAL_EXTENSIONS"):
        warning("*EXPERIMENTAL* extensions enabled.")

    if build_provider_flags.get("SNAPCRAFT_ENABLE_EXPERIMENTAL_TARGET_ARCH"):
        warning("*EXPERIMENTAL* --target-arch for core20 enabled.")

    if build_provider_flags.get("SNAPCRAFT_OFFLINE"):
        warning("*EXPERIMENTAL* --offline enabled.")
Example #10
0
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import codecs
import locale
import os
import subprocess

from snapcraft.cli._runner import run
from snapcraft.cli.snapcraftctl._runner import run as run_snapcraftctl  # noqa
from snapcraft.cli.echo import warning

# If the locale ends up being ascii, Click will barf. Let's try to prevent that
# here by using C.UTF-8 as a last-resort fallback. This mostly happens in CI,
# using LXD or Docker. This is the same logic used by Click to error out.
if codecs.lookup(locale.getpreferredencoding()).name == "ascii" and os.name == "posix":
    output = subprocess.check_output(["locale", "-a"]).decode("ascii", "replace")

    for line in output.splitlines():
        this_locale = line.strip()
        if this_locale.lower() in ("c.utf8", "c.utf-8"):
            warning("Locale not set! Snapcraft will temporarily use C.UTF-8")
            os.environ["LC_ALL"] = "C.UTF-8"
            os.environ["LANG"] = "C.UTF-8"
            break


if __name__ == "__main__":
    run()