Fix the tar command that replaced a shell string
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
archiveor an emptyfilenamereturns an empty list. - A
filenamethat starts with/returns an empty list: it is an absolute path. - Split
filenameon/. 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
Input
build_tar_argv("out.tgz", "report.csv")Output
["tar", "-czf", "out.tgz", "--", "report.csv"]Example 2
Input
build_tar_argv("out.tgz", "report.csv; rm -rf ~")Output
["tar", "-czf", "out.tgz", "--", "report.csv; rm -rf ~"]Example 3
Input
build_tar_argv("out.tgz", "../etc/passwd")Output
[]