diff --git a/main.go b/main.go index 9d77440..f2fd7d1 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,7 @@ import ( "net/textproto" "os" "path/filepath" + "strings" "github.com/sethvargo/go-githubactions" ) @@ -21,6 +22,37 @@ type AddResponse struct { Size string } +type IpfsMultipartWriter struct { + multipart.Writer +} + +var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") + +func escapeQuotes(s string) string { + return quoteEscaper.Replace(s) +} + +func NewIpfsMultipartWriter(w io.Writer) *IpfsMultipartWriter { + return &IpfsMultipartWriter{ + Writer: *multipart.NewWriter(w), + } +} + +func (w *IpfsMultipartWriter) CreateIpfsDirectoryPart(name string) (io.Writer, error) { + h := make(textproto.MIMEHeader) + h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, name)) + h.Set("Content-Type", "application/x-directory") + return w.CreatePart(h) +} + +func (w *IpfsMultipartWriter) CreateIpfsFilePart(absPath, name string) (io.Writer, error) { + h := make(textproto.MIMEHeader) + h.Set("AbsPath", absPath) + h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, escapeQuotes(name))) + h.Set("Content-Type", "application/octet-stream") + return w.CreatePart(h) +} + func main() { githubactions.Infof("Checking inputs...") @@ -65,18 +97,17 @@ func main() { githubactions.Fatalf("Unable to create request: %v", err.Error()) } - mwriter := multipart.NewWriter(writer) + mwriter := NewIpfsMultipartWriter(writer) req.Header.Add("Content-Type", mwriter.FormDataContentType()) go func() { defer mwriter.Close() defer writer.Close() - h := make(textproto.MIMEHeader) - h.Set("Content-Disposition", - fmt.Sprintf(`form-data; name="file"; filename="%s"`, path)) - h.Set("Content-Type", "application/x-directory") - mwriter.CreatePart(h) + w, err := mwriter.CreateIpfsDirectoryPart(path) + if err != nil { + githubactions.Fatalf("Unable to create root dir path: %v", fmt.Errorf("%w", err)) + } err = filepath.Walk(path, func(innerPath string, info fs.FileInfo, err error) error { if err != nil { @@ -88,7 +119,7 @@ func main() { } githubactions.Infof("Reading %v", innerPath) - w, err := mwriter.CreateFormFile("file", innerPath) + w, err = mwriter.CreateFormFile("file", innerPath) if err != nil { return err }