Merge branch 'feature/521-pinned-post-federation' into 'develop'
[akkoma] / lib / pleroma / utils.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Utils do
6 @posix_error_codes ~w(
7 eacces eagain ebadf ebadmsg ebusy edeadlk edeadlock edquot eexist efault
8 efbig eftype eintr einval eio eisdir eloop emfile emlink emultihop
9 enametoolong enfile enobufs enodev enolck enolink enoent enomem enospc
10 enosr enostr enosys enotblk enotdir enotsup enxio eopnotsupp eoverflow
11 eperm epipe erange erofs espipe esrch estale etxtbsy exdev
12 )a
13
14 def compile_dir(dir) when is_binary(dir) do
15 dir
16 |> File.ls!()
17 |> Enum.map(&Path.join(dir, &1))
18 |> Kernel.ParallelCompiler.compile()
19 end
20
21 @doc """
22 POSIX-compliant check if command is available in the system
23
24 ## Examples
25 iex> command_available?("git")
26 true
27 iex> command_available?("wrongcmd")
28 false
29
30 """
31 @spec command_available?(String.t()) :: boolean()
32 def command_available?(command) do
33 case :os.find_executable(String.to_charlist(command)) do
34 false -> false
35 _ -> true
36 end
37 end
38
39 @doc "creates the uniq temporary directory"
40 @spec tmp_dir(String.t()) :: {:ok, String.t()} | {:error, :file.posix()}
41 def tmp_dir(prefix \\ "") do
42 sub_dir =
43 [
44 prefix,
45 Timex.to_unix(Timex.now()),
46 :os.getpid(),
47 String.downcase(Integer.to_string(:rand.uniform(0x100000000), 36))
48 ]
49 |> Enum.join("-")
50
51 tmp_dir = Path.join(System.tmp_dir!(), sub_dir)
52
53 case File.mkdir(tmp_dir) do
54 :ok -> {:ok, tmp_dir}
55 error -> error
56 end
57 end
58
59 @spec posix_error_message(atom()) :: binary()
60 def posix_error_message(code) when code in @posix_error_codes do
61 error_message = Gettext.dgettext(Pleroma.Web.Gettext, "posix_errors", "#{code}")
62 "(POSIX error: #{error_message})"
63 end
64
65 def posix_error_message(_), do: ""
66 end