One, ptm-cli instructions
project template manager cli
Scaffolding tool for a project template / project management, with 添加模板/项目
, 编辑模板/项目
, 删除模板/项目
, 查看模板/项目
and 下载项目
, and根据模板初始化项目
other functions.
1. Features
-
ptm-cli is compatible
github
withgitee码云
:At present, many self-developed scaffolds can only download templates/projects on github (underlying use
download-git-repo
). With the development and growth of domestic code cloud, many domestic developers also carry out code management on code cloud and are compatible with gitee. Necessary; currently there are no existing scaffold wheels compatible with Mayun! -
Full management functions :
Most scaffolding only initializes and downloads a certain template, and only has the specified initialization function; ptm-cli can do it
模板和项目进行管理
, not only from由添加删除开源的优秀项目
(such as vue), but also添加删除编辑自己开发的项目模板
;
2. Installation
$ npm install ptm-cli -g
3. Use
1) Basic help commands
After installation, enter the corresponding commands on the computer terminal to view and perform related operations.
# 查看脚手架可执行的相关命令语句
$ ptm
# 查看当前版本
$ ptm -V
# 查看帮助
$ ptm -h
2) Add template/project
input the command:
$ ptm-add
Enter relevant information as prompted by the terminal:
Template name : added template
自定义命名
(recommended to use citation);url : template / project
github
or码云
onhttps
/ssh
clone address link;branch : the github or code cloud where the template/project is located
分支名
(master by default);delGitInfo : Whether to delete the template/project
原作者git的开发信息
(default true delete), the default setting for template management is recommended to be true, that is, the initialization template does not contain other people’s git information, for project management (own project) it is recommended to keep the git related to your own development information;description : description of the template/project (empty by default);
example:
xxx % ptm-add
? 请输入模板名称 vpblogs
? 请输入模板地址(https/ssh) [email protected]:goodloving/vpblogs.git
? 请输入模板分支(默认master) master
? 是否删除模板中.git信息(默认删除) true
? 请输入模板描述(默认为空) 基于vuepress创建个人博客主页的模板工程
添加模板成功!
最终的模板列表为:
vpblogs
url:[email protected]:goodloving/vpblogs.git
branch:master
description:基于vuepress创建个人博客主页的模板工程
delGitInfo:true
xxx %
3) Edit template/project
input the command:
$ ptm-edit templateName key content
Enter relevant information as prompted by the terminal:
templateName : I
添加过的模板/项目名
;key : The template/project you want to edit
关键信息
, including: url , branch , delGitInfo , description ;content :
内容进行编辑替代
the content corresponding to the keyword ;
Example (modify delGitInfo information of template vpblogs):
xxx % ptm-edit vpblogs delGitInfo false
修改模板成功!
最终的模板列表为:
vpblogs
url:[email protected]:goodloving/vpblogs.git
branch:master
description:基于vuepress创建个人博客主页的模板工程
delGitInfo:false
xxx %
4) View template/project
input the command:
$ ptm-list
example:
xxx % ptm-list
模板列表为:
vpblogs
url:[email protected]:goodloving/vpblogs.git
branch:master
description:基于vuepress创建个人博客主页的模板工程
delGitInfo:false
xxx %
5) Delete template/project
input the command:
$ ptm-del
example:
xxx % ptm-del
? 请输入要删除的模板名称 vpblogs
删除模板成功!
最终的模板列表为:
xxx %
6) New/initialize project based on template
input the command:
$ ptm-init vpblogs testPTM
Example (new project testPTM based on template vpblogs):
xxx % ptm-init vpblogs testPTM
开始创建项目~
✔ 正在创建中···
项目创建成功~
开始你的项目开发!
xxx %
After the execution is complete 终端所在目录
, you can see the named testPTM
project file in the current window !
Two ptm-cli
scaffolding Development
1. Knowledge reserve
1)commander
A complete node.js 命令行解决方案
third-party npm library used to process input commands and write command line instructions in the terminal command line.
Common API:
- Declare the program variable
const { program } = require('commander');
- Command line output version number
program.version('0.0.1');
- Command prompt output
program.usage("\<command> [Options]");
- Command line output single command input standard prompt
program.command("ptm-add", "Add a template library!")
- Parse command line parameters
program.parse(process.argv);
- ···
2)inquirer
Processing 可交互
node.js embedded 命令行界面
third-party npm library.
Common API:
- Declare the inquiry variable
const inquirer = require('inquirer');
- Specific usage
inquirer
.prompt([
/ Insert questions that can be provided interactively /
])
.then(answers => {
// Input parameters received in the command line
})
.catch(error => {
// Get an error report
});- ···
3)git-clone
克隆
A git存储库
third-party npm library through shell commands .
Common API:
- Declare git-clone variables
const clone = require('git-clone');
- Specific usage
clone(repo, targetPath, [options], cb);
Clone the git repository of a repo path to the targetPath directory, the callback function cd is used to capture the clone result;
- Optional parameters:
- git: The binary path of git (optional).
- shallow: When true, the clone depth is 1 (optional).
- checkout: Switch to the current branch (optional).
4)chalk
Change 样式
the third-party npm library for terminal output .
Common API:
- Declare the chalk variable
const chalk = require('chalk');
- Specific usage
console.log(chalk.blue('Hello world!'));
5) now
Add an elegant 终端转轮
third-party npm library.
Common API:
- Declare the ora variable
const ora = require('ora');
- Specific usage
const spinner = ora('Prompt content···');
- Start showing the runner
spinner.start()
- Error/failure display runner
spinner.fail()
- Successful runner display
spinner.succeed()
- ···
6) rimraf
Package rm -rf
commands, used 删除文件和文件夹
by third-party npm libraries.
Common API:
- Declare the rimraf variable
const rm = require("rimraf").sync;
- Specific usage, delete the specified file/folder
rm(file, [opts], callback)
- ···
2. Initialize the project
New project folder PTM_CLI
, opens a terminal at the project folder performs the initialization operation npm init
, interact with the terminal to generate the information items contained in package.json
the file, in turn mounted 步骤1
in 6个
use to the third party libraries npm: npm install xxx -g
(writing can also be directly dependent on package.json
the is dependences
performed directly npm install
);
open package.json
file, add the terminal command sentence ( bin
the region):
{
"name": "ptm-cli",
···
"private": false,
"author": {
"name": "wawoweb",
"wechat(公众号)": "wawoweb / 哇喔WEB",
"wechat": "h17179797429",
"email": "[email protected]"
},
"bin": {
"ptm": "./bin/ptm.js",
"ptm-init": "./bin/ptm-init.js",
"ptm-list": "./bin/ptm-list.js",
"ptm-add": "./bin/ptm-add.js",
"ptm-del": "./bin/ptm-del.js",
"ptm-edit": "./bin/ptm-edit.js"
},
···
"dependencies": {
"chalk": "^4.1.0",
"commander": "^6.2.1",
"git-clone": "^0.1.0",
"inquirer": "^7.3.3",
"ora": "^5.1.0",
"rimraf": "^3.0.2"
}
}
At the same time, create a new directory under the project folder bin
, and create package.json
the corresponding 6 files under the bin folder :
./bin/ptm.js 终端命令ptm执行文件
./bin/ptm-init.js 终端命令ptm-init执行文件(根据模板初始化项目)
./bin/ptm-list.js 终端命令ptm-list执行文件(查看当前模板列表)
./bin/ptm-add.js 终端命令ptm-add执行文件(添加新的模板)
./bin/ptm-del.js 终端命令ptm-del执行文件(删除指定模板)
./bin/ptm-edit.js 终端命令ptm-edit执行文件(编辑指定模板指定信息内容)
Finally, create a new template storage file in the root directory template.json
. The project directory structure is as follows:
3. Function development
Add at the top bin目录
of the six under the above new creation : Configure #!/usr/bin/env node, which solves the different node paths of different systems and allows the system to dynamically find the node to execute your script file.功能文件
#!/usr/bin/env node
1) ptm (scaffolding command prompt)
analysis:
When the user does not understand ptm-cli, input ptm to show the user the available command statements and meanings ( commander
);
Code (ptm.js):
#!/usr/bin/env node
const program = require("commander");
const package = require("../package.json");
// 定义当前版本
// 定义使用方法
// 定义五个指令
program
.version(package.version)
.usage("<command> [Options]")
.command("ptm-add", "新增一个模板库!")
.command("ptm-del", "删除一个模板库!")
.command("ptm-list", "查看模板库列表!")
.command("ptm-edit templatename key content", "修改模板库信息!")
.command("ptm-init templatename projectName", "基于模板库创建一个新的工程!");
// 解析命令行参数
program.parse(process.argv);
2) ptm-add (add template)
analysis:
Add the user-specified template to template.json and store it, you need to interact with the user ( inquirer
), which involves reading and writing of files ( fs
), and show the execution result to the user ( chalk
);
Code (ptm-add.js):
#!/usr/bin/env node
//交互式命令行库
const inquirer = require("inquirer");
//控制台样式库
const chalk = require("chalk");
//node内置文件模块库
const fs = require("fs");
//读取模板配置文件
const tpConfig = require(`${__dirname}/../template.json`);
// 打印模板列表的公共函数
const printPtmList = require("../utils").printPtmList;
//自定义交互式命令行的问答
let questions = [
{
name: "name",
type: "input",
message: "请输入模板名称",
validate(val) {
if (val === "") {
return "模板名不能为空!";
} else if (tpConfig[val]) {
return "模板名已经存在!";
} else {
return true;
}
},
},
{
name: "url",
type: "input",
message: "请输入模板地址(https/ssh)",
validate(val) {
if (val === "") return "模板地址不能为空!";
return true;
},
},
{
name: "branch",
type: "input",
message: "请输入模板分支(默认master)",
default: "master",
},
{
name: "delGitInfo",
type: "input",
message: "是否删除模板中.git信息(默认删除)",
default: true,
},
{
name: "description",
type: "input",
message: "请输入模板描述(默认为空)",
default: "",
},
];
inquirer.prompt(questions).then((answers) => {
// 获取用户输入的内容
let { name, url, branch, description, delGitInfo } = answers;
//过滤Unicode的字符
tpConfig[name] = {
url,
branch,
description,
delGitInfo,
};
// 将模板信息写入template.json文件中s
fs.writeFile(
`${__dirname}/../template.json`,
JSON.stringify(tpConfig),
"utf-8",
(err) => {
if (err) {
console.log(chalk.red(`\n添加模板失败:${err}\n`));
} else {
console.log(chalk.green("\n添加模板成功!\n"));
console.log("最终的模板列表为:");
printPtmList(tpConfig);
}
}
);
});
Template list printing function package (utils.js):
const chalk = require("chalk");
const printPtmList = (tpConfig) => {
//遍历模板展示出来
for (const key in tpConfig) {
if (tpConfig.hasOwnProperty(key)) {
const item = tpConfig[key];
console.log(chalk.blue(` ${key}`));
for (const i in item) {
if (item.hasOwnProperty.call(item, i)) {
const el = item[i];
console.log(chalk.blue(` ${i}:${el}`));
}
}
}
}
};
module.exports = {
printPtmList
};
3)ptm-list、ptm-del、ptm-edit
analysis:
- ptm-list: read template.json file (fs), output and print json format data (chalk);
- ptm-del: read the template.json file (fs), interact with the user (inquirer), delete the specified template information, and output the deleted result (chalk)
- ptm-edit: read the template.json file (fs), interact with the user (inquirer), specify the template information to modify (commander), and output the final modification result (chalk);
The code is simple (omitted)
4) ptm-init (initialize the project according to the template)
analysis:
Prompting the user to ptm-init
command the necessary parameters for 输入参数进行判断
reading template.json
information extraction template information based on new projects, from github
, or gitee(码云)
the clone git库
file is determined according to the configuration required 是否删除原作者的git开发信息
output init结果
!
Code
ptm-init.js
#!/usr/bin/env node
const program = require("commander");
const chalk = require("chalk");
const ora = require("ora");
const gitclone = require("git-clone");
const tpConfig = require(`${__dirname}/../template`);
const rm = require("rimraf").sync;
program.usage("templatename projectName").parse(process.argv);
//判断输入情况
if (program.args.length < 1) {
return program.help();
}
//输入参数提取
let templateName = program.args[0];
let projectName = program.args[1];
//参数校验
if (!tpConfig[templateName]) {
console.log(chalk.red("当前模板不存在!\n"));
return;
}
if (!projectName) {
console.log(chalk.red("新建项目名不能为空! \n"));
return;
}
let temp = tpConfig[templateName];
//提取模板的url
let url = temp.url;
//提取分支
let branch = temp.branch;
console.log(chalk.greenBright("\n开始创建项目~ \n"));
//显示加载图标
const spinner = ora("正在创建中···");
spinner.start();
//下载所需额外参数
let cloneOptions = {
checkout: branch,
shallow: branch === "master",
};
// 下载git上模板代码
gitclone(url, projectName, cloneOptions, (err) => {
if (err) {
spinner.fail();
console.log(chalk.red(`\n创建项目失败:${err}\n`));
} else {
if (temp.deldelGitInfo) {
// 删除.git相关文件
rm(projectName + "/.git");
}
//成功
spinner.succeed();
console.log(chalk.green("\n项目创建成功~ \n"));
console.log(chalk.green("开始你的项目开发!"));
}
});
4. npm release
-
1) Confirm whether the npm release content in package.json is complete and correct
- "name": "ptm-cli", //The name of the library published on npm
- "version": "1.0.0", //Current release version number (the xyz format stipulates: the version number of x is large, and the difference of the large version number means that it is not backward compatible; the small version number of y, the current version is greatly changed, down Compatible; z code minor changes or bug modifications)
- "description": "", //A brief description of the npm library
- "private": false, //Whether the setting is public
- "keywords": [], //Keyword settings for search on npm
- ···
-
2) npm login and release
- Go to the npm website to register an account;
- Terminal input
npm login
, enter the user name, password, and email address as prompted; - Enter
npm publish
release at the terminal to check whether the result is successfully released; - Forcibly withdraw the npm library released within 24 hours, enter
npm unpublish --force
;
- 3) npm release verification
- Enter the name of the published npm library in the npm website search, and you can find that it has been successfully published!
- Local download verification
Open the local terminal and enternpm install ptm-cli -g
the npm package to download and install the released npm package. After the installation, the custom command is valid!
- Local download verification
- Enter the name of the published npm library in the npm website search, and you can find that it has been successfully published!