<commit_before>"""distutils.command.bdist_pkgtool


Author: <NAME> <<EMAIL>>

Implements the Distutils 'bdist_pkgtool' command (create Solaris pkgtool
distributions)."""

import os, string, sys, pwd, grp
from types import *
from distutils.util import get_platform
from distutils.file_util import write_file
from distutils.errors import *
from distutils.command import bdist_packager
from distutils import sysconfig
from distutils import log
from commands import getoutput

__revision__ = "$Id: bdist_pkgtool.py,v 0.3 mwa "

# default request script - Is also wrapped around user's request script
# unless --no-autorelocate is requested. Finds the python site-packages
# directory and prompts for verification
DEFAULT_REQUEST="""#!/bin/sh
######################################################################
#         Distutils internal package relocation support              #
######################################################################

PRODUCT="__DISTUTILS_NAME__"

trap `exit 3` 15
/usr/bin/which python 2>&1 >/dev/null
if [ $? -ne 0 ]; then
    echo "The python interpretor needs to be on your path!"
    echo
    echo "If you have more than one, make sure the first one is where"
    echo "you want this module installed:"
    exit 1
fi

PY_DIR=`python -c "import sys;print '%s/lib/python%s' % (sys.exec_prefix,sys.version[0:3])" 2>/dev/null`
PY_PKG_DIR=`python -c "import sys;print '%s/lib/python%s/site-packages' % (sys.exec_prefix,sys.version[0:3])" 2>/dev/null`

echo ""
if [ -z "${PY_DIR}" ]; then
        echo "I can't seem to find the python distribution."
        echo "I'm assuming the default path for site-packages"
else
        BASEDIR="${PY_PKG_DIR}"
        cat <<EOF
        Python found! The default path:

        ${BASEDIR}

        will install ${PRODUCT} such that all python users
        can import it.

        If you just want individual access, you can install into
        any directory and add that directory to your \$PYTHONPATH
EOF
fi
echo ""

BASEDIR=`ckpath -d ${BASEDIR} -ay \
        -p "Where should ${PRODUCT} be installed? [${BASEDIR}]"` || exit $?

######################################################################
#                user supplied request script follows                #
######################################################################
"""
### request script

# default postinstall compiles and changes ownership on the module directory
# XXX The ownership change _should_ be handled by adjusting the prototype file
DEFAULT_POSTINSTALL="""#!/bin/sh
/usr/bin/test -d ${BASEDIR}/__DISTUTILS_NAME__
if [ $? -eq 0 ]; then
        python -c "import compileall;compileall.compile_dir(\\"${BASEDIR}/__DISTUTILS_NAME__\\")"
        chown -R root:other ${BASEDIR}/__DISTUTILS_NAME__
fi
"""

# default preremove deletes *.pyc and *.pyo from the module tree
# This should leave the tree empty, so pkgtool will remove it.
# If the user's scripts place anything else in there (e.g. config files),
# pkgtool will leave the directory intact
DEFAULT_PREREMOVE="""#!/bin/sh

/usr/bin/which python 2>&1 >/dev/null
if [ $? -ne 0 ]; then
    echo "The python interpretor needs to be on your path!"
    echo
    echo "If you have more than one, make sure the first one is where"
    echo "you want this module removed from"
    exit 1
fi

/usr/bin/test -d ${BASEDIR}/__DISTUTILS_NAME__
if [ $? -eq 0 ]; then
        find ${BASEDIR}/__DISTUTILS_NAME__ -name "*.pyc" -exec rm {} \;
        find ${BASEDIR}/__DISTUTILS_NAME__ -name "*.pyo" -exec rm {} \;
fi
"""

# default postremove removes the module directory _IF_ no files are
# there (Turns out this isn't needed if the preremove does it's job
# Left for posterity
DEFAULT_POSTREMOVE="""#!/bin/sh

/usr/bin/test -d ${BASEDIR}/__DISTUTILS_NAME__
if [ $? -eq 0 ]; then
        if [ `find ${BASEDIR}/__DISTUTILS_NAME__ ! -type d | wc -l` -eq 0 ]; then
        rm -rf ${BASEDIR}/__DISTUTILS_NAME__
        fi
fi
"""

class bdist_pkgtool (bdist_packager.bdist_packager):

    description = "create an pkgtool (Solaris) package"

    user_options = bdist_packager.bdist_packager.user_options + [
        ('revision=', None,
         "package revision number (PSTAMP)"),
        ('pkg-abrev=', None,
         "Abbreviation (9 characters or less) of the package name"),
        ('compver=', None,
         "file containing compatible versions of this package (man compver)"),
        ('depend=', None,
         "file containing dependencies for this package (man depend)"),
        #('category=', None,
         #"Software category"),
        ('request=', None,
         "request script (Bourne shell code)"),
       ]

    def initialize_options (self):
        # XXX Check for pkgtools on path...
        bdist_packager.bdist_packager.initialize_options(self)
        self.compver = None
        self.depend = None
        self.vendor = None
        self.classes = None
        self.request = None
        self.pkg_abrev = None
        self.revision = None
        # I'm not sure I should need to do this, but the setup.cfg
        # settings weren't showing up....
        options = self.distribution.get_option_dict('bdist_packager')
        for key in options.keys():
            setattr(self,key,options[key][1])

    # initialize_options()


    def finalize_options (self):
        global DEFAULT_REQUEST, DEFAULT_POSTINSTALL
        global DEFAULT_PREREMOVE, DEFAULT_POSTREMOVE
        if self.pkg_dir is None:
            dist_dir = self.get_finalized_command('bdist').dist_dir
            self.pkg_dir = os.path.join(dist_dir, "pkgtool")

        self.ensure_string('classes', None)
        self.ensure_string('revision', "1")
        self.ensure_script('request')
        self.ensure_script('preinstall')
        self.ensure_script('postinstall')
        self.ensure_script('preremove')
        self.ensure_script('postremove')
        self.ensure_string('vendor', None)
        if self.__dict__.has_key('author'):
            if self.__dict__.has_key('author_email'):
                self.ensure_string('vendor',
                        "%s <%s>" % (self.author,
                           self.author_email))
            else:
                self.ensure_string('vendor',
                     "%s" % (self.author))
        self.ensure_string('category', "System,application")
        self.ensure_script('compver')
        self.ensure_script('depend')
        bdist_packager.bdist_packager.finalize_options(self)
        if self.pkg_abrev is None:
            self.pkg_abrev=self.name
        if len(self.pkg_abrev)>9:
            raise DistutilsOptionError, \
            "pkg-abrev (%s) must be less than 9 characters" % self.pkg_abrev
        # Update default scripts with our metadata name
        DEFAULT_REQUEST = string.replace(DEFAULT_REQUEST,
            "__DISTUTILS_NAME__", self.root_package)
        DEFAULT_POSTINSTALL = string.replace(DEFAULT_POSTINSTALL,
            "__DISTUTILS_NAME__", self.root_package)
        DEFAULT_PREREMOVE = string.replace(DEFAULT_PREREMOVE,
            "__DISTUTILS_NAME__", self.root_package)
        DEFAULT_POSTREMOVE = string.replace(DEFAULT_POSTREMOVE,
            "__DISTUTILS_NAME__", self.root_package)

    # finalize_options()


    def make_package(self,root=None):
        # make directories
        self.mkpath(self.pkg_dir)
        if root:
            pkg_dir = self.pkg_dir+"/"+root
            self.mkpath(pkg_dir)
        else:
            pkg_dir = self.pkg_dir

        self.reinitialize_command('install', reinit_subcommands=1)
        # build package
        log.info('Building package')
        self.run_command('build')
        log.info('Creating pkginfo file')
        path = os.path.join(pkg_dir, "pkginfo")
        self.execute(write_file,
                     (path,
                      self._make_info_file()),
                     "writing '%s'" % path)
        # request script handling
        if self.request==None:
            self.request = self._make_request_script()
        if self.request!="":
            path = os.path.join(pkg_dir, "request")
            self.execute(write_file,
                     (path,
                      self.request),
                     "writing '%s'" % path)

        # Create installation scripts, since compver & depend are
        # user created files, they work just fine as scripts
        self.write_script(os.path.join(pkg_dir, "postinstall"),
                 'postinstall',DEFAULT_POSTINSTALL)
        self.write_script(os.path.join(pkg_dir, "preinstall"),
                 'preinstall',None)
        self.write_script(os.path.join(pkg_dir, "preremove"),
                 'preremove',DEFAULT_PREREMOVE)
        self.write_script(os.path.join(pkg_dir, "postremove"),
                 'postremove',None)
        self.write_script(os.path.join(pkg_dir, "compver"),
                 'compver',None)
        self.write_script(os.path.join(pkg_dir, "depend"),
                 'depend',None)

        log.info('Creating prototype file')
        path = os.path.join(pkg_dir, "prototype")
        self.execute(write_file,
                     (path,
                      self._make_prototype()),
                     "writing '%s'" % path)


        if self.control_only: # stop if requested
            return


        log.info('Creating package')
        pkg_cmd = ['pkgmk', '-o', '-f']
        pkg_cmd.append(path)
        pkg_cmd.append('-b')
        pkg_cmd.append(os.environ['PWD'])
        self.spawn(pkg_cmd)
        pkg_cmd = ['pkgtrans', '-s', '/var/spool/pkg']
        path = os.path.join(os.environ['PWD'],pkg_dir,
                           self.get_binary_name() + ".pkg")
        log.info('Transferring package to ' + pkg_dir)
        pkg_cmd.append(path)
        pkg_cmd.append(self.pkg_abrev)
        self.spawn(pkg_cmd)
        os.system("rm -rf /var/spool/pkg/%s" % self.pkg_abrev)


    def run (self):
        if self.subpackages:
            self.subpackages=string.split(self.subpackages,",")
            for pkg in self.subpackages:
                self.make_package(pkg)
        else:
            self.make_package()
    # run()


    def _make_prototype(self):
        proto_file = ["i pkginfo"]
        if self.request:
            proto_file.extend(['i request'])
        if self.postinstall:
            proto_file.extend(['i postinstall'])
        if self.postremove:
            proto_file.extend(['i postremove'])
        if self.preinstall:
            proto_file.extend(['i preinstall'])
        if self.preremove:
            proto_file.extend(['i preremove'])
        if self.compver:
            proto_file.extend(['i compver'])
        if self.requires:
            proto_file.extend(['i depend'])
        proto_file.extend(['!default 644 root bin'])
        build = self.get_finalized_command('build')

        try:
            self.distribution.packages[0]
            file_list=string.split(
                getoutput("pkgproto %s/%s=%s" % \
                          (build.build_lib, self.distribution.packages[0],
                           self.distribution.packages[0])), "\012")
        except:<commit_msg>This module broke on the Mac (where it can't work, but distutils seems to import it anyway) because it imported pwd and grp. Moved the import to inside the routine where they're used.<commit_after>"""distutils.command.bdist_pkgtool


Author: <NAME> <<EMAIL>>

Implements the Distutils 'bdist_pkgtool' command (create Solaris pkgtool
distributions)."""

import os, string, sys
from types import *
from distutils.util import get_platform
from distutils.file_util import write_file
from distutils.errors import *
from distutils.command import bdist_packager
from distutils import sysconfig
from distutils import log
from commands import getoutput

__revision__ = "$Id: bdist_pkgtool.py,v 0.3 mwa "

# default request script - Is also wrapped around user's request script
# unless --no-autorelocate is requested. Finds the python site-packages
# directory and prompts for verification
DEFAULT_REQUEST="""#!/bin/sh
######################################################################
#         Distutils internal package relocation support              #
######################################################################

PRODUCT="__DISTUTILS_NAME__"

trap `exit 3` 15
/usr/bin/which python 2>&1 >/dev/null
if [ $? -ne 0 ]; then
    echo "The python interpretor needs to be on your path!"
    echo
    echo "If you have more than one, make sure the first one is where"
    echo "you want this module installed:"
    exit 1
fi

PY_DIR=`python -c "import sys;print '%s/lib/python%s' % (sys.exec_prefix,sys.version[0:3])" 2>/dev/null`
PY_PKG_DIR=`python -c "import sys;print '%s/lib/python%s/site-packages' % (sys.exec_prefix,sys.version[0:3])" 2>/dev/null`

echo ""
if [ -z "${PY_DIR}" ]; then
        echo "I can't seem to find the python distribution."
        echo "I'm assuming the default path for site-packages"
else
        BASEDIR="${PY_PKG_DIR}"
        cat <<EOF
        Python found! The default path:

        ${BASEDIR}

        will install ${PRODUCT} such that all python users
        can import it.

        If you just want individual access, you can install into
        any directory and add that directory to your \$PYTHONPATH
EOF
fi
echo ""

BASEDIR=`ckpath -d ${BASEDIR} -ay \
        -p "Where should ${PRODUCT} be installed? [${BASEDIR}]"` || exit $?

######################################################################
#                user supplied request script follows                #
######################################################################
"""
### request script

# default postinstall compiles and changes ownership on the module directory
# XXX The ownership change _should_ be handled by adjusting the prototype file
DEFAULT_POSTINSTALL="""#!/bin/sh
/usr/bin/test -d ${BASEDIR}/__DISTUTILS_NAME__
if [ $? -eq 0 ]; then
        python -c "import compileall;compileall.compile_dir(\\"${BASEDIR}/__DISTUTILS_NAME__\\")"
        chown -R root:other ${BASEDIR}/__DISTUTILS_NAME__
fi
"""

# default preremove deletes *.pyc and *.pyo from the module tree
# This should leave the tree empty, so pkgtool will remove it.
# If the user's scripts place anything else in there (e.g. config files),
# pkgtool will leave the directory intact
DEFAULT_PREREMOVE="""#!/bin/sh

/usr/bin/which python 2>&1 >/dev/null
if [ $? -ne 0 ]; then
    echo "The python interpretor needs to be on your path!"
    echo
    echo "If you have more than one, make sure the first one is where"
    echo "you want this module removed from"
    exit 1
fi

/usr/bin/test -d ${BASEDIR}/__DISTUTILS_NAME__
if [ $? -eq 0 ]; then
        find ${BASEDIR}/__DISTUTILS_NAME__ -name "*.pyc" -exec rm {} \;
        find ${BASEDIR}/__DISTUTILS_NAME__ -name "*.pyo" -exec rm {} \;
fi
"""

# default postremove removes the module directory _IF_ no files are
# there (Turns out this isn't needed if the preremove does it's job
# Left for posterity
DEFAULT_POSTREMOVE="""#!/bin/sh

/usr/bin/test -d ${BASEDIR}/__DISTUTILS_NAME__
if [ $? -eq 0 ]; then
        if [ `find ${BASEDIR}/__DISTUTILS_NAME__ ! -type d | wc -l` -eq 0 ]; then
        rm -rf ${BASEDIR}/__DISTUTILS_NAME__
        fi
fi
"""

class bdist_pkgtool (bdist_packager.bdist_packager):

    description = "create an pkgtool (Solaris) package"

    user_options = bdist_packager.bdist_packager.user_options + [
        ('revision=', None,
         "package revision number (PSTAMP)"),
        ('pkg-abrev=', None,
         "Abbreviation (9 characters or less) of the package name"),
        ('compver=', None,
         "file containing compatible versions of this package (man compver)"),
        ('depend=', None,
         "file containing dependencies for this package (man depend)"),
        #('category=', None,
         #"Software category"),
        ('request=', None,
         "request script (Bourne shell code)"),
       ]

    def initialize_options (self):
        # XXX Check for pkgtools on path...
        bdist_packager.bdist_packager.initialize_options(self)
        self.compver = None
        self.depend = None
        self.vendor = None
        self.classes = None
        self.request = None
        self.pkg_abrev = None
        self.revision = None
        # I'm not sure I should need to do this, but the setup.cfg
        # settings weren't showing up....
        options = self.distribution.get_option_dict('bdist_packager')
        for key in options.keys():
            setattr(self,key,options[key][1])

    # initialize_options()


    def finalize_options (self):
        global DEFAULT_REQUEST, DEFAULT_POSTINSTALL
        global DEFAULT_PREREMOVE, DEFAULT_POSTREMOVE
        if self.pkg_dir is None:
            dist_dir = self.get_finalized_command('bdist').dist_dir
            self.pkg_dir = os.path.join(dist_dir, "pkgtool")

        self.ensure_string('classes', None)
        self.ensure_string('revision', "1")
        self.ensure_script('request')
        self.ensure_script('preinstall')
        self.ensure_script('postinstall')
        self.ensure_script('preremove')
        self.ensure_script('postremove')
        self.ensure_string('vendor', None)
        if self.__dict__.has_key('author'):
            if self.__dict__.has_key('author_email'):
                self.ensure_string('vendor',
                        "%s <%s>" % (self.author,
                           self.author_email))
            else:
                self.ensure_string('vendor',
                     "%s" % (self.author))
        self.ensure_string('category', "System,application")
        self.ensure_script('compver')
        self.ensure_script('depend')
        bdist_packager.bdist_packager.finalize_options(self)
        if self.pkg_abrev is None:
            self.pkg_abrev=self.name
        if len(self.pkg_abrev)>9:
            raise DistutilsOptionError, \
            "pkg-abrev (%s) must be less than 9 characters" % self.pkg_abrev
        # Update default scripts with our metadata name
        DEFAULT_REQUEST = string.replace(DEFAULT_REQUEST,
            "__DISTUTILS_NAME__", self.root_package)
        DEFAULT_POSTINSTALL = string.replace(DEFAULT_POSTINSTALL,
            "__DISTUTILS_NAME__", self.root_package)
        DEFAULT_PREREMOVE = string.replace(DEFAULT_PREREMOVE,
            "__DISTUTILS_NAME__", self.root_package)
        DEFAULT_POSTREMOVE = string.replace(DEFAULT_POSTREMOVE,
            "__DISTUTILS_NAME__", self.root_package)

    # finalize_options()


    def make_package(self,root=None):
        # make directories
        self.mkpath(self.pkg_dir)
        if root:
            pkg_dir = self.pkg_dir+"/"+root
            self.mkpath(pkg_dir)
        else:
            pkg_dir = self.pkg_dir

        self.reinitialize_command('install', reinit_subcommands=1)
        # build package
        log.info('Building package')
        self.run_command('build')
        log.info('Creating pkginfo file')
        path = os.path.join(pkg_dir, "pkginfo")
        self.execute(write_file,
                     (path,
                      self._make_info_file()),
                     "writing '%s'" % path)
        # request script handling
        if self.request==None:
            self.request = self._make_request_script()
        if self.request!="":
            path = os.path.join(pkg_dir, "request")
            self.execute(write_file,
                     (path,
                      self.request),
                     "writing '%s'" % path)

        # Create installation scripts, since compver & depend are
        # user created files, they work just fine as scripts
        self.write_script(os.path.join(pkg_dir, "postinstall"),
                 'postinstall',DEFAULT_POSTINSTALL)
        self.write_script(os.path.join(pkg_dir, "preinstall"),
                 'preinstall',None)
        self.write_script(os.path.join(pkg_dir, "preremove"),
                 'preremove',DEFAULT_PREREMOVE)
        self.write_script(os.path.join(pkg_dir, "postremove"),
                 'postremove',None)
        self.write_script(os.path.join(pkg_dir, "compver"),
                 'compver',None)
        self.write_script(os.path.join(pkg_dir, "depend"),
                 'depend',None)

        log.info('Creating prototype file')
        path = os.path.join(pkg_dir, "prototype")
        self.execute(write_file,
                     (path,
                      self._make_prototype()),
                     "writing '%s'" % path)


        if self.control_only: # stop if requested
            return


        log.info('Creating package')
        pkg_cmd = ['pkgmk', '-o', '-f']
        pkg_cmd.append(path)
        pkg_cmd.append('-b')
        pkg_cmd.append(os.environ['PWD'])
        self.spawn(pkg_cmd)
        pkg_cmd = ['pkgtrans', '-s', '/var/spool/pkg']
        path = os.path.join(os.environ['PWD'],pkg_dir,
                           self.get_binary_name() + ".pkg")
        log.info('Transferring package to ' + pkg_dir)
        pkg_cmd.append(path)
        pkg_cmd.append(self.pkg_abrev)
        self.spawn(pkg_cmd)
        os.system("rm -rf /var/spool/pkg/%s" % self.pkg_abrev)


    def run (self):
        if self.subpackages:
            self.subpackages=string.split(self.subpackages,",")
            for pkg in self.subpackages:
                self.make_package(pkg)
        else:
            self.make_package()
    # run()


    def _make_prototype(self):
        import pwd, grp
        proto_file = ["i pkginfo"]
        if self.request:
            proto_file.extend(['i request'])
        if self.postinstall:
            proto_file.extend(['i postinstall'])
        if self.postremove:
            proto_file.extend(['i postremove'])
        if self.preinstall:
            proto_file.extend(['i preinstall'])
        if self.preremove:
            proto_file.extend(['i preremove'])
        if self.compver:
            proto_file.extend(['i compver'])
        if self.requires:
            proto_file.extend(['i depend'])
        proto_file.extend(['!default 644 root bin'])
        build = self.get_finalized_command('build')

        try:
            self.distribution.packages[0]
            file_list=string.split(
                getoutput("pkgproto %s/%s=%s" % \
                          (build.build_lib, self.distribution.packages[0],
                           self.distribution.packages[0])), "\012")
        except:
{'fraction_non_alphanumeric': 0.1354492624050067, 'fraction_numerical': 0.003397407241841752, 'mean_word_length': 2.4353501228501226, 'pattern_counts': {'":': 2, '<': 15, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4405808', 'n_tokens_mistral': 6711, 'n_tokens_neox': 6438, 'n_words': 1650}