2017-05-17 15:38:46 -03:00
|
|
|
package task
|
|
|
|
|
|
|
|
|
|
import (
|
2025-03-11 13:53:08 +00:00
|
|
|
_ "embed"
|
2017-05-17 15:38:46 -03:00
|
|
|
"os"
|
2022-08-06 18:19:07 -03:00
|
|
|
|
2023-04-15 21:22:25 +01:00
|
|
|
"github.com/go-task/task/v3/errors"
|
2022-08-06 18:19:07 -03:00
|
|
|
"github.com/go-task/task/v3/internal/filepathext"
|
2025-12-07 17:29:51 -03:00
|
|
|
"github.com/go-task/task/v3/taskfile"
|
2017-05-17 15:38:46 -03:00
|
|
|
)
|
|
|
|
|
|
2025-12-07 17:29:51 -03:00
|
|
|
const defaultFilename = "Taskfile.yml"
|
2023-03-17 08:53:01 +08:00
|
|
|
|
2025-03-11 13:53:08 +00:00
|
|
|
//go:embed taskfile/templates/default.yml
|
|
|
|
|
var DefaultTaskfile string
|
|
|
|
|
|
2025-02-10 08:22:49 -03:00
|
|
|
// InitTaskfile creates a new Taskfile at path.
|
|
|
|
|
//
|
|
|
|
|
// path can be either a file path or a directory path.
|
|
|
|
|
// If path is a directory, path/Taskfile.yml will be created.
|
|
|
|
|
//
|
|
|
|
|
// The final file path is always returned and may be different from the input path.
|
2025-02-10 11:24:32 +00:00
|
|
|
func InitTaskfile(path string) (string, error) {
|
2025-12-07 17:29:51 -03:00
|
|
|
info, err := os.Stat(path)
|
|
|
|
|
if err == nil && !info.IsDir() {
|
2025-02-10 08:22:49 -03:00
|
|
|
return path, errors.TaskfileAlreadyExistsError{}
|
|
|
|
|
}
|
2018-03-04 16:17:51 -03:00
|
|
|
|
2025-12-07 17:29:51 -03:00
|
|
|
if info != nil && info.IsDir() {
|
|
|
|
|
// path was a directory, check if there is a Taskfile already
|
|
|
|
|
if hasDefaultTaskfile(path) {
|
2025-02-10 08:22:49 -03:00
|
|
|
return path, errors.TaskfileAlreadyExistsError{}
|
|
|
|
|
}
|
2025-12-07 17:29:51 -03:00
|
|
|
path = filepathext.SmartJoin(path, defaultFilename)
|
2017-05-17 15:38:46 -03:00
|
|
|
}
|
|
|
|
|
|
2025-02-10 08:22:49 -03:00
|
|
|
if err := os.WriteFile(path, []byte(DefaultTaskfile), 0o644); err != nil {
|
|
|
|
|
return path, err
|
2017-05-17 15:38:46 -03:00
|
|
|
}
|
2025-02-10 08:22:49 -03:00
|
|
|
return path, nil
|
2017-05-17 15:38:46 -03:00
|
|
|
}
|
2025-12-07 17:29:51 -03:00
|
|
|
|
|
|
|
|
func hasDefaultTaskfile(dir string) bool {
|
|
|
|
|
for _, name := range taskfile.DefaultTaskfiles {
|
|
|
|
|
if _, err := os.Stat(filepathext.SmartJoin(dir, name)); err == nil {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|