1from distutils import log
2import distutils.command.install_scripts as orig
3import os
4import sys
5
6from pkg_resources import Distribution, PathMetadata, ensure_directory
7
8
9class install_scripts(orig.install_scripts):
10    """Do normal script install, plus any egg_info wrapper scripts"""
11
12    def initialize_options(self):
13        orig.install_scripts.initialize_options(self)
14        self.no_ep = False
15
16    def run(self):
17        import setuptools.command.easy_install as ei
18
19        self.run_command("egg_info")
20        if self.distribution.scripts:
21            orig.install_scripts.run(self)  # run first to set up self.outfiles
22        else:
23            self.outfiles = []
24        if self.no_ep:
25            # don't install entry point scripts into .egg file!
26            return
27
28        ei_cmd = self.get_finalized_command("egg_info")
29        dist = Distribution(
30            ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
31            ei_cmd.egg_name, ei_cmd.egg_version,
32        )
33        bs_cmd = self.get_finalized_command('build_scripts')
34        exec_param = getattr(bs_cmd, 'executable', None)
35        bw_cmd = self.get_finalized_command("bdist_wininst")
36        is_wininst = getattr(bw_cmd, '_is_running', False)
37        writer = ei.ScriptWriter
38        if is_wininst:
39            exec_param = "python.exe"
40            writer = ei.WindowsScriptWriter
41        if exec_param == sys.executable:
42            # In case the path to the Python executable contains a space, wrap
43            # it so it's not split up.
44            exec_param = [exec_param]
45        # resolve the writer to the environment
46        writer = writer.best()
47        cmd = writer.command_spec_class.best().from_param(exec_param)
48        for args in writer.get_args(dist, cmd.as_header()):
49            self.write_script(*args)
50
51    def write_script(self, script_name, contents, mode="t", *ignored):
52        """Write an executable file to the scripts directory"""
53        from setuptools.command.easy_install import chmod, current_umask
54
55        log.info("Installing %s script to %s", script_name, self.install_dir)
56        target = os.path.join(self.install_dir, script_name)
57        self.outfiles.append(target)
58
59        mask = current_umask()
60        if not self.dry_run:
61            ensure_directory(target)
62            f = open(target, "w" + mode)
63            f.write(contents)
64            f.close()
65            chmod(target, 0o777 - mask)
66