Build compiles and links the given package and writes it to outpath.
(pkgName, outpath string, config *compileopts.Config)
| 142 | |
| 143 | // Build compiles and links the given package and writes it to outpath. |
| 144 | func Build(pkgName, outpath string, config *compileopts.Config) error { |
| 145 | if config.Target != nil && config.Target.InheritableOnly { |
| 146 | return errInheritableOnly |
| 147 | } |
| 148 | |
| 149 | // Create a temporary directory for intermediary files. |
| 150 | tmpdir, err := os.MkdirTemp("", "tinygo") |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | if !config.Options.Work { |
| 155 | defer os.RemoveAll(tmpdir) |
| 156 | } |
| 157 | |
| 158 | // Do the build. |
| 159 | result, err := builder.Build(pkgName, outpath, tmpdir, config) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | |
| 164 | if result.Binary != "" { |
| 165 | // If result.Binary is set, it means there is a build output (elf, hex, |
| 166 | // etc) that we need to move to the outpath. If it isn't set, it means |
| 167 | // the build output was a .ll, .bc or .o file that has already been |
| 168 | // written to outpath and so we don't need to do anything. |
| 169 | |
| 170 | if outpath == "" { |
| 171 | if strings.HasSuffix(pkgName, ".go") { |
| 172 | // A Go file was specified directly on the command line. |
| 173 | // Base the binary name off of it. |
| 174 | outpath = filepath.Base(pkgName[:len(pkgName)-3]) + config.DefaultBinaryExtension() |
| 175 | } else { |
| 176 | // Pick a default output path based on the main directory. |
| 177 | outpath = filepath.Base(result.MainDir) + config.DefaultBinaryExtension() |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | if err := os.Rename(result.Binary, outpath); err != nil { |
| 182 | // Moving failed. Do a file copy. |
| 183 | inf, err := os.Open(result.Binary) |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | defer inf.Close() |
| 188 | outf, err := os.OpenFile(outpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) |
| 189 | if err != nil { |
| 190 | return err |
| 191 | } |
| 192 | |
| 193 | // Copy data to output file. |
| 194 | _, err = io.Copy(outf, inf) |
| 195 | if err != nil { |
| 196 | return err |
| 197 | } |
| 198 | |
| 199 | // Check whether file writing was successful. |
| 200 | return outf.Close() |
| 201 | } |