gorig-cli 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,21 +1,49 @@
1
1
  # Gorig CLI
2
2
 
3
- Gorig CLI 是一个基于 Node.js 的脚手架工具,用于在基于gorig框架的 Go 项目中快速创建模块化结构。它提供了一组命令,用于自动生成项目中的目录和文件,简化开发流程。
3
+ Gorig CLI 是一个基于 Node.js 的脚手架工具,用于快速创建基于 Gorig 框架的 Go 项目结构和模块。
4
4
 
5
5
  ## 安装
6
6
 
7
- 使用 npm 进行全局安装:
7
+ 使用 npm 全局安装:
8
8
 
9
9
  ```sh
10
10
  npm install -g gorig-cli
11
11
  ```
12
12
 
13
- ## 使用示例
13
+ ## 快速开始
14
14
 
15
- 使用 `create` 命令创建一个新的模块,例如:
15
+ ### 初始化新项目
16
+
17
+ 使用 `init` 命令创建一个新项目:
18
+
19
+ ```sh
20
+ gorig-cli init my-new-project
21
+ ```
22
+
23
+ 这将在当前目录下创建一个新项目,包含 `_cmd/main.go`、`domain/init.go`、`cron/cron.go` 等基本文件和目录。
24
+
25
+ ### 创建新模块
26
+
27
+ 使用 `create` 命令创建一个新模块:
28
+
29
+ ```sh
30
+ gorig-cli create user
31
+ ```
32
+
33
+ 这将在项目中创建一个名为 `user` 的模块,包含 `api/`、`internal/`、`model/` 等文件夹和必要的代码。
34
+
35
+ ### 运行项目
36
+
37
+ 进入项目目录后,可以使用以下命令运行项目:
38
+
39
+ ```sh
40
+ cd my-new-project
41
+ go run _cmd/main.go
42
+ ```
43
+
44
+ 或者编译后运行:
16
45
 
17
46
  ```sh
18
- gorig-cli create coupon
47
+ go build -o my-new-project _cmd/main.go && ./my-new-project
19
48
  ```
20
49
 
21
- 以上命令将在项目中生成一个名为 `coupon` 的模块,包含必要的目录和文件。
package/bin/cli.js CHANGED
@@ -8,7 +8,7 @@ const args = process.argv.slice(2);
8
8
 
9
9
  // 验证是否提供了命令
10
10
  if (args.length < 1) {
11
- console.error(chalk.red('请提供一个有效的命令,例如: create'));
11
+ console.error(chalk.red('请提供一个有效的命令,例如: create 或 init'));
12
12
  process.exit(1);
13
13
  }
14
14
 
@@ -30,8 +30,18 @@ switch (command) {
30
30
  });
31
31
  break;
32
32
 
33
+ case 'init':
34
+ // 动态导入 init.js
35
+ import(path.join(__dirname, '../commands/init.js')).then(module => {
36
+ const initModule = module.default;
37
+ initModule(args.slice(1)); // 将命令行的其他参数传递给 init.js
38
+ }).catch(error => {
39
+ console.error(chalk.red('无法加载 init 命令模块:', error.message));
40
+ });
41
+ break;
42
+
33
43
  default:
34
44
  console.error(chalk.red(`未知的命令: ${command}`));
35
- console.error(chalk.yellow('可用的命令: create'));
45
+ console.error(chalk.yellow('可用的命令: create, init'));
36
46
  process.exit(1);
37
47
  }
@@ -0,0 +1,194 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import chalk from 'chalk';
4
+ import ejs from 'ejs';
5
+ import { exec } from 'child_process';
6
+ import { fileURLToPath } from 'url';
7
+ import readline from 'readline';
8
+
9
+ // 获取 __dirname 的替代方案
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+
13
+ // 检查系统是否安装了 Go
14
+ const checkGoEnvironment = () => {
15
+ return new Promise((resolve, reject) => {
16
+ exec('go version', (error, stdout, stderr) => {
17
+ if (error) {
18
+ reject(new Error('未检测到 Go 环境,请先安装 Go 语言环境,访问 https://golang.org/dl/ 进行安装。'));
19
+ } else {
20
+ resolve(stdout);
21
+ }
22
+ });
23
+ });
24
+ };
25
+
26
+ // 添加 gorig 依赖到项目中
27
+ const addGorigDependency = (projectDir) => {
28
+ return new Promise((resolve, reject) => {
29
+ exec('go get github.com/jom-io/gorig@latest', { cwd: projectDir }, (error, stdout, stderr) => {
30
+ if (error) {
31
+ reject(new Error(`无法添加 gorig 依赖: ${stderr}`));
32
+ } else {
33
+ resolve(stdout);
34
+ }
35
+ });
36
+ });
37
+ };
38
+
39
+ // 执行 go mod tidy
40
+ const runGoModTidy = (projectDir) => {
41
+ return new Promise((resolve, reject) => {
42
+ exec('go mod tidy', { cwd: projectDir }, (error, stdout, stderr) => {
43
+ if (error) {
44
+ reject(new Error(`运行 go mod tidy 失败: ${stderr}`));
45
+ } else {
46
+ resolve(stdout);
47
+ }
48
+ });
49
+ });
50
+ };
51
+
52
+ // 询问用户是否覆盖已有目录
53
+ const askOverwriteConfirmation = (projectDir) => {
54
+ return new Promise((resolve) => {
55
+ const rl = readline.createInterface({
56
+ input: process.stdin,
57
+ output: process.stdout
58
+ });
59
+ rl.question(
60
+ chalk.yellow(`目录 ${chalk.bold(projectDir)} 已经存在,是否覆盖?(y/N): `),
61
+ (answer) => {
62
+ rl.close();
63
+ if (answer.toLowerCase() === 'y') {
64
+ resolve(true);
65
+ } else {
66
+ resolve(false);
67
+ }
68
+ }
69
+ );
70
+ });
71
+ };
72
+
73
+ // 初始化项目的主函数
74
+ const initModule = async (args) => {
75
+ if (args.length < 1) {
76
+ console.error(chalk.yellow('请使用正确的命令格式: npx <你的包名> init <项目名>'));
77
+ process.exit(1);
78
+ }
79
+
80
+ const projectName = args[0];
81
+ const projectDir = path.join(process.cwd(), projectName);
82
+ const projectNameUpper = projectName.toUpperCase();
83
+ const projectPrefix = projectName.toLowerCase().replace(/-/g, '_');
84
+
85
+ // 定义需要创建的子目录
86
+ const subDirs = ['_bin', '_cmd', 'domain', 'global', 'cron'];
87
+
88
+ console.log(chalk.blue(`\n开始初始化项目: ${chalk.bold(projectName)}`));
89
+
90
+ try {
91
+ // 检查本地是否存在 Go 环境
92
+ await checkGoEnvironment();
93
+ console.log(chalk.green('检测到 Go 环境,继续进行项目初始化...'));
94
+
95
+ // 检查项目目录是否已存在
96
+ if (await fs.pathExists(projectDir)) {
97
+ const shouldOverwrite = await askOverwriteConfirmation(projectDir);
98
+ if (!shouldOverwrite) {
99
+ console.log(chalk.red('项目初始化已取消。'));
100
+ process.exit(0);
101
+ } else {
102
+ await fs.remove(projectDir); // 删除已有的目录
103
+ console.log(chalk.yellow(`已删除现有目录: ${chalk.bold(projectDir)}`));
104
+ }
105
+ }
106
+
107
+ // 创建项目目录
108
+ await fs.ensureDir(projectDir);
109
+
110
+ // 创建子目录
111
+ const createSubDirs = subDirs.map((subDir) => {
112
+ const subDirPath = path.join(projectDir, subDir);
113
+ return fs.ensureDir(subDirPath);
114
+ });
115
+ await Promise.all(createSubDirs);
116
+
117
+ // 创建并写入 go.mod 文件
118
+ const goModPath = path.join(projectDir, 'go.mod');
119
+ const goModContent = `module ${projectName}\n\ngo 1.20\n`;
120
+ await fs.writeFile(goModPath, goModContent);
121
+ console.log(chalk.green(`成功创建 ${chalk.bold('go.mod')} 文件`));
122
+
123
+ // 添加 gorig 依赖
124
+ console.log(chalk.blue('添加 gorig 依赖中,请稍候...'));
125
+ await addGorigDependency(projectDir);
126
+ console.log(chalk.green(`成功添加 github.com/jom-io/gorig 最新版本的依赖`));
127
+
128
+ // 创建 _bin 目录下的配置文件
129
+ const binDir = path.join(projectDir, '_bin');
130
+ const configTemplatePath = path.join(__dirname, '../templates/config.yaml.ejs');
131
+
132
+ const environments = ['dev', 'local', 'prod'];
133
+ for (const env of environments) {
134
+ const configFilePath = path.join(binDir, `${env}.yaml`);
135
+ const configContent = await ejs.renderFile(configTemplatePath, {
136
+ projectNameUpper,
137
+ projectPrefix,
138
+ mode: env,
139
+ });
140
+ await fs.writeFile(configFilePath, configContent);
141
+ console.log(chalk.green(`成功创建 ${chalk.bold(`${env}.yaml`)} 文件`));
142
+ }
143
+
144
+ // 创建 domain/init.go 文件
145
+ const domainDir = path.join(projectDir, 'domain');
146
+ const initGoPath = path.join(domainDir, 'init.go');
147
+ const initGoTemplatePath = path.join(__dirname, '../templates/init.go.ejs');
148
+ const initGoContent = await ejs.renderFile(initGoTemplatePath, { projectNameUpper });
149
+ await fs.writeFile(initGoPath, initGoContent);
150
+ console.log(chalk.green(`成功创建 ${chalk.bold('init.go')} 文件`));
151
+
152
+ // 创建 _cmd/main.go 文件
153
+ const cmdDir = path.join(projectDir, '_cmd');
154
+ const mainGoPath = path.join(cmdDir, 'main.go');
155
+ const mainGoTemplatePath = path.join(__dirname, '../templates/main.go.ejs');
156
+ const mainGoContent = await ejs.renderFile(mainGoTemplatePath, { projectName });
157
+ await fs.writeFile(mainGoPath, mainGoContent);
158
+ console.log(chalk.green(`成功创建 ${chalk.bold('main.go')} 文件`));
159
+
160
+ // 创建 global/config.go 文件
161
+ const globalDir = path.join(projectDir, 'global');
162
+ const configGoPath = path.join(globalDir, 'config.go');
163
+ const configGoTemplatePath = path.join(__dirname, '../templates/config.go.ejs');
164
+ const configGoContent = await ejs.renderFile(configGoTemplatePath, { projectNameUpper });
165
+ await fs.writeFile(configGoPath, configGoContent);
166
+ console.log(chalk.green(`成功创建 ${chalk.bold('config.go')} 文件`));
167
+
168
+ // 创建 cron/cron.go 文件
169
+ const cronDir = path.join(projectDir, 'cron');
170
+ const cronGoPath = path.join(cronDir, 'cron.go');
171
+ const cronGoTemplatePath = path.join(__dirname, '../templates/cron.go.ejs');
172
+ const cronGoContent = await ejs.renderFile(cronGoTemplatePath, {});
173
+ await fs.writeFile(cronGoPath, cronGoContent);
174
+ console.log(chalk.green(`成功创建 ${chalk.bold('cron.go')} 文件`));
175
+
176
+ // 运行 go mod tidy
177
+ console.log(chalk.blue('整理 Go 模块依赖中 (go mod tidy),请稍候...'));
178
+ await runGoModTidy(projectDir);
179
+ console.log(chalk.green('成功整理 Go 模块依赖'));
180
+
181
+ // 提示用户如何运行项目
182
+ console.log(chalk.blue(`\n项目 ${chalk.bold(projectName)} 已成功创建在 ${chalk.bold(projectDir)} 目录下`));
183
+ console.log(chalk.yellow('\n运行项目的方法:'));
184
+ console.log(chalk.green(`1. 进入项目目录: cd ${projectName}`));
185
+ console.log(chalk.green(`2. 使用 Go 命令运行项目:`));
186
+ console.log(chalk.cyan(` go run _cmd/main.go`));
187
+ console.log(chalk.green(`\n或者直接编译并运行:`));
188
+ console.log(chalk.cyan(` go build -o ${projectName} _cmd/main.go && ./${projectName}`));
189
+ } catch (error) {
190
+ console.error(chalk.red('初始化项目时出错:'), chalk.redBright(error.message));
191
+ }
192
+ };
193
+
194
+ export default initModule;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gorig-cli",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "type": "module",
5
5
  "description": "gorig构建工具",
6
6
  "main": "bin/cli.js",
@@ -0,0 +1,13 @@
1
+ package global
2
+
3
+ import (
4
+ configure "github.com/jom-io/gorig/utils/cofigure"
5
+ )
6
+
7
+ var (
8
+ SysName = ""
9
+ )
10
+
11
+ func init() {
12
+ SysName = configure.GetString("sys.name", "<%= projectNameUpper %>")
13
+ }
@@ -0,0 +1,45 @@
1
+ sys:
2
+ name: <%= projectNameUpper %>
3
+ mode: <%= mode %>
4
+
5
+ api:
6
+ rest:
7
+ addr: :9527
8
+
9
+ #db:
10
+ # prefix: <%= projectPrefix %>_
11
+
12
+ #mongo:
13
+ # Main:
14
+ # uri: mongodb://addr
15
+ # auth:
16
+ # need: true
17
+ # source: db_source
18
+ # user: user
19
+ # password: pwd
20
+ # db:
21
+ # name: db_name
22
+ #
23
+ #Mysql:
24
+ # Main:
25
+ # GormInit: 1
26
+ # SlowThreshold: 30 # 慢 SQL 阈值(sql执行时间超过此时间单位(秒),就会触发系统日志记录)
27
+ # Write:
28
+ # Host: addr
29
+ # DataBase: db_name
30
+ # Port: 3306
31
+ # User: user
32
+ # Pass: pwd
33
+ # Charset: "utf8"
34
+ # SetMaxIdleConns: 10
35
+ # SetMaxOpenConns: 128
36
+ # SetConnMaxLifetime: 60 # 连接不活动时的最大生存时间(秒)
37
+
38
+ #redis:
39
+ # addr: localhost:6379
40
+ # password:
41
+ # db: 0
42
+
43
+ #notify:
44
+ # dingding:
45
+ # token: xxxxx
@@ -0,0 +1,17 @@
1
+ package cron
2
+
3
+ import (
4
+ "fmt"
5
+ "github.com/jom-io/gorig/cronx"
6
+ "github.com/jom-io/gorig/utils/logger"
7
+ "time"
8
+ )
9
+
10
+ func test() {
11
+ logger.Info(nil, fmt.Sprintf("hello, now is %s", time.Now().Format("2006-01-02 15:04:05")))
12
+ }
13
+
14
+ func init() {
15
+ // 每隔10s运行
16
+ cronx.AddTask("*/10 * * * * *", test)
17
+ }
@@ -0,0 +1,22 @@
1
+ package domain
2
+
3
+ import (
4
+ "github.com/jom-io/gorig/httpx"
5
+ "github.com/jom-io/gorig/serv"
6
+ configure "github.com/jom-io/gorig/utils/cofigure"
7
+ "github.com/jom-io/gorig/utils/sys"
8
+ )
9
+
10
+ func init() {
11
+ err := serv.RegisterService(
12
+ serv.Service{
13
+ Code: "<%= projectNameUpper %>_HTTP",
14
+ PORT: configure.GetString("api.rest.addr", ":9527"),
15
+ Startup: httpx.Startup,
16
+ Shutdown: httpx.Shutdown,
17
+ },
18
+ )
19
+ if err != nil {
20
+ sys.Exit(err)
21
+ }
22
+ }
@@ -0,0 +1,12 @@
1
+ package main
2
+
3
+ import (
4
+ "github.com/jom-io/gorig/bootstrap"
5
+ )
6
+
7
+ import _ "<%= projectName %>/cron"
8
+ import _ "<%= projectName %>/domain"
9
+
10
+ func main() {
11
+ bootstrap.StartUp()
12
+ }