nixpkgs/pkgs/development/interpreters/python/wrap-python.nix
Frederik Rietdijk d68aba4cfb Python: script names now include full path
Certain programs, like zim, calibre and now also apparently mercurial,
rely on sys.argv[0] providing not just the script name but the full
path.

The Python docs [1] state the following on the matter:

> argv[0] is the script name (it is operating system dependent whether
this is a full pathname or not).

Therefore, scripts should not expect to receive a full path.
Unfortunately some do. While this can be considered a bug, there doesn't
seem any reason not to provide the full path. Therefore we now provide
the full path.

[1]
https://docs.python.org/3.5/library/sys.html?highlight=sys.argv#sys.argv
2017-01-02 11:29:11 +01:00

52 lines
1.8 KiB
Nix

{ lib
, python
, makeSetupHook
, makeWrapper }:
with lib;
makeSetupHook {
deps = makeWrapper;
substitutions.libPrefix = python.libPrefix;
substitutions.executable = python.interpreter;
substitutions.python = python;
substitutions.magicalSedExpression = let
# Looks weird? Of course, it's between single quoted shell strings.
# NOTE: Order DOES matter here, so single character quotes need to be
# at the last position.
quoteVariants = [ "'\"'''\"'" "\"\"\"" "\"" "'\"'\"'" ]; # hey Vim: ''
mkStringSkipper = labelNum: quote: let
label = "q${toString labelNum}";
isSingle = elem quote [ "\"" "'\"'\"'" ];
endQuote = if isSingle then "[^\\\\]${quote}" else quote;
in ''
/^[a-z]?${quote}/ {
/${quote}${quote}|${quote}.*${endQuote}/{n;br}
:${label}; n; /^${quote}/{n;br}; /${endQuote}/{n;br}; b${label}
}
'';
# This preamble does two things:
# * Sets argv[0] to the original application's name; otherwise it would be .foo-wrapped.
# Python doesn't support `exec -a`.
# * Adds all required libraries to sys.path via `site.addsitedir`. It also handles *.pth files.
preamble = ''
import sys
import site
import functools
sys.argv[0] = '"'$(readlink -f "$f")'"'
functools.reduce(lambda k, p: site.addsitedir(p, k), ['"$([ -n "$program_PYTHONPATH" ] && (echo "'$program_PYTHONPATH'" | sed "s|:|','|g") || true)"'], site._init_pathinfo())
'';
in ''
1 {
:r
/\\$|,$/{N;br}
/__future__|^ |^ *(#.*)?$/{n;br}
${concatImapStrings mkStringSkipper quoteVariants}
/^[^# ]/i ${replaceStrings ["\n"] [";"] preamble}
}
'';
} ./wrap.sh