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        try:
36            bw_cmd = self.get_finalized_command("bdist_wininst")
37            is_wininst = getattr(bw_cmd, '_is_running', False)
38        except ImportError:
39            is_wininst = False
40        writer = ei.ScriptWriter
41        if is_wininst:
42            exec_param = "python.exe"
43            writer = ei.WindowsScriptWriter
44        if exec_param == sys.executable:
45            # In case the path to the Python executable contains a space, wrap
46            # it so it's not split up.
47            exec_param = [exec_param]
48        # resolve the writer to the environment
49        writer = writer.best()
50        cmd = writer.command_spec_class.best().from_param(exec_param)
51        for args in writer.get_args(dist, cmd.as_header()):
52            self.write_script(*args)
53
54    def write_script(self, script_name, contents, mode="t", *ignored):
55        """Write an executable file to the scripts directory"""
56        from setuptools.command.easy_install import chmod, current_umask
57
58        log.info("Installing %s script to %s", script_name, self.install_dir)
59        target = os.path.join(self.install_dir, script_name)
60        self.outfiles.append(target)
61
62        mask = current_umask()
63        if not self.dry_run:
64            ensure_directory(target)
65            f = open(target, "w" + mode)
66            f.write(contents)
67            f.close()
68            chmod(target, 0o777 - mask)
69