| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package main |
| 16 |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "os" |
| 20 | "os/exec" |
| 21 | "path" |
| 22 | "path/filepath" |
| 23 | ) |
| 24 |
| 25 | type Task interface { |
| 26 | // Destination returns the destination path for this task, using forward |
| 27 | // slashes and relative to the source directory. That is, use the "path" |
| 28 | // package, not "path/filepath". |
| 29 | Destination() string |
| 30 |
| 31 | // Run computes the output for this task. It should be written to the |
| 32 | // destination path. |
| 33 | Run() ([]byte, error) |
| 34 | } |
| 35 |
| 36 | type SimpleTask struct { |
| 37 | Dst string |
| 38 | RunFunc func() ([]byte, error) |
| 39 | } |
| 40 |
| 41 | func (t *SimpleTask) Destination() string { return t.Dst } |
| 42 | func (t *SimpleTask) Run() ([]byte, error) { return t.RunFunc() } |
| 43 |
| 44 | func NewSimpleTask(dst string, runFunc func() ([]byte, error)) *SimpleTask { |
| 45 | return &SimpleTask{Dst: dst, RunFunc: runFunc} |
| 46 | } |
| 47 |
| 48 | type PerlasmTask struct { |
| 49 | Src, Dst string |
| 50 | Args []string |
| 51 | } |
| 52 |
| 53 | func (t *PerlasmTask) Destination() string { return t.Dst } |
| 54 | func (t *PerlasmTask) Run() ([]byte, error) { |
| 55 | base := path.Base(t.Dst) |
| 56 | out, err := os.CreateTemp("", "*."+base) |
| 57 | if err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | defer os.Remove(out.Name()) |
| 61 |
| 62 | args := make([]string, 0, 2+len(t.Args)) |
| 63 | args = append(args, filepath.FromSlash(t.Src)) |
| 64 | args = append(args, t.Args...) |
| 65 | args = append(args, out.Name()) |
| 66 | cmd := exec.Command(*perlPath, args...) |
| 67 | cmd.Stderr = os.Stderr |
| 68 | cmd.Stdout = os.Stdout |
| 69 | if err := cmd.Run(); err != nil { |
| 70 | return nil, err |
| 71 | } |
| 72 |
| 73 | data, err := os.ReadFile(out.Name()) |
| 74 | if err != nil { |
| 75 | return nil, err |
| 76 | } |
| 77 |
| 78 | // On Windows, perl emits CRLF line endings. Normalize this so that the tool |
| 79 | // can be run on Windows too. |
| 80 | data = bytes.ReplaceAll(data, []byte("\r\n"), []byte("\n")) |
| 81 | return data, nil |
| 82 | } |
| 83 |