Home  >  Article  >  Backend Development  >  How to mark files in zip as unix executable?

How to mark files in zip as unix executable?

WBOY
WBOYforward
2024-02-14 08:18:08962browse

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

php editor Xiaoxin will introduce to you how to mark the files in the zip file as Unix executable files. In Unix systems, the executable attribute of a file is determined by the file's permissions, so we need to modify the permissions of the files in the zip file. First, unzip the zip file into the target folder. Then, use the chmod command to modify the file's permissions. Finally, repackage the modified files into a zip file. With this simple step, you can mark the files in your zip file as Unix executable.

Question content

I want to write a function like this:

func MarkFileAsExecutable(zipPath, filePath string) error

It receives the path to zip and the file path within zip. The goal is to use the zip package to change the externalattributes of the internal file, marking it as unix executable.

Please note that marking the file as executable before archiving it using chmod x is not a solution as I need it to work on windows. Therefore, I need to modify the existing zip archive accordingly.

Solution

You can use the zip package. It provides a reader and a writer. You open the zip archive with Reader. You then loop through the files in the archive, change permissions as needed, and copy the files to the writer.

This is a minimal example with no error checking:

package main

import (
    "archive/zip"
    "os"
)

func main() {
    r, _ := zip.OpenReader("example.zip")
    defer r.Close()

    f, _ := os.Create("output.zip")
    defer f.Close()

    w := zip.NewWriter(f)
    defer w.Close()

    for _, f := range r.File {
        f.SetMode(0777)
        w.Copy(f)
    }
}

The above is the detailed content of How to mark files in zip as unix executable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete