How to use the snapcraft.file_utils function in snapcraft

To help you get started, we’ve selected a few snapcraft 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 snapcore / snapcraft / tests / unit / test_file_utils.py View on Github external
def test_replace_in_file(self):
        os.makedirs("bin")

        with open(self.file_path, "w") as f:
            f.write(self.contents)

        file_utils.replace_in_file(
            "bin", re.compile(r""), re.compile(r"#!.*python"), r"#!/usr/bin/env python"
        )

        with open(self.file_path, "r") as f:
            self.assertThat(f.read(), Equals(self.expected))
github snapcore / snapcraft / tests / unit / cache / test_snap.py View on Github external
def test_snap_cache(self):
        # cache snap
        snap_cache = cache.SnapCache(project_name="cache-test")
        cached_snap_path = snap_cache.cache(snap_filename=self.snap_path)

        expected_snap_path = os.path.join(
            snap_cache.snap_cache_root,
            "amd64",
            file_utils.calculate_sha3_384(self.snap_path),
        )

        self.assertThat(cached_snap_path, Equals(expected_snap_path))
        self.assertTrue(os.path.isfile(cached_snap_path))
github snapcore / snapcraft / tests / unit / plugins / test_dotnet.py View on Github external
dedent(
                            """\
                        Hash: SHA512

                        05fe90457a8b77ad5a5eb2f22348f53e962012a
                        {} dotnet-sdk-2.1.4-linux-x64.tar.gz
                        """
                        ).format(self._checksum),
                        "utf-8",
                    )
                return data

        with tarfile.open("test-sdk.tar", "w") as test_sdk_tar:
            open("test-sdk", "w").close()
            test_sdk_tar.add("test-sdk")
        checksum = file_utils.calculate_hash("test-sdk.tar", algorithm="sha512")

        patcher = mock.patch("urllib.request.urlopen")
        urlopen_mock = patcher.start()
        urlopen_mock.side_effect = fake_urlopen
        self.addCleanup(patcher.stop)

        original_check_call = snapcraft.internal.common.run
        patcher = mock.patch("snapcraft.internal.common.run")
        self.mock_check_call = patcher.start()
        self.addCleanup(patcher.stop)

        def side_effect(cmd, *args, **kwargs):
            if cmd[0].endswith("dotnet"):
                pass
            else:
                original_check_call(cmd, *args, **kwargs)
github snapcore / snapcraft / tests / unit / test_file_utils.py View on Github external
def test_requires_path_exists_custom_error(self):
        raised = self.assertRaises(
            RequiredPathDoesNotExist,
            file_utils.requires_path_exists(
                "foo", error_fmt="what? {path!r}"
            ).__enter__,
        )

        self.assertThat(str(raised), Equals("what? 'foo'"))
github snapcore / snapcraft / snapcraft / plugins / colcon.py View on Github external
def _rewrite_cmake_paths(self, new_path_callable):
        def _rewrite_paths(match):
            paths = match.group(1).strip().split(";")
            for i, path in enumerate(paths):
                # Offer the opportunity to rewrite this path if it's absolute.
                if os.path.isabs(path):
                    paths[i] = new_path_callable(path)

            return '"' + ";".join(paths) + '"'

        # Looking for any path-like string
        file_utils.replace_in_file(
            self._ros_underlay,
            re.compile(r".*Config.cmake$"),
            re.compile(r'"(.*?/.*?)"'),
            _rewrite_paths,
        )
github snapcore / snapcraft / snapcraft / project / _project_options.py View on Github external
def _get_linker_version_for_base(self, base: str) -> str:
        """Returns the linker version for base."""
        try:
            return _LINKER_VERSION_FOR_BASE[base]
        except KeyError:
            linker_file = os.path.basename(self.get_core_dynamic_linker(base))
            return file_utils.get_linker_version_from_file(linker_file)
github snapcore / snapcraft / snapcraft / internal / repo / _deb.py View on Github external
def unpack(self, unpackdir) -> None:
        pkgs_abs_path = glob.glob(os.path.join(self._downloaddir, "*.deb"))
        for pkg in pkgs_abs_path:
            with tempfile.TemporaryDirectory() as temp_dir:
                self._extract_deb(pkg, temp_dir)
                deb_name = self._extract_deb_name_version(pkg)
                self._mark_origin_stage_package(temp_dir, deb_name)
                file_utils.link_or_copy_tree(temp_dir, unpackdir)
        self.normalize(unpackdir)
github snapcore / snapcraft / snapcraft / internal / elf.py View on Github external
:param str dynamic_linker: the path to the dynamic linker to set the
                                   elf file to.
        :param str root_path: the base path for the snap to determine
                              if use of $ORIGIN is possible.
        :param str preferred_patchelf_path: patch the necessary elf_files with
                                        this patchelf.
        """
        self._dynamic_linker = dynamic_linker
        self._root_path = root_path

        if preferred_patchelf_path:
            self._patchelf_cmd = preferred_patchelf_path
        else:
            self._patchelf_cmd = file_utils.get_tool_path("patchelf")

        self._strip_cmd = file_utils.get_tool_path("strip")
github snapcore / snapcraft / snapcraft / internal / pluginhandler / __init__.py View on Github external
def _migrate_files(
    snap_files,
    snap_dirs,
    srcdir,
    dstdir,
    missing_ok=False,
    follow_symlinks=False,
    fixup_func=lambda *args: None,
):
    for snap_dir in sorted(snap_dirs):
        src = os.path.join(srcdir, snap_dir)
        dst = os.path.join(dstdir, snap_dir)

        snapcraft.file_utils.create_similar_directory(src, dst)

    for snap_file in sorted(snap_files):
        src = os.path.join(srcdir, snap_file)
        dst = os.path.join(dstdir, snap_file)

        if missing_ok and not os.path.exists(src):
            continue

        # If the file is already here and it's a symlink, leave it alone.
        if os.path.islink(dst):
            continue

        # Otherwise, remove and re-link it.
        if os.path.exists(dst):
            os.remove(dst)
github juju / juju / snap / plugins / x-dep.py View on Github external
def pull(self):
        super().pull()

        try:
            shutil.rmtree(os.path.dirname(self._path_in_gopath))
        except:  # noqa: E722
            pass
        finally:
            os.makedirs(os.path.dirname(self._path_in_gopath), exist_ok=True)

        file_utils.link_or_copy_tree(self.sourcedir, self._path_in_gopath)

        # Fetch and run dep
        logger.info("Fetching dep...")
        self._run(["go", "get", "github.com/golang/dep/cmd/dep"])

        logger.info("Obtaining project dependencies...")
        self._run(
            [
                "dep",
                "ensure",
                "-vendor-only",
            ]