Skip to content

Commit

Permalink
Update SSHKit.Context.build/2 implementation
Browse files Browse the repository at this point in the history
- Use sudo for both switching user and group in a single command
- Quick version of `SSHKit.Utils.shellquote/1`, improved one follows
  • Loading branch information
pmeinhardt committed May 9, 2017
1 parent c79a3fd commit e11da3f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 18 deletions.
29 changes: 12 additions & 17 deletions lib/sshkit/context.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,32 +22,27 @@ defmodule SSHKit.Context do
```
"""
def build(context, command) do
command
|> cmd
|> group(context.group)
|> user(context.user)
|> env(context.env)
"/usr/bin/env #{command}"
|> sudo(context.user, context.group)
|> export(context.env)
|> umask(context.umask)
|> path(context.path)
|> cd(context.path)
end

defp cmd(command), do: "/usr/bin/env #{command}"
defp sudo(command, nil, nil), do: command
defp sudo(command, username, nil), do: "sudo -n -u #{username} -- sh -c #{shellquote(command)}"
defp sudo(command, nil, groupname), do: "sudo -n -g #{groupname} -- sh -c #{shellquote(command)}"
defp sudo(command, username, groupname), do: "sudo -n -u #{username} -g #{groupname} -- sh -c #{shellquote(command)}"

defp group(command, nil), do: command
defp group(command, _name), do: command

defp user(command, nil), do: command
defp user(command, name), do: "sudo -u #{name} -- sh -c #{shellquote(command)}"

defp env(command, nil), do: command
defp env(command, env) do
defp export(command, nil), do: command
defp export(command, env) do
exports = Enum.map_join(env, " ", fn {name, value} -> "#{name}=\"#{value}\"" end)
"(export #{exports} && #{command})"
end

defp umask(command, nil), do: command
defp umask(command, mask), do: "umask #{mask} && #{command}"

defp path(command, nil), do: command
defp path(command, path), do: "cd #{path} && #{command}"
defp cd(command, nil), do: command
defp cd(command, path), do: "cd #{path} && #{command}"
end
2 changes: 1 addition & 1 deletion lib/sshkit/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ defmodule SSHKit.Utils do

def shellescape(value), do: value

def shellquote(value), do: value
def shellquote(value), do: "'#{value}'" # TODO: Proper quoting

def charlistify(value) when is_list(value) do
Enum.map(value, &charlistify/1)
Expand Down

0 comments on commit e11da3f

Please sign in to comment.