コード例 #1
0
ファイル: __init__.py プロジェクト: discentem/autopkg
    def get_or_setup_token(self):
        """Setup a GitHub OAuth token string. Will help to create one if necessary.
        The string will be stored in TOKEN_LOCATION and used again
        if it exists."""

        token = self._get_token()
        if not token and not os.path.exists(TOKEN_LOCATION):
            print("""Create a new token in your GitHub settings page:

    https://github.com/settings/tokens

To save the token, paste it to the following prompt.""")

            token = input("Token: ")
            if token:
                log(f"Writing token file {TOKEN_LOCATION}.")
                try:
                    with open(TOKEN_LOCATION, "w") as tokenf:
                        tokenf.write(token)
                    os.chmod(TOKEN_LOCATION, 0o600)
                except OSError as err:
                    log_err(
                        f"Couldn't write token file at {TOKEN_LOCATION}! Error: {err}"
                    )
            else:
                log("Skipping token file creation.")

        self.token = token
        return token
コード例 #2
0
ファイル: __init__.py プロジェクト: doc22940/auto.pkg
    def setup_token(self):
        """Setup a GitHub OAuth token string. Will help to create one if necessary.
        The string will be stored in TOKEN_LOCATION and used again
        if it exists."""

        if not os.path.exists(TOKEN_LOCATION):
            print(
                """Create a new token in your GitHub settings page:

    https://github.com/settings/tokens

To save the token, paste it to the following prompt."""
            )

            token = raw_input("Token: ")
            if token:
                log("""Writing token file {}.""".format(TOKEN_LOCATION))
                try:
                    with open(TOKEN_LOCATION, "w") as tokenf:
                        tokenf.write(token)
                    os.chmod(TOKEN_LOCATION, 0o600)
                except IOError as err:
                    log_err(
                        "Couldn't write token file at {}! Error: {}".format(
                            TOKEN_LOCATION, err
                        )
                    )
            else:
                log("Skipping token file creation.")
        else:
            try:
                with open(TOKEN_LOCATION, "r") as tokenf:
                    token = tokenf.read()
            except IOError as err:
                log_err(
                    "Couldn't read token file at {}! Error: {}".format(
                        TOKEN_LOCATION, err
                    )
                )

            # TODO: validate token given we found one but haven't checked its
            # auth status

        self.token = token
コード例 #3
0
ファイル: __init__.py プロジェクト: discentem/autopkg
    def search_for_name(
        self,
        name: str,
        path_only: bool = False,
        user: str = DEFAULT_SEARCH_USER,
        use_token: bool = False,
        results_limit: int = 100,
    ):
        """Search GitHub for results for a given name."""

        # Include all supported recipe extensions in search.
        # Compound extensions like ".recipe.yaml" aren't definable here,
        # so further filtering of results is done below.
        exts = "+".join(
            ("extension:" + ext.split(".")[-1] for ext in RECIPE_EXTS))
        # Example value: "extension:recipe+extension:plist+extension:yaml"

        query = f"q={quote(name)}+{exts}+user:{user}"

        if path_only:
            query += "+in:path,filepath"
        else:
            query += "+in:path,file"
        query += f"&per_page={results_limit}"

        results = self.code_search(query, use_token=use_token)

        if not results or not results.get("total_count"):
            log("Nothing found.")
            return []

        # Filter out files from results that are not AutoPkg recipes.
        results_items = [
            item for item in results["items"]
            if any((item["name"].endswith(ext) for ext in RECIPE_EXTS))
        ]

        if not results_items:
            log("Nothing found.")
            return []
        return results_items
コード例 #4
0
#
#     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.
"""See docstring for MunkiSetDefaultCatalog class"""

from autopkglib import Processor, log

try:
    from Foundation import CFPreferencesCopyAppValue
except ImportError:
    log("WARNING: Failed 'from Foundation import CFPreferencesCopyAppValue' "
        "in " + __name__)

__all__ = ["MunkiSetDefaultCatalog"]


class MunkiSetDefaultCatalog(Processor):
    """Edit current munki pkginfo to set the 'catalog' key to the default
    catalog preference for munkiimport (com.googlecode.munki.munkiimport),
    if one has been set. Typically this would be run as a preprocessor."""

    input_variables = {
        "pkginfo": {
            "required": False,
            "description": "Dictionary of Munki pkginfo."
        }
    }
コード例 #5
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.
"""See docstring for MunkiInstallsItemsCreator class"""

import plistlib
import subprocess

from autopkglib import Processor, ProcessorError, log

try:
    from Foundation import NSDictionary
except ImportError:
    log("WARNING: Failed 'from Foundation import NSDictionary' in " + __name__)

__all__ = ["MunkiInstallsItemsCreator"]


class MunkiInstallsItemsCreator(Processor):
    """Generates an installs array for a pkginfo file."""

    input_variables = {
        "installs_item_paths": {
            "required": True,
            "description": "Array of paths to create installs items for.",
        },
        "faux_root": {
            "required": False,
            "description": "The root of an expanded package or filesystem.",
コード例 #6
0
#
#     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.
"""See docstring for StopProcessingIf class"""

from autopkglib import Processor, ProcessorError, log

try:
    from Foundation import NSPredicate
except ImportError:
    log("WARNING: Failed 'from Foundation import NSPredicate' in " + __name__)

__all__ = ["StopProcessingIf"]


class StopProcessingIf(Processor):
    """Sets a variable to tell AutoPackager to stop processing a recipe if a
    predicate comparison evaluates to true."""

    description = __doc__
    input_variables = {
        "predicate": {
            "required": True,
            "description": (
                "NSPredicate-style comparison against an environment key. See "
                "http://developer.apple.com/library/mac/#documentation/"
コード例 #7
0
ファイル: DmgMounter.py プロジェクト: doc22940/auto.pkg
        try:
            proc = subprocess.Popen(
                ("/usr/bin/hdiutil", "detach", self.mounts[pathname]),
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            stderr = proc.communicate()[1]
        except OSError as err:
            raise ProcessorError(
                "hdiutil execution failed with error code %d: %s" %
                (err.errno, err.strerror))
        if proc.returncode != 0:
            raise ProcessorError("unmounting %s failed: %s" %
                                 (pathname, stderr))

        # Delete mount from mount list.
        del self.mounts[pathname]


if __name__ == "__main__":
    try:
        DMGMOUNTER = DmgMounter()
        MOUNTPOINT = DMGMOUNTER.mount("Download/Firefox-sv-SE.dmg")
        log("Mounted at %s" % MOUNTPOINT)
        DMGMOUNTER.unmount("Download/Firefox-sv-SE.dmg")
    except ProcessorError as err:
        log_err("ProcessorError: %s" % err)
        sys.exit(10)
    else:
        sys.exit(0)
コード例 #8
0
        try:
            proc = subprocess.Popen(
                ("/usr/bin/hdiutil", "detach", self.mounts[pathname]),
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
            )
            (_, stderr) = proc.communicate()
        except OSError as err:
            raise ProcessorError(
                f"hdiutil execution failed with error code {err.errno}: {err.strerror}"
            )
        if proc.returncode != 0:
            raise ProcessorError(f"unmounting {pathname} failed: {stderr}")

        # Delete mount from mount list.
        del self.mounts[pathname]


if __name__ == "__main__":
    try:
        DMGMOUNTER = DmgMounter()
        MOUNTPOINT = DMGMOUNTER.mount("Download/Firefox-sv-SE.dmg")
        log(f"Mounted at {MOUNTPOINT}")
        DMGMOUNTER.unmount("Download/Firefox-sv-SE.dmg")
    except ProcessorError as err:
        log_err(f"ProcessorError: {err}")
        sys.exit(10)
    else:
        sys.exit(0)
コード例 #9
0
ファイル: AppDmgVersioner.py プロジェクト: doc22940/auto.pkg
# See the License for the specific language governing permissions and
# limitations under the License.
"""See docstring for AppDmgVersioner class"""

import glob
import os.path

from autopkglib import ProcessorError, log
from autopkglib.DmgMounter import DmgMounter

# pylint: disable=no-name-in-module
try:
    from Foundation import NSData, NSPropertyListSerialization
    from Foundation import NSPropertyListMutableContainers
except:
    log("WARNING: Failed 'from Foundation import NSData, "
        "NSPropertyListSerialization' in " + __name__)
    log("WARNING: Failed 'from Foundation import "
        "NSPropertyListMutableContainers' in " + __name__)
# pylint: enable=no-name-in-module

__all__ = ["AppDmgVersioner"]


class AppDmgVersioner(DmgMounter):
    # we dynamically set the docstring from the description (DRY), so:
    # pylint: disable=missing-docstring
    description = "Extracts bundle ID and version of app inside dmg."
    input_variables = {
        "dmg_path": {
            "required": True,
            "description": "Path to a dmg containing an app.",