如何将zip文件中的文件标记为Unix可执行文件?

huangapple go评论121阅读模式
英文:

How to mark a file in a zip as unix executable?

问题

我想写一个类似这样的函数:

  1. func MarkFileAsExecutable(zipPath, filePath string) error

它接收一个 zip 文件的路径和 zip 内的文件路径。目标是使用 zip 包来修改文件内的 ExternalAttributes,将其标记为 Unix 可执行文件。

请注意,在使用 chmod +x 将文件标记为可执行文件之前进行归档并不是一个解决方案,因为我需要在 Windows 上使用此功能。所以,我需要相应地修改现有的 zip 归档文件。

英文:

I'd like to write a function like this:

  1. func MarkFileAsExecutable(zipPath, filePath string) error

It receives a path to a zip and a file path within the zip. The goal is to use the zip package to change the ExternalAttributes of the file inside to mark it as a unix executable.

Note that marking the file as executable prior to archiving it using chmod +x isn't a solution because I need this to work on Windows. So instead I need to modify the existing zip archive accordingly.

答案1

得分: 3

你可以使用zip包。它提供了一个Reader和一个Writer。你可以用一个读取器打开zip归档文件。然后遍历归档文件中的文件,根据需要更改权限,并将文件复制到写入器中。

以下是一个简单的示例,没有错误检查:

  1. package main
  2. import (
  3. "archive/zip"
  4. "os"
  5. )
  6. func main() {
  7. r, _ := zip.OpenReader("example.zip")
  8. defer r.Close()
  9. f, _ := os.Create("output.zip")
  10. defer f.Close()
  11. w := zip.NewWriter(f)
  12. defer w.Close()
  13. for _, f := range r.File {
  14. f.SetMode(0777)
  15. w.Copy(f)
  16. }
  17. }
英文:

You can use the zip package. It provides a Reader and a Writer. You open the zip archive with a reader. Then you walk the files in the archive, change your permissions as needed, and copy the files to the writer.

Here is a minimal example, without error checking:

  1. package main
  2. import (
  3. "archive/zip"
  4. "os"
  5. )
  6. func main() {
  7. r, _ := zip.OpenReader("example.zip")
  8. defer r.Close()
  9. f, _ := os.Create("output.zip")
  10. defer f.Close()
  11. w := zip.NewWriter(f)
  12. defer w.Close()
  13. for _, f := range r.File {
  14. f.SetMode(0777)
  15. w.Copy(f)
  16. }
  17. }

huangapple
  • 本文由 发表于 2023年7月15日 02:20:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76690262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定