Fix the tar command that replaced a shell string

Review the AI's codeEasy10 min

Your task

An assistant's archiving code pasted a user's filename into the shell string tar -czf out.tgz <name>, and its only test used report.csv. The replacement builds an argument list that runs with no shell, so ;, | and $(...) in a name stay plain characters.

An assistant wrote build_tar_argv(archive, filename). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • archive: the name of the archive to write.
  • filename: the file to archive, as the user typed it. It can hold any character.
  • Return the argument list to run, as a list of strings, or an empty list to refuse.

Rules the tests check:

  • An empty archive or an empty filename returns an empty list.
  • A filename that starts with / returns an empty list: it is an absolute path.
  • Split filename on /. If any piece is exactly .., return an empty list: the path climbs out of the working directory. Only a piece that is exactly .. counts. Nothing else is refused.
  • Otherwise return ["tar", "-czf", archive, "--", filename]. The -- tells tar that no options follow, so a name that starts with - is read as a file.
  • Use both strings exactly as given. No quoting or escaping, even when the name holds spaces, quotes, ;, | or $.

Examples

build_tar_argv(archive: str, filename: str) -> list[str]
Example 1
Inputbuild_tar_argv("out.tgz", "report.csv")
Output["tar", "-czf", "out.tgz", "--", "report.csv"]
Example 2
Inputbuild_tar_argv("out.tgz", "report.csv; rm -rf ~")
Output["tar", "-czf", "out.tgz", "--", "report.csv; rm -rf ~"]
Example 3
Inputbuild_tar_argv("out.tgz", "../etc/passwd")
Output[]