Update app
Changes: - cmd/app.go - Удален Config за ненадобностью; - Добавлены флаги -n, -g, -f. Подробно в документации; - Теперь при запуске приложения создаются папка приложения и временная папка приложения; - Добавлено чтение из папки и чтение из git-репозитория; - blueprint: - слегка изменена логика проверки файла настроек; - в creator добавлена переменная projectName; - в template просто переименовал структуру; - modules/env: - добавлена проверка обязательных значений из настроек; - добавлена проверка значения переменной в Declaration; - поправлена периодическая ошибка с go get; - modules/logger; - удалена ненужная функция GetFunctions(); - добавлена проверка значения переменной messageType для Message; - поправлена периодическая ошибка с go get; - README.md: добавлена документация по приложению.
This commit is contained in:
parent
ee3accd198
commit
ddb7be7dff
160
README.md
160
README.md
@ -1,93 +1,121 @@
|
||||
# blueprint
|
||||
# Blueprint
|
||||
|
||||
Приложение для развертывания базового проекта на языке Golang.\
|
||||
`<USER_HOME_DIR>/blueprint` - Папка приложения. Здесь хранятся глобально вызываемые Blueprint-проекты.\
|
||||
`<TEMP_DIR/blueprint-*` - Временная папка приложения, создается на время работы приложения.
|
||||
|
||||
## Установка и начало работы
|
||||
|
||||
## Getting started
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
|
||||
## Add your files
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://penahub.gitlab.yandexcloud.net/pena-services/blueprint.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```bash
|
||||
go install penahub.gitlab.yandexcloud.net/pena-services/bluepint
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
```bash
|
||||
cd ./path-to-the-new-project
|
||||
```
|
||||
|
||||
- [ ] [Set up project integrations](https://penahub.gitlab.yandexcloud.net/pena-services/blueprint/-/settings/integrations)
|
||||
```bash
|
||||
bluepint
|
||||
```
|
||||
|
||||
## Collaborate with your team
|
||||
## Структура Blueprint-проекта и работа с приложением
|
||||
### Базовый состав Blueprint-проекта
|
||||
- **Blueprint.yaml** - файл настройки проекта.
|
||||
- **template** - папка хранящая файлы шаблонов кода развертываемого проекта.
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
|
||||
## Test and Deploy
|
||||
### Флаги
|
||||
При вызове приложения без флагов, будет произведен поиск Blueprint-файла и папки template по текущей папке.\
|
||||
`-h`, `-help` - Помощь по программе.\
|
||||
`-n` - Меняет имя проекта, указанное в Blueprint.yaml.\
|
||||
`-f` - Указать Blueprint-проект хранящийся в папке приложения.\
|
||||
`-g` - Указать Blueprint-проект хранящийся в git-репозитории.
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
## Blueprint.yaml
|
||||
Файл настроек должен храниться в корневой папке Blueprint-проекта или в месте вызова приложения, если не были указаны флаги месторасположения Blueprint-проекта.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
Рекомендуемое имя файла настроек `Blueprint.yaml`.\
|
||||
Допустимые имена файла: `Blueprint.yaml`, `Blueprint.yml`, `blueprint.yaml`, `blueprint.yml`.\
|
||||
|
||||
***
|
||||
|
||||
# Editing this README
|
||||
### Настройки файла
|
||||
`ProjectName` - имя проекта. Значение передается в Template.vars\
|
||||
`Description` - базовое описание проекта\
|
||||
`Template` - настройки шаблонизатора\
|
||||
`Modules` - настройки модулей
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
## Template
|
||||
Приложение полностью копирует расположение файлов из папки **template**.
|
||||
Допустимое разрешение файлов шаблонов: `.tmpl`
|
||||
|
||||
## Suggestions for a good README
|
||||
### Настройки
|
||||
`path` - альтернативное расположение папки.\
|
||||
`vars` - хеш-таблица значений, доступных в шаблонах. Пример в шаблоне: `{{.Vars.SomeValue}}`
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
## Модули их настройки и функции
|
||||
Если модуль не будет указан в файле настроек, то он не будет вызван и не сможет использоваться в шаблонизаторе.\
|
||||
Доступные модули:
|
||||
- logger
|
||||
- env
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
## logger
|
||||
Модуль логгера для шаблонизатора
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
### Настройки
|
||||
`name` - Название логгера. Допустимые значения: `zap`
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
### Функции модуля для шаблонизатора
|
||||
`logger.Import()` - возвращает строку для импорта выбранного логгера. Например: `{{.Modules.logger.Import}}` для zap вернет `"go.uber.org/zap"`.\
|
||||
`logger.ImportCore()` - возвращает строку для импорта ядра выбранного логгера. Например: `{{.Modules.logger.ImportCore}}` для zap вернет `"go.uber.org/zap/core"`.\
|
||||
`logger.Declaration()` - возвращает декларирование выбранного логгера. Например: `{{.Modules.logger.Declaration}}` для zap вернет:
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
```golang
|
||||
cfgLogger := zap.NewDevelopmentConfig()
|
||||
cfgLogger.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
|
||||
cfgLogger.EncoderConfig.ConsoleSeparator = " "
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
logger, err := cfgLogger.Build()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
`logger.Type` - возвращает строку с типом выбранного логгера. Например: `{{Modules.logger.Type}}` для zap вернет `*zap.Logger`.\
|
||||
`logger.Message(messageType string, message string, fields ...any)` - принимает messageType как обязательный аргумент, fields должно быть четным, т.к. представляется в виде пары ключ-значение. Ключ всегда оборачивается как строка. Например: `{{.Modules.logger.Message "Fatal" "some error" "Error" "err"}}` для zap вернет `zap.Fatal("some error", zap.Any("Error", err))`.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
## env
|
||||
Модуль для описания переменных окружения и создания структуры конфигурации приложения.\
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
### Настройки
|
||||
`vars` - массив значений переменных окружения.\
|
||||
Принимает объект с полями:
|
||||
- `name` - имя переменной окружения, в структуре именуется в CamelCase. **Обязательное значение.**
|
||||
- `type` - тип переменной для структуры. **Обязательное значение.**
|
||||
- `default` - стандартное значение.
|
||||
- `required` - является ли значение обязательным. По умолчанию: false
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
Пример:
|
||||
```yaml
|
||||
vars:
|
||||
- name: APP_NAME
|
||||
type: string
|
||||
default: Some app name
|
||||
required: true
|
||||
```
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
### Функции модуля для шаблонизатора
|
||||
`env.Import()` - возвращает строку для импорта env. `{{.Modules.env.Import}}` вернет `"github.com/caarlos0/env/v8"`\
|
||||
`env.Declaration(v string)` - возвращает декларирование переменной с заполненной структурой переменных окружения. `{{.Modules.env.Declaration config}}` вернет
|
||||
```golang
|
||||
err = env.Parse(config)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
```
|
||||
`env.Struct()` - возвращает представленное переменное окружение как структуру. Например `{{.Modules.env.Struct}}` для примера выше вернет
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
```golang
|
||||
type Config struct {
|
||||
AppName string `env:"APP_NAME,required" envDefault:"Some app name"`
|
||||
}
|
||||
```
|
||||
|
@ -5,10 +5,11 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"text/template"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"gopkg.in/yaml.v2"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const BlueprintDefaultPath = "./"
|
||||
@ -19,36 +20,45 @@ var (
|
||||
|
||||
// BlueprintFile - описание модели файла.
|
||||
type BlueprintFile struct {
|
||||
ProjectName string `yaml:"ProjectName"`
|
||||
Description string `yaml:"Description,omitempty"`
|
||||
Author string `yaml:"Author,omitempty"`
|
||||
ModulesSettings map[string]any `yaml:"Modules"`
|
||||
Template Settings `yaml:"Template,omitempty"`
|
||||
Vars map[string]any `yaml:"Vars,omitempty"`
|
||||
ProjectName string `yaml:"ProjectName"`
|
||||
Description string `yaml:"Description,omitempty"`
|
||||
Author string `yaml:"Author,omitempty"`
|
||||
ModulesSettings map[string]any `yaml:"Modules"`
|
||||
Template TemplateSettings `yaml:"Template,omitempty"`
|
||||
Vars map[string]any `yaml:"Vars,omitempty"`
|
||||
}
|
||||
|
||||
func readFile(blueprintFilePath string) (blueprint *BlueprintFile, err error) {
|
||||
func readFile(path string) (blueprint *BlueprintFile, err error) {
|
||||
var fileStat os.FileInfo
|
||||
|
||||
if blueprintFilePath == "" {
|
||||
for _, fileName := range BluePrintFileNames {
|
||||
blueprintFilePath = BlueprintDefaultPath + fileName
|
||||
|
||||
fileStat, err = os.Stat(blueprintFilePath)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
|
||||
if fileStat.Size() <= 0 {
|
||||
return nil, fmt.Errorf("blueprint file is empty")
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
if path == "" {
|
||||
path = BlueprintDefaultPath
|
||||
}
|
||||
|
||||
file, err := os.ReadFile(blueprintFilePath)
|
||||
var fullPath string
|
||||
for _, fileName := range BluePrintFileNames {
|
||||
fullPath = filepath.Join(path, fileName)
|
||||
|
||||
fileStat, err = os.Stat(fullPath)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
|
||||
err = nil
|
||||
break
|
||||
}
|
||||
|
||||
if os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("blueprint file not found")
|
||||
}
|
||||
|
||||
if fileStat.Size() <= 0 {
|
||||
return nil, fmt.Errorf("blueprint file is empty")
|
||||
}
|
||||
|
||||
file, err := os.ReadFile(fullPath)
|
||||
if err != nil {
|
||||
// Проверяем еще раз на всякий случай.
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, fmt.Errorf("blueprint file not found")
|
||||
}
|
||||
@ -56,7 +66,7 @@ func readFile(blueprintFilePath string) (blueprint *BlueprintFile, err error) {
|
||||
return nil, fmt.Errorf("cannot read blueprint file: %w", err)
|
||||
}
|
||||
|
||||
log.Info().Str("file", blueprintFilePath).Msg("Reading blueprint file")
|
||||
log.Info().Str("file", fullPath).Msg("Reading blueprint file")
|
||||
|
||||
// Получаем базовый файл.
|
||||
if err = yaml.Unmarshal(file, &blueprint); err != nil {
|
||||
|
@ -20,13 +20,17 @@ type BlueprintModule interface {
|
||||
Execute() error
|
||||
}
|
||||
|
||||
func NewBlueprintCreator(blueprintPath string) (*BlueprintCreator, error) {
|
||||
func NewBlueprintCreator(blueprintPath, projectName string) (*BlueprintCreator, error) {
|
||||
file, err := readFile(blueprintPath)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if projectName != "" {
|
||||
file.ProjectName = projectName
|
||||
}
|
||||
|
||||
blueprintModules := []BlueprintModule{
|
||||
logger.NewLoggerModule(),
|
||||
env.NewEnvModule(),
|
||||
@ -49,9 +53,9 @@ func NewBlueprintCreator(blueprintPath string) (*BlueprintCreator, error) {
|
||||
return nil, fmt.Errorf("blueprintCreator: cannot get absolute path for execPath. %v", err)
|
||||
}
|
||||
|
||||
template := NewTemplate(Settings{
|
||||
template := NewTemplate(TemplateSettings{
|
||||
ExecPath: absExecPath,
|
||||
TemplatePath: file.Template.TemplatePath,
|
||||
TemplatePath: filepath.Join(blueprintPath, file.Template.TemplatePath),
|
||||
Vars: file.Template.Vars,
|
||||
Modules: templateModules,
|
||||
})
|
||||
|
24
blueprint/modules/env/env.go
vendored
24
blueprint/modules/env/env.go
vendored
@ -59,11 +59,27 @@ func (r *EnvModule) SetSettings(settings any) error {
|
||||
return err
|
||||
}
|
||||
|
||||
return yaml.Unmarshal(out, &r.settings)
|
||||
if err = yaml.Unmarshal(out, &r.settings); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Проверяем, обязательные поля name и type
|
||||
for _, v := range r.settings.Vars {
|
||||
if v.Name == "" {
|
||||
return fmt.Errorf("name required for env.vars item")
|
||||
}
|
||||
|
||||
if v.Type == "" {
|
||||
return fmt.Errorf("type required for env.vars item (%v)", v.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *EnvModule) Execute() error {
|
||||
cmd := exec.Command("go", "get", r.Import())
|
||||
value := strings.Replace(r.Import(), `"`, "", -1)
|
||||
cmd := exec.Command("go", "get", value)
|
||||
|
||||
return cmd.Run()
|
||||
}
|
||||
@ -73,6 +89,10 @@ func (r *EnvModule) Import() string {
|
||||
}
|
||||
|
||||
func (r *EnvModule) Declaration(v string) string {
|
||||
if v == "" {
|
||||
return "//FIXME TEMPLATE ERROR: env.Declaration required with non-empty argument"
|
||||
}
|
||||
|
||||
return fmt.Sprintf(`err = env.Parse(%v)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
@ -3,6 +3,7 @@ package logger
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
@ -56,12 +57,9 @@ func (r *LoggerModule) SetSettings(settings any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *LoggerModule) GetFunctions() any {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *LoggerModule) Execute() error {
|
||||
cmd := exec.Command("go", "get", r.Import())
|
||||
value := strings.Replace(r.Import(), `"`, "", -1)
|
||||
cmd := exec.Command("go", "get", value)
|
||||
|
||||
return cmd.Run()
|
||||
}
|
||||
|
@ -43,6 +43,10 @@ func (r *ZapLogger) Message(messageType, message string, fields ...any) string {
|
||||
caser := cases.Title(language.English)
|
||||
messageType = caser.String(messageType)
|
||||
|
||||
if !r.isAllowedMessageType(messageType) {
|
||||
return fmt.Sprintf(`//FIXME TEMPLATE ERROR: logger.Message messageType bad type. Allowed types: %v`, r.allowedMessageTypes())
|
||||
}
|
||||
|
||||
if len(fields)%2 != 0 {
|
||||
return `//FIXME TEMPLATE ERROR: logger.Message need even number of fields. Example: logger.Message <messageType> <some msg> <fieldName> <fieldVal>...`
|
||||
}
|
||||
@ -57,3 +61,17 @@ func (r *ZapLogger) Message(messageType, message string, fields ...any) string {
|
||||
|
||||
return fmt.Sprintf(`logger.%v("%v", %v)`, messageType, message, fieldsToString)
|
||||
}
|
||||
|
||||
func (r *ZapLogger) isAllowedMessageType(messageType string) bool {
|
||||
for _, allowed := range r.allowedMessageTypes() {
|
||||
if messageType == allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *ZapLogger) allowedMessageTypes() []string {
|
||||
return []string{"DPanic", "Debug", "Error", "Fatal", "Info", "Panic", "Warn"}
|
||||
}
|
||||
|
@ -21,20 +21,19 @@ var (
|
||||
TemplateFormats = []string{"tmpl", "gotmpl"}
|
||||
)
|
||||
|
||||
type Settings struct {
|
||||
type TemplateSettings struct {
|
||||
ExecPath string `yaml:"-"`
|
||||
TemplatePath string `yaml:"path"`
|
||||
Vars map[string]any `yaml:"vars,omitempty"`
|
||||
Modules map[string]BlueprintModule `yaml:"-"`
|
||||
// TODO: добавить модули сюда и попробовать вызвать функцию
|
||||
}
|
||||
|
||||
type Template struct {
|
||||
settings *Settings
|
||||
settings *TemplateSettings
|
||||
queue []string
|
||||
}
|
||||
|
||||
func NewTemplate(settings Settings) *Template {
|
||||
func NewTemplate(settings TemplateSettings) *Template {
|
||||
if settings.Vars == nil {
|
||||
settings.Vars = make(map[string]any)
|
||||
}
|
||||
|
166
cmd/app.go
166
cmd/app.go
@ -3,28 +3,41 @@ package cmd
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"penahub.gitlab.yandexcloud.net/pena-services/bluepint/blueprint"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
Config *Config
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Name string
|
||||
Version string
|
||||
Dir string
|
||||
TempDir string
|
||||
}
|
||||
|
||||
func NewApp(cfg *Config) *App {
|
||||
type StartFlags struct {
|
||||
ProjectName string
|
||||
Git string
|
||||
Folder string
|
||||
}
|
||||
|
||||
func NewApp() *App {
|
||||
return &App{
|
||||
Config: cfg,
|
||||
Name: "blueprint",
|
||||
Version: "0.0.1",
|
||||
}
|
||||
}
|
||||
|
||||
// Execute - Любой вызов приложения.
|
||||
func (r *App) Execute() {
|
||||
versionFlag := flag.Bool("v", false, "Show current version")
|
||||
projectNameFlag := flag.String("n", "", "Set project name")
|
||||
gitFlag := flag.String("g", "", "Get blueprint from git")
|
||||
folderFlag := flag.String("f", "", "Get blueprint from ../<user>/blueprint/<folder>")
|
||||
|
||||
flag.Parse()
|
||||
|
||||
@ -36,27 +49,150 @@ func (r *App) Execute() {
|
||||
return
|
||||
}
|
||||
|
||||
r.Run()
|
||||
startFlags := StartFlags{
|
||||
ProjectName: *projectNameFlag,
|
||||
Git: *gitFlag,
|
||||
Folder: *folderFlag,
|
||||
}
|
||||
|
||||
log.Info().Str("version", r.Version).Msg("Blueprint started")
|
||||
if err := r.Run(startFlags); err != nil {
|
||||
log.Error().Err(err).Msg("Run app")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err := r.Close(); err != nil {
|
||||
log.Error().Err(err).Msg("Close app")
|
||||
}
|
||||
log.Info().Msg("Blueprint closed")
|
||||
}()
|
||||
}
|
||||
|
||||
// Run - Запуск приложения.
|
||||
func (r *App) Run() {
|
||||
log.Info().Str("version", r.Config.Version).Msg("Blueprint started")
|
||||
blueprintCreator, err := blueprint.NewBlueprintCreator("")
|
||||
func (r *App) Run(flags StartFlags) error {
|
||||
var err error
|
||||
var blueprintPath, projectName string
|
||||
|
||||
// Create app directory and temporary directory
|
||||
log.Info().Msg("Creating app directory")
|
||||
if err = r.createDir(); err != nil {
|
||||
return fmt.Errorf("cannot create app directory. %v", err)
|
||||
}
|
||||
|
||||
log.Info().Msg("Creating temporary app directory")
|
||||
if err = r.createTempDir(); err != nil {
|
||||
return fmt.Errorf("cannot create temporary app directory. %v", err)
|
||||
}
|
||||
|
||||
if flags.Folder != "" {
|
||||
blueprintPath, err = r.getFromFolder(flags.Folder)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot get from folder. %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if flags.Git != "" {
|
||||
blueprintPath, err = r.getFromGit(flags.Git)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot get from git. %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if flags.ProjectName != "" {
|
||||
projectName = flags.ProjectName
|
||||
}
|
||||
|
||||
blueprintCreator, err := blueprint.NewBlueprintCreator(blueprintPath, projectName)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("NewBlueprintCreator")
|
||||
return
|
||||
return fmt.Errorf("cannot create blueprint creator. %v", err)
|
||||
}
|
||||
|
||||
if err = blueprintCreator.Create(); err != nil {
|
||||
log.Error().Err(err).Msg("BlueprintCreator.Create")
|
||||
return
|
||||
return fmt.Errorf("cannot create app. %v", err)
|
||||
}
|
||||
|
||||
log.Info().Msg("Closing app")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *App) Close() error {
|
||||
log.Info().Msg("removing temporary directory")
|
||||
return os.RemoveAll(r.TempDir)
|
||||
}
|
||||
|
||||
// PrintVersion - Вывод версии приложения.
|
||||
func (r *App) PrintVersion() error {
|
||||
_, err := fmt.Println("Version: ", r.Config.Version)
|
||||
_, err := fmt.Println("Version: ", r.Version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot print. %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createDir - создает папку приложения, если она не существует.
|
||||
func (r *App) createDir() error {
|
||||
path, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path = filepath.Join(path, r.Name)
|
||||
|
||||
r.Dir = path
|
||||
|
||||
_, err = os.Stat(r.Dir)
|
||||
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if os.IsNotExist(err) {
|
||||
return os.Mkdir(r.Dir, 0750)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *App) createTempDir() error {
|
||||
path, err := os.MkdirTemp("", fmt.Sprintf("%v-*", r.Name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.TempDir = path
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getFromGit - возвращает папку с расположением git-репозитория указанного в флаге. Использует команду git clone для загрузки из git-репозитория.
|
||||
func (r *App) getFromGit(url string) (path string, err error) {
|
||||
cmd := exec.Command("git", "clone", url)
|
||||
|
||||
cmd.Dir = r.TempDir
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
url = strings.TrimSuffix(url, ".git")
|
||||
|
||||
repoName := filepath.Base(url)
|
||||
|
||||
path = filepath.Join(r.TempDir, repoName)
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// getFromFolder - возвращает путь из папки приложения + папка из флага. Если папка не существует, то вернется ошибка.
|
||||
func (r *App) getFromFolder(folder string) (path string, err error) {
|
||||
path = filepath.Join(r.Dir, folder)
|
||||
|
||||
_, err = os.Stat(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
@ -26,5 +26,4 @@ func main() {
|
||||
if err := app.Run(ctx, config, logger); err != nil {
|
||||
{{.Modules.logger.Message "Fatal" "Failed to run app" "Error" "err"}}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
1
go.mod
1
go.mod
@ -4,7 +4,6 @@ go 1.21.0
|
||||
|
||||
require (
|
||||
github.com/rs/zerolog v1.31.0
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
|
2
main.go
2
main.go
@ -5,6 +5,6 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := cmd.NewApp(&cmd.Config{Version: "0.0.1"})
|
||||
cmd := cmd.NewApp()
|
||||
cmd.Execute()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user