Debian Codegraph @

hgext/logtoprocess.py

raw
1 # logtoprocess.py - send ui.log() data to a subprocess
2 #
3 # Copyright 2016 Facebook, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7 """send ui.log() data to a subprocess (EXPERIMENTAL)
8
9 This extension lets you specify a shell command per ui.log() event,
10 sending all remaining arguments to as environment variables to that command.
11
12 Positional arguments construct a log message, which is passed in the `MSG1`
13 environment variables. Each keyword argument is set as a `OPT_UPPERCASE_KEY`
14 variable (so the key is uppercased, and prefixed with `OPT_`). The original
15 event name is passed in the `EVENT` environment variable, and the process ID
16 of mercurial is given in `HGPID`.
17
18 So given a call `ui.log('foo', 'bar %s\n', 'baz', spam='eggs'), a script
19 configured for the `foo` event can expect an environment with `MSG1=bar baz`,
20 and `OPT_SPAM=eggs`.
21
22 Scripts are configured in the `[logtoprocess]` section, each key an event name.
23 For example::
24
25 [logtoprocess]
26 commandexception = echo "$MSG1" > /var/log/mercurial_exceptions.log
27
28 would log the warning message and traceback of any failed command dispatch.
29
30 Scripts are run asynchronously as detached daemon processes; mercurial will
31 not ensure that they exit cleanly.
32
33 """
34
35 from __future__ import annotations
36
37 import os
38
39 from mercurial.utils import procutil
40
41 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
42 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
43 # be specifying the version(s) of Mercurial they are tested with, or
44 # leave the attribute unspecified.
45 testedwith = b'ships-with-hg-core'
46
47
48 class processlogger:
49 """Map log events to external commands
50
51 Arguments are passed on as environment variables.
52 """
53
54 def __init__(self, ui):
55 self._scripts = dict(ui.configitems(b'logtoprocess'))
56
57 def tracked(self, event):
58 return bool(self._scripts.get(event))
59
60 def log(self, ui, event, msg, opts):
61 script = self._scripts[event]
62 maxmsg = 100000
63 if len(msg) > maxmsg:
64 # Each env var has a 128KiB limit on linux. msg can be long, in
65 # particular for command event, where it's the full command line.
66 # Prefer truncating the message than raising "Argument list too
67 # long" error.
68 msg = msg[:maxmsg] + b' (truncated)'
69 env = {
70 b'EVENT': event,
71 b'HGPID': os.getpid(),
72 b'MSG1': msg,
73 }
74 # keyword arguments get prefixed with OPT_ and uppercased
75 env.update(
76 (b'OPT_%s' % key.upper(), value) for key, value in opts.items()
77 )
78 fullenv = procutil.shellenviron(env)
79 procutil.runbgcommand(script, fullenv, shell=True)
80
81
82 def uipopulate(ui):
83 ui.setlogger(b'logtoprocess', processlogger(ui))