summaryrefslogtreecommitdiff
path: root/admin/emacs-shell-lib
blob: 67f76f6130078701a8da4707cb175a7e6a5b77c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/bin/bash
### emacs-shell-lib - shared code for Emacs shell scripts

## Copyright (C) 2022-2023 Free Software Foundation, Inc.

## Author: Stefan Kangas <stefankangas@gmail.com>

## This file is part of GNU Emacs.

## GNU Emacs is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.

## GNU Emacs is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.

### Code:

# Set an explicit umask.
umask 077

# Treat unset variables as an error.
set -o nounset

# Exit immediately on error.
set -o errexit

# Avoid non-standard command output from non-C locales.
unset LANG LC_ALL LC_MESSAGES

PN=${0##*/}                     # basename of script
PD=${0%/*}                      # script directory

[ "$PD" = "$0" ] && PD=.        # if PATH includes PWD

die ()                 # write error to stderr and exit
{
    [ $# -gt 0 ] && echo "$PN: $@" >&2
    exit 1
}

emacs_tempfiles=()

emacs_tempfiles_cleanup ()
{
    for file in ${emacs_tempfiles[@]}; do
        rm -f "${file}" 2> /dev/null
    done
}

trap '
  ret=$?
  emacs_tempfiles_cleanup
  exit $ret
' EXIT

emacs_mktemp ()
{
    local readonly file="${1-}"
    local tempfile
    local prefix

    if [ -z "$file" ]; then
        prefix="$PN"
    else
        prefix="$1"
    fi

    if [ -x "$(command -v mktemp)" ]; then
        tempfile=$(mktemp "${TMPDIR-/tmp}/${prefix}.XXXXXXXXXX")
    else
        tempfile="${TMPDIR-/tmp}/${prefix}.$RANDOM$$"
        (umask 077 && touch "$tempfile")
    fi

    [ -z "${tempfile}" ] && die "Creating temporary file failed"

    emacs_tempfiles+=("${tempfile}")

    echo "$tempfile"
}